SQLite static openDatabase database method error in Android
Asked Answered
O

2

5

I created a static method to access my database on one of my activities but I keep getting error on 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 have been getting sqlite3_open_v2("studentDB", &handle, 6, NULL) failed. Cant find what's wrong... I have also tried using MODE_WORLD_WRITEABLE. Currently using MODE_PRIVATEfor database creation. Please help me out!

Orchestrion answered 12/10, 2011 at 19:15 Comment(0)
E
7

First argument to openDatabase should be full path to db so if:

//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";

then you should call:

sampleDB =  SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.CREATE_IF_NECESSARY); 
Earthworm answered 12/10, 2011 at 19:29 Comment(3)
wow, you are right! I didnt expect I need to input the full path for static method. Usually, I will just do sampleDB = SQLiteDatabase.openOrCreateDatabase("studentDB", null); within the activity. First time trying out static methods. Thanks!Orchestrion
don't we have to put the extension "studentDB.db" or "studentDB.sqlite" ?Melena
Adding SQLiteDatabase.CREATE_IF_NECESSARY is what fixed my issue.Lampkin
H
5

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

File dbFile= myActivity.getDatabasePath("studentDB");
sampleDB = SQLiteDatabase.openDatabase(dbFile.getAbsolutePath(), null, SQLiteDatabase.CREATE_IF_NECESSARY);
Hath answered 27/4, 2012 at 11:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.