This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12个答案)
12个月前关闭。
我正在学习SQlite,并且有两个课程:
但我收到此错误:
代码是:
DatabaseHelper.java
MainActivity.java
在使用msqliteDatabase之前。
(12个答案)
12个月前关闭。
我正在学习SQlite,并且有两个课程:
DatabaseHelper
和MainActivity
。第一个负责数据库。我想在MainActivity
类中创建一个新表。但我收到此错误:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.database.sqlite.SQLiteDatabase.execSQL(java.lang.String)' on a null object reference
代码是:
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "ABC.db";
@SuppressLint("SdCardPath")
public static final String DBLOCATION = "/data/data/com.example.abc/databases/";
private Context mContext;
private SQLiteDatabase mDatabase;
public DatabaseHelper(Context context) {
super(context, DBNAME, null, 1);
this.mContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void openDatabase() {
String dbPath = mContext.getDatabasePath(DBNAME).getPath();
if (mDatabase != null && mDatabase.isOpen()) {
return;
}
mDatabase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
}
public void closeDatabase() {
if (mDatabase != null) {
mDatabase.close();
}
}
public List<ABCMODEL> getListABC() {
ABCModel abcModel = null;
List<ABCModel> abcModelList = new ArrayList<>();
openDatabase();
Cursor cursor = mDatabase.rawQuery("SELECT * FROM abctable ", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
abcModel = new ABCModel(cursor.getString(0),cursor.getString(0));
abcModelList.add(abcModel);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
return abcModelList;
}
}
MainActivity.java
DatabaseHelper mdatabaseHelper;
SQLiteDatabase msqliteDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mdatabaseHelper= new DatabaseHelper(this);
File database= getApplicationContext().getDatabasePath(DatabaseHelper.DBNAME);
if(false== database.exists()){
mdatabaseHelper.getReadableDatabase();
if(copyDatabase(this)){
Toast.makeText(this,"Copy database succes",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this,"Copy database error",Toast.LENGTH_SHORT).show();
return;
}
}
mdatabaseHelper.openDatabase();
String query;
query=
"CREATE TABLE abctable2(\n" +
"Text TEXT,\n" +
"Text2 TEXT\n" +
");";
msqliteDatabase.execSQL(query);
mdatabaseHelper.closeDatabase();
}
最佳答案
您没有实例化msqliteDatabase,因此在尝试msqliteDatabase.execSQL(query);
时它将为null。
使用SQLiteDatabase msqliteDatabase;
仅为SQLiteDatabase对象保留内存,它不会实例化它,因此尚未设置/初始化指向该对象的指针,因此为null。
您可以添加
msqliteDatabase = mdatabaseHelper.getWritableDatabase();
在使用msqliteDatabase之前。
关于java - 尝试在空对象引用上调用虚拟方法'void android.database.sqlite.SQLiteDatabase.execSQL(java.lang.String)',我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56934603/
10-11 10:51