我做一个简单的练习,以建立一个代理来访问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地方初始化你的数据库代理,因为它的上下文是空的。请分享该课程从何处开始的功能代码。 –