在上一篇文章中,有一种方法可以创建我的SQLiteDatabse的单个实例,然后在我的应用程序中简单地引用它。我无法弄清楚如何告诉它我的数据库在哪里。由于我的数据库被写入SDCard,因此必须有一种方法告诉它应该使用哪个数据库?以下是代码:
public class DatabaseManager {
private int mOpenCounter;
private static DatabaseManager instance;
private static SQLiteOpenHelper mDatabaseHelper;
private SQLiteDatabase mDatabase;
public static synchronized void initializeInstance(SQLiteOpenHelper helper) {
if (instance == null) {
instance = new DatabaseManager();
mDatabaseHelper = helper;
}
}
public static synchronized DatabaseManager getInstance() {
if (instance == null) {
throw new IllegalStateException(DatabaseManager.class.getSimpleName() +
" is not initialized, call initializeInstance(..) method first.");
}
return instance;
}
public synchronized SQLiteDatabase openDatabase() {
mOpenCounter++;
if(mOpenCounter == 1) {
// Opening new database
mDatabase = mDatabaseHelper.getWritableDatabase();
}
return mDatabase;
}
public synchronized void closeDatabase() {
mOpenCounter--;
if(mOpenCounter == 0) {
// Closing database
mDatabase.close();
}
}
}
我的实际数据库名为FooBase.db
static File directoryPath = new File(Environment.getExternalStorageDirectory().toString() + "/MyApp/database");
答案 0 :(得分:0)
您不需要明确提及数据库的路径。
默认情况下,所有Android应用程序都将其数据库存储在该位置
/data/data/packageName/
SQLiteOpenHelper - creating database on SD card