我正試圖將我創建的數據庫導出到手機的SD卡上,以便我可以在eclipse的DDMS模式下查看其內容。將Android數據庫保存到SD卡?
下面的代碼是從這樣一個問題:Making a database backup to SDCard on Android
但是,我不知道該如何對我的應用程序中使用此代碼?即我需要實例化類嗎?如果是的話,在哪裏?
package com.example.multapply;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
public class ExportDatabaseFileTask extends AsyncTask<String, Void, Boolean> {
//Default constructor
public ExportDatabaseFileTask() {
}
//delete if necessary
private final ProgressDialog dialog = new ProgressDialog(null);
// 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) {
//original database file location
File dbFile = new File(Environment.getDataDirectory()
+ "/data/com.example.multapply/databases/MultapplyDatabase.db");
//the destination file location
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(null, "Export successful!", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(null, "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();
}
}
}
編輯(我目前用於添加到數據庫的代碼):
//Adding the score to the database from
DatabaseHelper db = new DatabaseHelper(this);
db.addScore(new Score(UserName.getUserName(), score, System.currentTimeMillis()));
這個'新的ProgressDialog(null);'是不會工作的。 – njzk2
(並且這兩者都不是'Toast.makeText(null') – njzk2
進度對話框和吐司是否需要進行備份? – RYJava2014