我创建了一个从SQLite获取数据并在textview中显示的方法但是当按下按钮时显示应用程序崩溃。守则:
public void ViewData(){
btnControler.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Cursor data = peopleDB.showData();
if (data.getCount() == 0) {
display("","");
return;
}
StringBuffer buffer = new StringBuffer();
StringBuffer buffer2 = new StringBuffer();
while (data.moveToNext()) {
display(buffer.append("Name:\t " + data.getString(1) + "\n").toString(),buffer2.append("Email:\t " + data.getString(2) + "\n").toString());
}
}
});
}
public void display(String name, String email){
TVusername.append(name);
rphone.append(email);
}
错误被指定到第五行Cursor data = peopleDB.showData();
05-25 23:37:03.439 916-916/info.devexchanges.googlelocation E/AndroidRuntime: FATAL EXCEPTION: main
Process: info.devexchanges.googlelocation, PID: 916
java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor info.devexchanges.googlelocation.DatabaseHelper.showData()' on a null object reference
at info.devexchanges.googlelocation.LocationActivity$5.onClick(LocationActivity.java:473)
at android.view.View.performClick(View.java:5184)
at android.view.View$PerformClick.run(View.java:20910)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
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:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
答案 0 :(得分:1)
您可能缺少使用以下命令获取SQLiteDatabase引用:
DatabaseHelper databasehelper = new DatabaseHelper(getApplicationContext());
SQLiteDatabase peopleDB = databasehelper.getWritableDatabase();
您可以在this link中看到一个示例。