mercredi 2 septembre 2015

Read from sqlite db in Drive and write it to local db - Android

I am developing an application which requires sqlite database to be backed up to Google Drive (which I accomplished). Now I want to restore that database back into my application and load it at runtime from SD card.

I am reading the contents of database from Google Drive using android-demo/RetrieveContentsActivity on GitHub and I am using the following code to write it back in my database

ListView onItemClickListener

               Drive.DriveApi
                    .getFile(api,
                            mResultsAdapter.getItem(position).getDriveId())
                    .openContents(api, DriveFile.MODE_READ_ONLY, null)
                    .setResultCallback(contentsOpenedCallback);

ResultCallBack

final private ResultCallback<ContentsResult> contentsOpenedCallback = new ResultCallback<ContentsResult>() {
    @Override
    public void onResult(ContentsResult result) {
        if (!result.getStatus().isSuccess()) {
            return;
        }

        if (GetFileFromDrive(result)) {
            Toast.makeText(getApplicationContext(), "File restored",
                    Toast.LENGTH_LONG).show();
        }
    }
};

GetFileFromDrive

private boolean GetFileFromDrive(ContentsResult result) {
    Contents contents = result.getContents();
    InputStream mInput = contents.getInputStream();
    OutputStream mOutput;
    boolean restoreSuccess = false;

    try {
        mOutput = new FileOutputStream(getDatabasePath(DB_NAME));
        byte[] mBuffer = new byte[1024];
        int mLength;
        while ((mLength = mInput.read(mBuffer)) > 0) {
            mOutput.write(mBuffer, 0, mLength);
        }

        mOutput.flush();

        mInput.close();
        mOutput.close();
        restoreSuccess = true;
    } catch (FileNotFoundException e) {
        // TODO: Log exception
        Log.e("error_filenotfound", "" + e.getLocalizedMessage());
    } catch (IOException e) {
        // TODO: Log Exception
        Log.e("error_io", "" + e.getLocalizedMessage());
    }

    return restoreSuccess;
}

The problem is that it deletes the already existing data in my sqlite and empties my sqlite completely. I have tried to find this issue on Google but none came close to helping me.

This guy - Google Drive Android api - Downloading db file from drive - is trying to do the same but he says that he replaced openContents with open. I tried that but it gives an error that The method open(GoogleApiClient, int, null) is undefined for the type DriveFile.

Any sort of help will be appreciated, please. I have been stuck on this for almost a week now and I am getting annoyed.

Aucun commentaire:

Enregistrer un commentaire