java.lang.NullPointerException
at com.example.notepad.MyAdapter.getCount(MyAdapter.java:29)
at android.widget.ListView.setAdapter(ListView.java:480)
at com.example.notepad.MainActivity.onCreate(MainActivity.java:44)
在 MainActivity.onCreate 中:
List<UserInfo> liUse; // 只有聲明,未初始化,值為 null
adapter = new MyAdapter(this, liUse); // 傳入 null
listView.setAdapter(adapter); // ListView 內部調用 getCount() → liUse.size() → NPE
List<UserInfo> liUse = new ArrayList<>(); // 空列表而非 null
public MyAdapter(Context c, List<UserInfo> userInfos) {
this.context = c;
this.userInfos = (userInfos != null) ? userInfos : new ArrayList<>();
}
@Override
public int getCount() {
return (userInfos != null) ? userInfos.size() : 0;
}
shuaxin() 中調用 adapter.notifyDataSetChanged() 替代 notifyDataSetInvalidated(),後者會重置選中位置;selectAll() 返回 liUse 但實際構建的是局部變量 ls,修為 return ls;;ViewHolder 模式優化 getView,避免重複 findViewById;RecyclerView + ListAdapter 獲得 DiffUtil 自動動畫與穩定性。| 問題代碼 | 修正代碼 |
|---|---|
List<UserInfo> liUse; | List<UserInfo> liUse = new ArrayList<>(); |
return liUse; (selectAll) | return ls; |
notifyDataSetInvalidated() | notifyDataSetChanged() |
集合聲明即初始化 是避免 NPE 的鐵律。Adapter 構造函數與 getCount 均應做空值防護。配合 notifyDataSetChanged 正確刷新 UI。