SQLite static openDatabase error in Android

I created a static method to access my database using one of my actions, but I keep getting an error when opening the database.

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(); 

I get sqlite3_open_v2("studentDB", &handle, 6, NULL) failed . I can not find what is wrong ... I also tried using MODE_WORLD_WRITEABLE . Currently using MODE_PRIVATE to create the database. Please help me!

+4
source share
2 answers

The first argument to openDatabase should be the full path to db, so if:

 //The Android default system path of your application database. private static String DB_PATH = "/data/data/YOUR_PACKAGE/databases/"; private static String DB_NAME = "studentDB"; 

then you should call:

 sampleDB = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.CREATE_IF_NECESSARY); 
+5
source

Use the ContextWrapper # getDatabasePath (java.lang.String) method and pass the result to SQLiteDatabase.openDatabase :

 File dbFile= myActivity.getDatabasePath("studentDB"); sampleDB = SQLiteDatabase.openDatabase(dbFile.getAbsolutePath(), null, SQLiteDatabase.CREATE_IF_NECESSARY); 
+2
source

All Articles