Google drive to back up and restore database and shared preferences of Android application

半世苍凉 提交于 2019-11-28 17:20:31

The answer applies to both your SQLite dbase file and to your Shared Prefs.

First, turn anything you want to save into byte[] buffer. Here is an example for 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 file to byte[] buffer).

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

To get it back, start with 'Retrieve contents' just replace the BufferBuilder, StringBuilder with your own InputStream reader that produces the data you place back into your SQLite file. Something similar to :

  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 stream into a file)

Sorry, I'm giving you only high level ideas, I tried to pull functional snippets from my code, but it is so tangled that I would have to copy half of my stuff here.

Turns out the only issue was creating the file before actualy adding data to it. Called 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 taking the effort to help guys !

I will definitely take a look at your SQLiteExample @seanpj. Will get back if i find it as a better solution.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!