我做一個簡單的練習,以建立一個代理來訪問SQLite的,我的主要活動是:機器人工作室錯誤:「顯示java.lang.NullPointerException:試圖調用虛擬方法......」
package com.example.mauro.localtest;
import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
public class MainActivity extends Activity {
DbBroker db = new DbBroker(this, "my_database", null, 1);
SQLiteDatabase sqldb = db.getWritableDatabase();
public int test = db.insertTest("New test", "Test created from app");
}
雖然DbBroker類:
package com.example.mauro.localtest;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Mauro on 09/06/2016.
*/
public class DbBroker extends SQLiteOpenHelper {
public DbBroker(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase arg0) {
arg0.execSQL("create table tests (id INTEGER PRIMARY KEY, publicid INTEGER, testname TEXT, description TEXT");
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
}
public int insertTest(String name, String desc){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues vals = new ContentValues();
vals.put("testname", name);
vals.put("description", desc);
return (int) db.insert("tests", null, vals);
}
}
當我運行該項目,該錯誤將停止應用程序:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.mauro.localtest/com.example.mauro.localtest.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory, android.database.DatabaseErrorHandler)' on a null object reference
誰能幫我unders問題在哪裏?
您是否定義了清單中的活動? –
我建議你通過更改代碼DbBroker db = new DbBroker(getActivity(),my_database,null,1)來嘗試一次。 截至目前我看到只有上下文是null的候選人。 我發現了一個類似的問題:http://stackoverflow.com/questions/30064080/android-app-crashes-on-startup-sqlite-nullpointerexception-in-contactsfragment http://stackoverflow.com/questions/29545524/android-nullpointerexception-unable-to-load-database-into-listview -a-fra 希望它可以解決你的問題。 – pbajpai21
我想你是在womg地方初始化你的數據庫代理,因爲它的上下文是空的。請分享該課程從何處開始的功能代碼。 –