mardi 31 mars 2015

Share SQLite database from Android app, without intermediate copy

I want to allow users of my Android app to export the SQLite database file for content they create. My current solution copies the file to private storage (/data/data/http://ift.tt/1CtvgdC), then creates a URI for this file and opens the Share dialog. This is working, allowing me to export the database file using Dropbox, for example. Here is the code I'm using, partially adapted from http://ift.tt/1GJdeqL -



private void exportContent() {
copyContentToPrivateStorage();

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("application/octet-stream");

Uri uri = new FileProvider().getDatabaseURI(this);

intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

startActivity(Intent.createChooser(intent, "Backup via:"));
}

private void copyContentToPrivateStorage() {
// From http://ift.tt/1GJdeqL
try {
File data = Environment.getDataDirectory();
File sd = getFilesDir();

if (sd.canWrite()) {
String currentDBPath = "//data//http://ift.tt/1CtviC9";
String backupDBPath = "Content.db";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);

if (currentDB.exists()) {
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
}
} catch (Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
}

public class FileProvider extends android.support.v4.content.FileProvider {

public Uri getDatabaseURI(Context c) {
File exportFile = new File(c.getFilesDir(), "Content.db");
Uri uri = getUriForFile(c, "com.package.name.fileprovider", exportFile);

c.grantUriPermission("*", uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);

return uri;
}
}


It seems like I should be able to directly create a URI from the existing database path, instead of doing an intermediate copy. Is there a way to do this?


I could keep doing the intermediate copy, but I believe it would be bad practice to leave the second copy of the database in the data directory longer than necessary. Is there a way to clean it up and delete it after the chosen app has finished using the URI to share the file?


Aucun commentaire:

Enregistrer un commentaire