You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Fragment中调用Glide加载图片报空指针异常导致应用崩溃如何解决?

问题原因

你遇到的崩溃是典型的异步请求生命周期不同步问题:Firestore的get()请求是异步执行的,当请求结果返回时,你的Account Fragment可能已经因为底部导航切换、用户退出页面等原因和Activity解绑,此时getContext()返回null,Glide调用就触发了报错。另外你当前的代码还存在profileImage空指针的潜在风险:如果Firestore返回的profile字段为null,调用profileImage.equals("")会直接崩溃。

解决方案

按以下步骤修改即可解决:

  1. 优先用View作为Glide的上下文载体,代替Fragment/Activity上下文:如果View已经和页面解绑,Glide会自动丢弃加载任务,不会触发崩溃
  2. 所有异步回调里操作UI/调用上下文前,先判断Fragment是否仍处于附着状态、相关控件是否非空
  3. 用TextUtils.isEmpty()判空字符串,避免空指针

修改后的核心代码示例:

// 把Firestore请求的Task存为成员变量,方便销毁时取消
private Task<DocumentSnapshot> userInfoTask;

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

    currentUser = FirebaseAuth.getInstance().getCurrentUser();

    fullNameTextPP = view.findViewById(R.id.full_name_nav_header);
    mobileNoTextPP = view.findViewById(R.id.mobileNo_nav_header);
    profileView = view.findViewById(R.id.profile_images_nav_header);
    addProfile = view.findViewById(R.id.addProfile__nav_header);

    
    if (currentUser == null) {
        fullNameTextPP.setVisibility(View.GONE);
        mobileNoTextPP.setVisibility(View.GONE);
        profileView.setVisibility(View.GONE);
        addProfile.setVisibility(View.GONE);
    } else {
        userInfoTask = FirebaseFirestore.getInstance().collection("USERS").document(currentUser.getUid())
                .get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                // 先判断Fragment仍附着、控件非空再操作
                if (!isAdded() || profileView == null || fullNameTextPP == null || addProfile == null || mobileNoTextPP == null) {
                    return;
                }
                if (task.isSuccessful()) {
                    String fullNAme = task.getResult().getString("fullName");
                    String mobile = task.getResult().getString("phoneNumber");
                    String profileImage = task.getResult().getString("profile");

                    fullNameTextPP.setText(fullNAme);
                    mobileNoTextPP.setText(mobile);

                    if (TextUtils.isEmpty(profileImage)) {
                        addProfile.setVisibility(View.VISIBLE);
                    } else {
                        addProfile.setVisibility(View.INVISIBLE);
                        // 直接传入要加载的View,Glide会自动感知生命周期
                        Glide.with(profileView).load(profileImage).into(profileView);
                    }
                } else {
                    String error = task.getException() != null ? task.getException().getMessage() : "加载用户信息失败";
                    Toast.makeText(requireContext(), error, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    return view;
}

@Override
public void onDestroyView() {
    super.onDestroyView();
    // 页面销毁时取消未完成的请求,避免无效回调
    if (userInfoTask != null && !userInfoTask.isComplete()) {
        userInfoTask.cancel(true);
    }
}

额外优化说明

如果你的项目适配了AndroidX,也可以将getContext()替换为requireContext(),但仍需要配合isAdded()判断使用,避免抛出IllegalStateException。

内容的提问来源于stack exchange,提问作者Vijayee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 10:06:02