0

I'm creating an app that will let the user change his/her image by pressing the ImageView, the Image will be coming from his/her Gallery and will be uploaded in my FirebaseStorage. The user's Personal Details are uploaded separately in FirebaseDatabase and the ImageUrl will be added after. I'm getting the error java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.app.Activity.isDestroyed()' on a null object reference just after I selected the Image from the gallery and proceed uploading the image, but even with the error the image is still uploaded in my FirebaseStorage and the ImageUrl is updated in the user's Details. and restarting the app will actually show the Image that I was just uploaded. The error points out in the Glide.with(getActivity()) part. I had my Glide.with in my FirebaseDatabase.addValueEventListener.How can I resolve this?

Here is my partial code of onCreateView, onRequestPermissionsResult and onActivityResult

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    FrameLayout rootView = (FrameLayout)inflater.inflate(R.layout.fragment_tch_profile, container, false);

    mDataRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
             {
                tv_email.setText(dataSnapshot.child("email").getValue(String.class));
                tv_name.setText(dataSnapshot.child("name").getValue(String.class));
                tv_gs.setText(dataSnapshot.child("cassSection").getValue(String.class));
                if(dataSnapshot.hasChild("tImage")){
                    Glide.with(getActivity())
                            .load(dataSnapshot.child("tImage").getValue(String.class))
                            .crossFade()
                            .placeholder(R.mipmap.ic_loader)
                            .thumbnail(0.1f)
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .into(iv_image);
                }

            }
            else {
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Toast.makeText(getActivity(),"The read failed: " + databaseError.getCode(),Toast.LENGTH_SHORT).show();
        }
    });

    return rootView;
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    switch (requestCode) {
        case READ_EXTERNAL_STORAGE:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                callGallery();
            return;
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK) {

        mImageURI = data.getData();
        iv_image.setImageURI(mImageURI);
        StorageReference filePath = mStorageRef.child("userImage").child(mImageURI.getLastPathSegment());

        filePath.putFile(mImageURI).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                Uri downloadUri = taskSnapshot.getDownloadUrl();  //Ignore This error

                mDataRef.child("tImage").setValue(downloadUri.toString());

            }
        });
    }
}

private void callGallery() {
    Intent i = new Intent(Intent.ACTION_PICK);
    i.setType("image/*");
    startActivityForResult(i, GALLERY_INTENT);
}

And Here is the Logcat:

FATAL EXCEPTION: main
                                                                         Process: kayaba.akihiro.educ_games, PID: 4502
                                                                         java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.app.Activity.isDestroyed()' on a null object reference
                                                                             at com.bumptech.glide.manager.RequestManagerRetriever.assertNotDestroyed(RequestManagerRetriever.java:133)
                                                                             at com.bumptech.glide.manager.RequestManagerRetriever.get(RequestManagerRetriever.java:102)
                                                                             at com.bumptech.glide.Glide.with(Glide.java:653)
                                                                             at kayaba.akihiro.educ_games.TchProfile$3.onSuccess(TchProfile.java:169)
                                                                             at kayaba.akihiro.educ_games.TchProfile$3.onSuccess(TchProfile.java:161)
                                                                             at com.google.firebase.storage.zzi.zzi(Unknown Source)
                                                                             at com.google.firebase.storage.zzz.run(Unknown Source)
                                                                             at android.os.Handler.handleCallback(Handler.java:739)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                             at android.os.Looper.loop(Looper.java:148)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
a.kyaba
  • 25
  • 4
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – ADM Jan 28 '18 at 15:05
  • 1
    You need to remove the `ValueEventListener` when fragment is detached . – ADM Jan 28 '18 at 15:08
  • @ADM Thank you for your input, removing the ValueEventListener inside detach did the trick. Would you mind explaining it a little how did it solve the issue? – a.kyaba Jan 28 '18 at 15:25
  • 1
    Its Simple . You set `ValueEventListener` it will give you callback of data changed without caring of state of `Context` i.e your `Activity`. So need to remove it .And in your case once fragment is detached getActivity() will return null . – ADM Jan 28 '18 at 15:32

1 Answers1

2

As per @ADM comment I tried removing ValueEventListener when fragment is detached and it did solve the issue.

Here are the added Codes for future reference:

ValueEventListener mListener;
DatabaseReference mDataRef;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    FrameLayout rootView = (FrameLayout)inflater.inflate(R.layout.fragment_tch_profile, container, false);

    mListener = mDataRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
             {
             //SOME CODES HERE
             }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Toast.makeText(getActivity(),"The read failed: " + databaseError.getCode(),Toast.LENGTH_SHORT).show();
        }
    });

    return rootView;
}


    @Override
    public void onDetach() {
        super.onDetach();
        if(mDataRef!=null && mListener!=null){
            mDataRef.removeEventListener(mListener);
        }
    }
a.kyaba
  • 25
  • 4