a.kyaba
a.kyaba

Reputation: 25

Using Glide in Fragment with FirebaseDatabase and Storage resulting to Glide.with(getActivity) Null Object

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)

Upvotes: 0

Views: 1308

Answers (1)

a.kyaba
a.kyaba

Reputation: 25

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);
        }
    }

Upvotes: 2

Related Questions