我需要你的幫助,我完成了一個應用程序的編碼,但問題在於數據庫在系統中:/data/data/your.package.name,我試圖通過這個數據庫訪問SD卡,我已經看在這個論壇的解決方案,也有很多,但我不知道如何使它工作,例如:將數據庫導出到SD卡
private class ExportDatabaseFileTask extends AsyncTask<String, Void, Boolean> {
private final ProgressDialog dialog = new ProgressDialog(ctx);
// can use UI thread here
protected void onPreExecute() {
this.dialog.setMessage("Exporting database...");
this.dialog.show();
}
// automatically done on worker thread (separate from UI thread)
protected Boolean doInBackground(final String... args) {
File dbFile =
new File(Environment.getDataDirectory() + "/data/com.mypkg/databases/mydbfile.db");
File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File file = new File(exportDir, dbFile.getName());
try {
file.createNewFile();
this.copyFile(dbFile, file);
return true;
} catch (IOException e) {
Log.e("mypck", e.getMessage(), e);
return false;
}
}
// can use UI thread here
protected void onPostExecute(final Boolean success) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
if (success) {
Toast.makeText(ctx, "Export successful!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ctx, "Export failed", Toast.LENGTH_SHORT).show();
}
}
void copyFile(File src, File dst) throws IOException {
FileChannel inChannel = new FileInputStream(src).getChannel();
FileChannel outChannel = new FileOutputStream(dst).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
}
這是我應該添加給其他人的類嗎?以及如何執行? –
將它作爲活動課內的私人課程。創建一個實例:ExportDatabaseFileTask task = new ExportDatabaseFileTask()。執行它:task.execute。 – NigelK
非常感謝回覆,whish課程?主要的 ?或數據庫適配器? –