首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Android BaseAdapter getCount 空指針異常排查:List 未初始化導致

     編輯:程式設計疑難解答

異常堆疊

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<>();
}

方法三:getCount 防空

@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。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved