我正在构建一个联系人应用程序并为其创建了一个数据库。每次运行它时,它都会显示以下异常。
logcat错误示例:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
at com.example.joey.sqlite.MainActivity.onResume(MainActivity.java:48)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1257)
at android.app.Activity.performResume(Activity.java:6076)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3039)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3081)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2447)
at android.app.ActivityThread.access$800(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5389)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
我该如何解决?
报告错误在for循环中:
@Override
protected void onResume() {
DBHelper dbHelper = new DBHelper(this);
namesList = new ArrayList<String>();
for (int i=0; i< dbHelper.getAllContacts().size();i++){
namesList.add(dbHelper.getAllContacts().get(i).getName());
}
adapter = new ArrayAdapter(getApplicationContext(),android.R.layout.simple_list_item_1,namesList);
list.setAdapter(adapter);
super.onResume();
}
数据库读取方法示例:
public ArrayList<Contact> getAllContacts() {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<Contact> contactArrayList = new ArrayList<Contact>();
Cursor cur = db.rawQuery("select * from " + TABLE,null);
cur.moveToFirst();
while (cur.isAfterLast() == false) {
try {
Contact contact_new = new Contact();
contact_new.setName(cur.getString(cur.getColumnIndex(NAME)));
contact_new.setEmail(cur.getString(cur.getColumnIndex(EMAIL)));
contact_new.setPhone(cur.getString(cur.getColumnIndex(PHONE)));
contactArrayList.add(contact_new);
cur.moveToNext();
return contactArrayList;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
return null;
}
答案 0 :(得分:1)
只需在for循环上方添加此检查,以避免在数据库请求返回null时发生崩溃:
if (dbHelper.getAllContacts() != null) {
for(...) {...}
}