我在更改自定義databaseHelper.class
中的數據庫路徑時遇到了一些問題。因此,在開始時我將數據庫置於內部存儲的默認數據庫文件夾中,但現在我想將它放在files/documents/users/servername/data
中,但是當我更改初始化存儲路徑的字符串時,放置在那裏的數據庫爲空。我忘了提及,實際上我的應用程序的資產文件夾中有sqlite文件,並且將文件從那裏複製到我的內部存儲器中。因此,這裏是一塊代碼我使用的:Android更改數據庫路徑問題
private static final int DATABASE_VERSION = 1;
private static String DB_PATH_PREFIX = "/data/data/";
private static String DB_PATH_SUFFIX = "/databases/";
public UserDatabaseHelper(Context context, // String dbname,
CursorFactory factory, int version) {
super(context,"stampii_tpl.sqlite", factory, version);
this.context = context;
Log.i(TAG, "Create or Open database : " + "stampii_tpl.sqlite");
}
private static void copyDataBase(Context aContext)
throws IOException {
// Open your local db as the input stream
InputStream myInput = aContext.getAssets().open("stampii_tpl.sqlite");
// Path to the just created empty db
String outFileName = getDatabasePath(aContext);
Log.i(TAG, "Check if create dir : " + DB_PATH_PREFIX
+ aContext.getPackageName() + DB_PATH_SUFFIX);
// if the path doesn't exist first, create it
File f = new File(DB_PATH_PREFIX + aContext.getPackageName()
+ DB_PATH_SUFFIX);
if (!f.exists())
f.mkdir();
Log.i(TAG, "Trying to copy local DB to : " + outFileName);
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
Log.i(TAG, "DB (" + "stampii_tpl.sqlite" + ") copied!");
}
private static boolean checkDatabase(Context aContext) {
SQLiteDatabase checkDB = null;
try {
String myPath = getDatabasePath(aContext);
Log.i(TAG, "Trying to conntect to : " + myPath);
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
Log.i(TAG, "Database " + "stampii_tpl.sqlite" + " found!");
checkDB.close();
} catch (SQLiteException e) {
Log.i(TAG, "Database " + "stampii_tpl.sqlite" + " does not exists!");
}
return checkDB != null ? true : false;
}
@SuppressWarnings("unused")
private static String getDatabasePath() {
return getDatabasePath(context);
}
private static String getDatabasePath(Context aContext) {
return DB_PATH_PREFIX + aContext.getPackageName() + DB_PATH_SUFFIX
+ "stampii_tpl.sqlite";
}
如果我試圖改變DB_PATH_SUFFIX
到:/files/documents/users/servername/data
,我有沒有空的,沒有其中創建表的數據庫在資產文件夾中的文件中。
那麼任何想法如何解決這個問題?
其實路徑到我的數據庫文件夾現在是'數據/數據/ app_package_name/databases'覆蓋
getDatabasePath()
方法,我想將文件複製到'數據/數據/ app_package_name/files/documents/users/data「,但實際上你的代碼甚至不會創建目錄並將空文件複製到'databases'目錄。任何想法可能是我的錯誤? –http://developer.android.com/reference/java/io/File.html#mkdirs%28%29可能對您有用。 – bos