我创建了一个静态方法来访问我的一个活动上的数据库,但是在打开数据库时我一直收到错误。
MainActivity
public static String getStudentData() {
SQLiteDatabase sampleDB = null;
try {
//NOT WORKING
sampleDB = SQLiteDatabase.openDatabase("studentDB",null, SQLiteDatabase.CREATE_IF_NECESSARY);
//Also not working
//sampleDB = SQLiteDatabase.openOrCreateDatabase("studentDB", null);
Cursor c = sampleDB.rawQuery("SELECT * FROM student where id='1'", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
//...
}while (c.moveToNext());
}
}
c.close();
} catch (Exception se ) {
} finally {
sampleDB.close();
}
}
OtherActivity
String student = MainActivity.getStudentData();
我一直在sqlite3_open_v2("studentDB", &handle, 6, NULL) failed
。不能发现什么是错的......我也试过使用MODE_WORLD_WRITEABLE
。目前正在使用MODE_PRIVATE
进行数据库创建。请帮帮我!
答案 0 :(得分:5)
openDatabase
的第一个参数应该是db的完整路径,所以如果:
//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/YOUR_PACKAGE/databases/";
private static String DB_NAME = "studentDB";
然后你应该打电话:
sampleDB = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.CREATE_IF_NECESSARY);
答案 1 :(得分:2)
使用方法ContextWrapper#getDatabasePath(java.lang.String)并将结果传递给SQLiteDatabase.openDatabase
:
File dbFile= myActivity.getDatabasePath("studentDB");
sampleDB = SQLiteDatabase.openDatabase(dbFile.getAbsolutePath(), null, SQLiteDatabase.CREATE_IF_NECESSARY);