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

如何修复Android中findViewById调用时的NullPointerException错误

修复java.lang.NullPointerException: findViewById调用空指针异常

错误原因分析

  1. 核心问题:root_view未初始化
    你声明了成员变量private View root_view;,但在onCreateView中仅返回了inflated的布局,未将布局实例赋值给root_view,导致后续displayCategory方法中调用root_view.findViewById()时,root_view为null,触发空指针异常。

  2. 适配器初始化顺序错误
    在displayCategory中,你先调用gridView.setAdapter(adapterCategory),但此时adapterCategory还未初始化(后续才执行new GalleryAdapter(...)),会导致潜在的空指针或无效状态。

  3. 冗余局部变量
    displayCategory中声明了局部GridView gridView,与成员变量重名,属于冗余代码。


修复步骤及代码

1. 初始化root_view

在onCreateView中,将inflated的布局赋值给root_view后再返回:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    root_view = inflater.inflate(R.layout.fragment_phones, container, false);
    return root_view;
}

2. 调整适配器初始化顺序

先创建适配器实例,再设置给GridView,同时简化视图可见性判断逻辑:

3. 可选优化:提前获取视图引用

在onViewCreated中提前获取GridView和LinearLayout的引用,避免重复调用findViewById。


完整修复后代码

public class FragmentCategory extends Fragment {
    private Call<CallbackHome> callbackCall = null;
    SharedPref sharedPref;
    private View root_view;
    private GalleryAdapter adapterCategory;
    private GridView gridView;
    private List<Category> mensWears;
    private GalleryAdapter adapter;
    private LinearLayout lyt_category; // 新增成员变量存储视图引用

    public FragmentCategory() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // 初始化root_view
        root_view = inflater.inflate(R.layout.fragment_phones, container, false);
        return root_view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 提前获取视图引用,避免重复findViewById
        gridView = root_view.findViewById(R.id.gridHolder);
        lyt_category = root_view.findViewById(R.id.lyt_category);

        this.callbackCall = RestAdapter.createAPI(getApiUrl).getHome(AppConfig.REST_API_KEY);
        this.callbackCall.enqueue(new Callback<CallbackHome>() {
            @Override
            public void onResponse(Call<CallbackHome> call, Response<CallbackHome> response) {
                CallbackHome responseHome = response.body();
                if (responseHome == null || !responseHome.status.equals("ok")) {
                    return;
                }
                displayData(responseHome);
            }

            private void displayData(CallbackHome responseHome) {
                displayCategory(responseHome.category);
            }

            @Override
            public void onFailure(Call<CallbackHome> call, Throwable th) {
                Log.e("onFailure", th.getMessage());
                if (!call.isCanceled()) {
                    // 可添加失败提示逻辑,比如Toast.makeText(getActivity(), "加载失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void displayCategory(List<Category> list) {
        // 先初始化适配器,再设置给GridView
        adapterCategory = new GalleryAdapter(getActivity(), new ArrayList<>(list));
        gridView.setAdapter(adapterCategory);

        // 简化可见性判断
        lyt_category.setVisibility(list.size() > 0 ? View.VISIBLE : View.GONE);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 11:30:52