Android Java中RecyclerView.setAdapter()空引用错误排查
报错信息
error: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)' on a null object reference
问题根因
空指针的核心触发原因是findViewById(R.id.get_property_entry_property_home)返回了null,后续对null对象调用setAdapter直接崩溃,返回null的具体原因有2个:
PropertyHome的onCreate方法中,调用findViewById之前没有执行setContentView()加载布局文件,Activity未初始化视图树,无法找到对应ID的控件。- 布局文件存在拼写错误:当前布局文件名为
activity_property_homr.xml,home被错拼为homr,就算补了setContentView,文件名不匹配也会导致布局加载失败。
另外布局还存在ScrollView嵌套RecyclerView的滑动冲突问题,就算空指针修复,列表也无法正常滚动展示。
修复方案
- 补全
setContentView调用,放在super.onCreate之后、所有findViewById逻辑之前,同时修正布局文件名拼写:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 必须先加载对应布局,后续findViewById才能正常找到控件 setContentView(R.layout.activity_property_home); try { recyclerView = (RecyclerView)findViewById(R.id.get_property_entry_property_home); String[] myRecycler = new String[5]; myRecycler[0] = "Recycler 1"; myRecycler[1] = "Recycler 2"; myRecycler[2] = "Recycler 3"; myRecycler[3] = "Recycler 4"; myRecycler[4] = "Recycler 5"; recyclerAdapter = new GetPropertyRecyclerViewAdapater(myRecycler); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setAdapter(recyclerAdapter); } catch(Exception e) { Toast.makeText(PropertyHome.this, "Error: " + e.toString(), Toast.LENGTH_LONG).show(); } }
- 将当前命名为
activity_property_homr.xml的布局文件重命名为activity_property_home.xml,同时把布局根节点的tools:context属性从.MainActivity修改为.PropertyHome,避免编辑器关联错误。 - 修复布局滑动冲突:RecyclerView本身已实现滑动能力,不需要额外嵌套ScrollView,直接去掉外层ScrollView即可,修改后的布局代码如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/linear_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:onClick="AppLogout" android:orientation="vertical" android:textAlignment="gravity" tools:context=".PropertyHome"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/get_property_entry_property_home" android:layout_width="match_parent" android:layout_height="match_parent" tools:itemCount="5" /> </LinearLayout>
适配器代码和列表item布局代码逻辑没有问题,完成以上修改后即可正常运行,空指针会消失,列表也能正常展示数据。
内容的提问来源于stack exchange,提问作者Meeth
相关产品推荐
相关产品推荐

