android-fragments 无法在getActivity()返回空值的尚未附加的视图或片段上启动加载

kuhbmx9i  于 2022-11-13  发布在  Android
关注(0)|答案(7)|浏览(136)

我正在使用FragmentStatePagerAdapter显示一个Activity中的大约5个片段。在每个Activity上,我都显示了我从FirebaseListAdapter/FirebaseRecyclerAdapter中获取的图像。由于它是FragmentStagePagerAdapter,因此即使相邻的视图/片段不可见,它们也将被初始化。如果以快速方式滚动标签(前进/后退)应用程序崩溃与上述错误。我发现了一些类似的问题在互联网上,但无法修复这个问题。我也得到如果我正在启动一个新的Activity(在Activity中,我在网格视图中显示来自firebase的图像)并立即关闭它(按下back按钮),则无法为一个已销毁的Activity启动加载错误。

adapt= new FirebaseListAdapter<MyClassStudent>(getActivity(), 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) {
                        Child child=dataSnapshot.getValue(Child.class);
                        uname.setText(child.getUsername());
                        Glide.with(getActivity()).load(child.getProfileImage()).into(profileImage);
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });
            }
        };

堆栈跟踪:

E/UncaughtException: java.lang.NullPointerException: You cannot start a load on a not yet attached View or a  Fragment where getActivity() returns null (which usually occurs when getActivity() is called before the Fragment is attached or after the Fragment is destroyed).
                         at com.bumptech.glide.util.Preconditions.checkNotNull(Preconditions.java:27)
                         at com.bumptech.glide.Glide.getRetriever(Glide.java:509)
                         at com.bumptech.glide.Glide.with(Glide.java:563)
                         at com.mycompany.educareteacher.FragmentStudents$2$1.onDataChange(FragmentStudents.java:184)
                         at com.google.firebase.database.zzp.onDataChange(Unknown Source)
                         at com.google.android.gms.internal.tl.zza(Unknown Source)
                         at com.google.android.gms.internal.vg.zzHW(Unknown Source)
                         at com.google.android.gms.internal.vm.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:5438)
                         at java.lang.reflect.Method.invoke(Native Method)
                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
D/FA: Logging event (FE): app_exception(_ae), Bundle[{firebase_event_origin(_o)=crash, firebase_screen_class(_sc)=ClassDetailActivity, firebase_screen_id(_si)=-4663411025690523798, timestamp=1500710706898, fatal=1}]
V/FA: Recording user engagement, ms: 3544
D/FA: Logging event (FE): user_engagement(_e), Bundle[{firebase_event_origin(_o)=auto, engagement_time_msec(_et)=3544, firebase_screen_class(_sc)=ClassDetailActivity, firebase_screen_id(_si)=-4663411025690523798}]
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.mycompany.com.educareteacher, PID: 5154
                  java.lang.NullPointerException: You cannot start a load on a not yet attached View or a  Fragment where getActivity() returns null (which usually occurs when getActivity() is called before the Fragment is attached or after the Fragment is destroyed).
                      at com.bumptech.glide.util.Preconditions.checkNotNull(Preconditions.java:27)
                      at com.bumptech.glide.Glide.getRetriever(Glide.java:509)
                      at com.bumptech.glide.Glide.with(Glide.java:563)
                      at com.mycompany.educareteacher.FragmentStudents$2$1.onDataChange(FragmentStudents.java:184)
                      at com.google.firebase.database.zzp.onDataChange(Unknown Source)
                      at com.google.android.gms.internal.tl.zza(Unknown Source)
                      at com.google.android.gms.internal.vg.zzHW(Unknown Source)
                      at com.google.android.gms.internal.vm.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:5438)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)

如何解决此问题?

rggaifut

rggaifut1#

你的片段在响应来自firebase之前被分离,所以在使用之前试着检查getActivity()是否为空

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

你可以像检查活动一样检查活动是否为空或不在其他地方。

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<MyClassStudent>(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) {

                }
            });
        }
    };
}
6qftjkof

6qftjkof2#

我更喜欢在用Glide加载图像之前使用片段的isAdded()方法。

ktecyv1j

ktecyv1j3#

1.在RecyclerView所在的活动上添加以下代码

public static Context context;

1.然后,在RecyclerView所在的同一活动的onCreate中,添加以下代码

context = getApplicationContext();

1.然后参考下图所示的滑动

Glide.with(YourActivity.context).load("Image Link").into(holder.YourImageView);
gudnpqoy

gudnpqoy4#

我也是这样发现的

public class NoteAdapter extends FirestoreRecyclerAdapter<Note,NoteAdapter.NoteHolder> {

Context context;

public NoteAdapter(@NonNull FirestoreRecyclerOptions<Note> options) {
    super(options);
}

@Override
protected void onBindViewHolder(@NonNull NoteHolder holder, int position, @NonNull final Note model) {

    context = holder.itemView.getContext();

    holder.r_tv.setText(model.getTitle());
    Glide.with(context).load(model.getImage()).into(holder.r_iv);

    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(context, CategoryProductActivity.class);
            MainActivity.myCategory2 = model.getTitle();
            MainActivity.myCategoryIcon2 = model.getImage();
            context.startActivity(i);
        }
    });

}

@NonNull
@Override
public NoteHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_category,parent,false);

    return new NoteHolder(v);
}

public static class NoteHolder extends RecyclerView.ViewHolder
{
    TextView r_tv;
    ImageView r_iv;

    public NoteHolder(@NonNull View itemView) {
        super(itemView);

        r_tv = itemView.findViewById(R.id.r_tv);
        r_iv = itemView.findViewById(R.id.r_iv);

    }
}
}
nimxete2

nimxete25#

只是使用片段。

if (getActivity != null) { 
    Glide.with(getActivity()).load(imageUrl).into(yourImageView); 
}
6ju8rftf

6ju8rftf6#

当您未在适配器的构造函数中添加上下文时,就会出现此问题,您可以轻松地解决此问题:-)
不要忘记在构造函数中添加此.context = context

public groupUserAdapter(Context context, ArrayList<Users> groupUsers) {
    this.groupUsers = groupUsers;
    this.context = context;
};
kb5ga3dv

kb5ga3dv7#

ArrayList<ClientData> clientData = new ArrayList<>();
int j=0;
for (String h:profileImg)
{
    ClientData clientItem = new ClientData();
    clientItem.setProfileImage(h);
    clientItem.setName(name[j]);
    clientItem.setAddress(location[j]);
    clientData.add(clientItem);
    j++;
    }
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplication(),RecyclerView.VERTICAL,false);
    recy_client.setLayoutManager(layoutManager);
    recy_client.setItemAnimator(new DefaultItemAnimator());
    clientAdp = new ClientAdp(getApplicationContext(),clientData);
    recy_client.setAdapter(clientAdp);

替换自

clientAdp = new ClientAdp(context,clientData);

结束日期

clientAdp = new ClientAdp(getApplicationContext(),clientData);

就我而言

相关问题