Google to backup and restore the database and general settings of the Android application

I need to back up my application, which would include backing up two databases, as well as general settings using the Google Drive APIs. I was able to authenticate for the application and also create a new folder in Drive using the following code:

public class MainActivity2 extends BaseDemoActivity { DriveId folderId; @Override public void onConnected(Bundle connectionHint) { super.onConnected(connectionHint); MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle("New folder").build(); Drive.DriveApi.getRootFolder(getGoogleApiClient()) .createFolder(getGoogleApiClient(), changeSet) .setResultCallback(folderCreatedCallback); } ResultCallback<DriveFolderResult> folderCreatedCallback = new ResultCallback<DriveFolderResult>() { @Override public void onResult(DriveFolderResult result) { if (!result.getStatus().isSuccess()) { showMessage("Error while trying to create the folder"); return; } folderId = result.getDriveFolder().getDriveId(); showMessage("Created a folder: " + result.getDriveFolder().getDriveId()); } }; } 

I am inserting a file using

 fileUri = Uri.fromFile(new java.io.File(Environment.getDataDirectory().getPath() + "/data/com.example.myapp/databases/mydb.db")); java.io.File fileContent = new java.io.File(fileUri.getPath()); FileContent mediaContent = new FileContent(getMimeType("db"), fileContent); File body = new com.google.api.services.drive.model.File(); body.setTitle(fileContent.getName()); body.setMimeType(getMimeType("db")); File file = service.files().insert(body, mediaContent).execute(); 

It works great.

I restore with

 AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { try { fileId="0B7Gol85MIbTJLTRxX1hZdDJjaEE"; credential.setSelectedAccountName("the same drive account"); service = getDriveService(credential); if (fileId != null) { File file = service.files().get(fileId).execute(); downloadFile(service, file); } else return null; } catch (Throwable tr) { } return fileId; } private void downloadFile(Drive service, File file) { InputStream mInput=null; FileOutputStream mOutput=null; if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) { try { HttpResponse resp = service.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl())).execute(); mInput = resp.getContent(); String outFileName = "file://"+Environment.getDataDirectory().getPath() + "/data/com.example.myapp/databases/InvoiceDataBase.db"; Log.e("com.example.myapp", "getDatabasePath="+ getDatabasePath("")); Log.e("com.example.myapp", "outFileName="+outFileName); // String outFileName = "../databases/" + "Quickpay.db"; mOutput = new FileOutputStream(outFileName); byte[] mBuffer = new byte[1024]; int mLength; while ((mLength = mInput.read(mBuffer)) > 0) { mOutput.write(mBuffer, 0, mLength); } mOutput.flush(); } catch (IOException e) { // An error occurred. e.printStackTrace(); // return null; } finally { try { //Close the streams if(mOutput != null){ mOutput.close(); } if(mInput != null){ mInput.close(); } } catch (IOException e) { Log.e("com.example.myapp", "failed to close databases"); } } } else { // The file doesn't have any content stored on Drive. // return null; Log.e("com.example.myapp", "No content on Drive"); } } 

When I back up again after recovery, I get

"/data/data/com.example.myapp/databases/mydb: open failed: ENOENT (There is no such file or directory)"

Now I need to upload the ".db" file to this folder, and also upload the general settings as an XML file. So my questions are:

  • How to upload my application database to this folder? resolved.
  • How to restore the original database file back to the application?
  • Can a user have full access to files when logging into their Google Drive account? Is there any other way to backup and restore? I can’t use the “Android backup services” because it cannot be a forced backup.

TIA.

+6
android sharedpreferences backup google-drive-sdk database-backups
source share
2 answers

It turns out that the only problem was creating the file before actually adding data to it. Called by the constructor of my dbhelper before writing to the db file.

used the following code:

 java.io.File dir = myContext.getDatabasePath("myDb.db"); mOutput = new FileOutputStream(outFileName); byte[] mBuffer = new byte[1024]; int mLength; while ((mLength = mInput.read(mBuffer)) > 0) { mOutput.write(mBuffer, 0, mLength); } mOutput.flush(); 

Thanks for helping the guys!

I will definitely look at your SQLiteExample @seanpj. Will come back if I find this the best solution.

+1
source share

The answer applies to both your SQLite database file and your shared prefiles.

First flip everything that you want to keep in the buffer []. Here is an example of SQLite dbase:

  byte[] getDBBytes() { Context ctx = getApplicationContext(); byte[] out = null; try { File from = ctx.getDatabasePath(ctx.getString(R.string.app_name)); if (from.exists()) out = strm2Bytes(new FileInputStream(from)); } catch (Exception e) {} return out; } 

(strm2Bytes () is a primitive that copies a file to the byte buffer []).

Then use DEMO ( 'Create a file in a folder' , 'Edit contents " ) to put the data in the Drive file. Keep these two processes separate, since you will only update the contents if the file exists.

To get it back, start with Get Content, 'just replace the BufferBuilder, StringBuilder with your own InputStream reader, which creates the data that you post back to your SQLite file. Something like:

  public static void setDB(InputStream is) { Context ctx = getApplicationContext(); try { File to = ctx.getDatabasePath(ctx.getString(R.string.app_name)); if (to.exists()) to.delete(); strm2File(is, to); } catch (Exception e) {} } 

(again, strm2FIle () is a primitive that copies a stream to a file)

Sorry, I only give you high-level ideas, I tried to get functional snippets out of my code, but it is so messy that I will have to copy half of my material here.

+3
source share

All Articles