2011-10-12 138 views
4

我创建了一个静态方法来访问我的一个活动的数据库,但我一直在打开数据库时出错。Android中的SQLite静态openDatabase数据库方法错误

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进行数据库创建。请帮助我!

回答

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); 
+0

哇,你是对的!我没想到我需要输入静态方法的完整路径。通常,我会在活动中执行'sampleDB = SQLiteDatabase.openOrCreateDatabase(“studentDB”,null);'。第一次尝试静态方法。谢谢! – newbie

+0

我们不必把扩展名为“studentDB.db”或“studentDB.sqlite”吗? –

2

使用方法ContextWrapper#getDatabasePath(java.lang.String)并将结果传递到SQLiteDatabase.openDatabase

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