I am attempting to export a database that I am creating to the SD card of my phone so that I can look at its contents in DDMS mode of eclipse.
The following code is from the question: Making a database backup to SDCard on Android
However, I am unsure how to use this code within my application? I.e. do I need to instantiate the class? And if so, where?
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();
}
}
}
Edit (my current code for adding to the database):
//Adding the score to the database from
DatabaseHelper db = new DatabaseHelper(this);
db.addScore(new Score(UserName.getUserName(), score, System.currentTimeMillis() ));