You cannot start a load on a not yet attached View or a Fragment where getActivity() returns null

前端 未结 5 1186
别跟我提以往
别跟我提以往 2021-01-13 21:26

I am using FragmentStatePagerAdapter to show around 5 fragments in an activity.On each activity I am showing the images which I am fetching from FirebaseListAdapter/Firebase

5条回答
  •  离开以前
    2021-01-13 22:08

    Your fragment is detached before response coming from firebase, So try to check getActivity() null before using that

    public void onDataChange(DataSnapshot dataSnapshot) {
        if (getActivity() == null) {
            return;
        }
        Child child = dataSnapshot.getValue(Child.class);
        uname.setText(child.getUsername());
        Glide.with(getActivity()).load(child.getProfileImage()).into(profileImage);
    }
    

    You can do like to check activity is null or not in other place.

    private Activity mActivity;
    
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    
        mActivity = getActivity();
    }
    
    @Override
    public void onDetach() {
        super.onDetach();
        mActivity = null;
    }
    
    private void doAction() {
        if (mActivity == null) {
            return;
        }
    
        adapt = new FirebaseListAdapter(mActivity, MyClassStudent.class, R.layout.mychild_grid_template, myRef) {
            @Override
            protected void populateView(final View v, MyClassStudent model, int position) {
                final TextView uname = (TextView) v.findViewById(R.id.mychild_uname);
    
                final CircleImageView profileImage = (CircleImageView) v.findViewById(R.id.mychild_image);
                studRef.child(model.getUsername()).addListenerForSingleValueEvent(new ValueEventListener() {
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        if (mActivity == null) {
                            return;
                        }
                        Child child = dataSnapshot.getValue(Child.class);
                        uname.setText(child.getUsername());
                        Glide.with(mActivity).load(child.getProfileImage()).into(profileImage);
                    }
    
                    @Override
                    public void onCancelled(DatabaseError databaseError) {
    
                    }
                });
            }
        };
    }
    

提交回复
热议问题