Android开发已获取API数据仍遇RecyclerView及TextView空指针异常
运行报错现象
- API数据拉取正常,界面加载时输出两类日志:
E/RecyclerView: No adapter attached; skipping layout,列表无渲染效果- 空指针异常:
void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
- 已参考同类公开问题的修复方案调整代码,问题仍复现
提交的代码片段
HomeFragment 代码
public class HomeFragment extends Fragment { private View view; private RecyclerView recyclerView; private ArrayList<Result> arrayList; private SwipeRefreshLayout refreshLayout; private PostAdapter postAdapter; private MaterialToolbar toolbar; private SharedPreferences userPref; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.layout_home,container,false); return view; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); init(); } private void init() { userPref = getContext().getApplicationContext().getSharedPreferences("user", Context.MODE_PRIVATE); recyclerView = (RecyclerView)view.findViewById(R.id.recyclerHome); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); refreshLayout = (SwipeRefreshLayout)view.findViewById(R.id.swipeHome); toolbar =(MaterialToolbar) view.findViewById(R.id.toolbarHome); ((HomeActivity)getContext()).setSupportActionBar(toolbar); getResults(); refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { getResults(); } }); } private void getResults() {//数据拉取逻辑可正常运行} }
PostAdapter 代码
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostsHolder>{ private ArrayList<Result> list; private Context context; public PostAdapter(Context context, ArrayList<Result> list) { this.list = new ArrayList<Result>(list); this.context = context; } @NonNull @Override public PostsHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_home, parent, false); return new PostsHolder(view); } @Override public void onBindViewHolder(@NonNull PostsHolder holder, int position) { Result result = list.get(position); holder.imgPostDate.setText(result.getDate()); } @Override public int getItemCount() { return list.size(); } public static class PostsHolder extends RecyclerView.ViewHolder{ private TextView imgPostProfile,imgPostName,imgPostDate; private ImageButton btnPostOption; public PostsHolder(@NonNull View itemView) { super(itemView); imgPostProfile =(TextView) itemView.findViewById(R.id.imgPostProfile); imgPostName = (TextView)itemView.findViewById(R.id.imgPostName); imgPostDate =(TextView) itemView.findViewById(R.id.imgPostDate); btnPostOption =(ImageButton) itemView.findViewById(R.id.btnPostOption); } } }
布局文件
主页面布局 layout_home.xml
<?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:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <com.google.android.material.appbar.MaterialToolbar android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/toolbarHome" android:elevation="1dp" android:theme="@style/Theme.MaCoSISBottomAppBar" app:title="" tools:targetApi="lollipop"> </com.google.android.material.appbar.MaterialToolbar> <androidx.swiperefreshlayout.widget.SwipeRefreshLayout android:layout_width="match_parent" android:id="@+id/swipeHome" android:layout_height="match_parent"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerHome" android:layout_height="match_parent" android:layout_width="match_parent"/> </androidx.swiperefreshlayout.widget.SwipeRefreshLayout> </LinearLayout>
列表项布局 layout_post.xml
<?xml version="1.0" encoding="utf-8"?> <androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:clickable="true" android:focusable="true" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="10dp"> <TextView android:id="@+id/imgPostProfile" android:layout_width="60sp" android:layout_height="60sp" android:background="@drawable/shape_circle" android:text="MC" android:gravity="center" android:textColor="@color/colorWhite" android:textSize="14sp" /> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:paddingLeft="6dp" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imgPostName" android:text="BBAD1252 Social Harmony and Business Skills Development" android:textColor="@color/colorBlack" android:textSize="14sp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imgPostDate" android:text="12 November 2020" android:textColor="@color/colorLightGrey" android:textSize="12dp" /> </LinearLayout> <ImageButton android:id="@+id/btnPostOption" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="8dp" android:background="@android:color/transparent" android:layout_gravity="center_vertical" android:src="@drawable/ic_baseline_more_vert_24"/> </LinearLayout> <View android:layout_width="match_parent" android:layout_height="1px" android:background="@color/colorLightGrey"/> </LinearLayout> </androidx.cardview.widget.CardView>
问题根因
- 适配器的
onCreateViewHolder方法加载了错误的布局文件:当前传入的是Fragment的根布局R.layout.layout_home,该布局内不存在imgPostProfile、imgPostName、imgPostDate、btnPostOption这些控件,因此ViewHolder初始化时所有控件实例均为null,后续调用setText时直接触发空指针异常。 - Fragment初始化流程中从未为RecyclerView绑定适配器:仅完成了LayoutManager的设置,既没有在拿到API返回数据后实例化
PostAdapter,也没有调用recyclerView.setAdapter()完成绑定,因此RecyclerView启动时检测到无适配器,输出No adapter attached; skipping layout日志并跳过布局渲染。
修复方案
- 修改
PostAdapter的onCreateViewHolder方法,将加载的布局替换为正确的列表项布局:
@Override public PostsHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_post, parent, false); return new PostsHolder(view); }
- 在
getResults方法拿到API返回的arrayList数据后,完成适配器实例化与绑定逻辑:
// 拿到API返回的完整arrayList后执行 if (postAdapter == null) { postAdapter = new PostAdapter(getContext(), arrayList); recyclerView.setAdapter(postAdapter); } else { postAdapter.updateData(arrayList); refreshLayout.setRefreshing(false); }
- 在适配器中补充数据更新公共方法,避免重复创建适配器造成内存抖动:
public void updateData(ArrayList<Result> newList) { this.list.clear(); this.list.addAll(newList); notifyDataSetChanged(); }
内容的提问来源于stack exchange,提问作者Achchuthan Yogarajah
相关产品推荐
相关产品推荐

