Drive API - Download/upload sql database

爷,独闯天下 提交于 2019-12-01 07:28:08

问题


Im currently working on downloading my sql database i uploaded with the drive api. There's one backup for sure, but when i try to open the file I get an error that the file is unable to open.

EDIT: I solved the problem above. Now i want to finally upload and download the sql database.

I found code on the internet to download and upload, but nothing worked.

How do i upload and download my sql database correctly?

My code:

public static void restoreDriveBackup() {
    Query query = new Query.Builder()
            .addFilter(Filters.eq(SearchableField.TITLE, GOOGLE_DRIVE_FILE_NAME))
            .build();

    Drive.DriveApi.query(api, query).setResultCallback(new ResultCallback<DriveApi.MetadataBufferResult>() {
        @Override
        public void onResult(DriveApi.MetadataBufferResult metadataBufferResult) {
            int count = metadataBufferResult.getMetadataBuffer().getCount() - 1;
            debug("Count: " + count);
            driveId = metadataBufferResult.getMetadataBuffer().get(count).getDriveId();
            debug("driveId: " + driveId);
            metadataBufferResult.getMetadataBuffer().release();

            mfile = Drive.DriveApi.getFile(api, driveId);

            mfile.open(api, DriveFile.MODE_READ_ONLY, new DriveFile.DownloadProgressListener() {
                @Override
                public void onProgress(long l, long l1) {
                    debug("Downloading... ("+l+")");
                }
            })
                    .setResultCallback(restoreContentsCallback);
        }
    });
}

public static void doDriveBackup() { Drive.DriveApi.newContents(api).setResultCallback(backupContentsCallback); }

static final private ResultCallback<DriveApi.DriveContentsResult> restoreContentsCallback =
        new ResultCallback<DriveApi.DriveContentsResult>() {
            @Override
            public void onResult(DriveApi.DriveContentsResult result) {
                if (!result.getStatus().isSuccess()) {
                    mToast("File cant be opened");
                    return;
                }

                utilsM.dbClose();

                DriveContents contents = result.getDriveContents();
                File db_file;

                InputStreamReader is = new InputStreamReader(contents.getInputStream());
                BufferedReader reader = new BufferedReader(new InputStreamReader(contents.getInputStream());

                FileOutputStream fos; 
                String line;

                db_file = getDbPath();

                if (db_file != null) {
                    db_file.delete();
                }

                try {
                    fos = new FileOutputStream(act.getDatabasePath(DATABASE_NAME));

                    while ((line = reader.readLine()) != null) { fos.write(line.getBytes()); }
                    fos.flush();
                    fos.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                utilsM.dbOpen();
                mRecyclerView.invalidate();
                mAdapter.notifyDataSetChanged();
                contents.discard(api);

            }
        };




static final private ResultCallback<DriveApi.DriveContentsResult> backupContentsCallback = new ResultCallback<DriveApi.DriveContentsResult>() {

    @Override
    public void onResult(DriveApi.DriveContentsResult result) {
        if (!result.getStatus().isSuccess()) {
            mToast("Error while trying to create new file contents");
            return;
        }

        String mimeType = MimeTypeMap.getSingleton().getExtensionFromMimeType("db");
        MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                .setTitle(GOOGLE_DRIVE_FILE_NAME) // Google Drive File name
                .setMimeType(mimeType)
                .setStarred(true).build();
        // create a file on root folder
        Drive.DriveApi.getRootFolder(api)
                .createFile(api, changeSet, result.getDriveContents())
                .setResultCallback(backupFileCallback);
    }
};
static final private ResultCallback<DriveFolder.DriveFileResult> backupFileCallback = new ResultCallback<DriveFolder.DriveFileResult>() {
    @Override
    public void onResult(DriveFolder.DriveFileResult result) {
        if (!result.getStatus().isSuccess()) {
            mToast("Error while trying to create the file");
            return;
        }
        mfile = result.getDriveFile();
        mfile.open(api, DriveFile.MODE_WRITE_ONLY, null).setResultCallback(backupContentsOpenedCallback);
    }
};
static final private ResultCallback<DriveApi.DriveContentsResult> backupContentsOpenedCallback = new ResultCallback<DriveApi.DriveContentsResult>() {
    @Override
    public void onResult(DriveApi.DriveContentsResult result) {
        if (!result.getStatus().isSuccess()) {
            mToast("Error opening file");
            return;
        }
        try {
            mToast("Uploading db...");

            DriveContents content = result.getDriveContents();
            FileInputStream is = new FileInputStream(act.getDatabasePath(DATABASE_NAME));

            BufferedInputStream in = new BufferedInputStream(is);
            BufferedOutputStream out = new BufferedOutputStream(content.getOutputStream());

            byte[] buffer = new byte[4 * 1024];
            int n = 0;
            int off = 0;

            while( ( n = in.read(buffer) ) > 0) {
                out.write(buffer, 0, n);
                off += n;
                debug("upload_buffer: " + buffer[0]);
                debug("upload_n: " + n);
            }

            debug("writen len: "+off);

            in.close();
            is.close();
            out.flush();
            out.close();
            content.commit(api, null).setResultCallback(new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    mToast("Upload successfull!");
                }
            });
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
};

回答1:


Got a solution, and just forget to commit my file. Here's my code:

public static void doDriveBackup () {
    Drive.DriveApi.newDriveContents(api).setResultCallback(backupContentsCallback);
}

public static void restoreDriveBackup() {
    Query query = new Query.Builder()
            .addFilter(Filters.eq(SearchableField.TITLE, GOOGLE_DRIVE_FILE_NAME))
            .build();

    Drive.DriveApi.query(api, query).setResultCallback(new ResultCallback<DriveApi.MetadataBufferResult>() {
        @Override
        public void onResult(DriveApi.MetadataBufferResult metadataBufferResult) {

            /*for(int i = 0 ;i < metadataBufferResult.getMetadataBuffer().getCount() ;i++) {
                debug("got index "+i);
                debug("filesize in cloud "+ metadataBufferResult.getMetadataBuffer().get(i).getFileSize());
                debug("driveId(1): "+ metadataBufferResult.getMetadataBuffer().get(i).getDriveId());
            }*/


            int count = metadataBufferResult.getMetadataBuffer().getCount() - 1;
            //debug("Count: " + count);
            driveId = metadataBufferResult.getMetadataBuffer().get(0).getDriveId();
            //debug("driveId: " + driveId);
            debug("filesize in cloud " + metadataBufferResult.getMetadataBuffer().get(0).getFileSize());
            metadataBufferResult.getMetadataBuffer().release();


            mfile = Drive.DriveApi.getFile(api, driveId);

            mfile.open(api, DriveFile.MODE_READ_ONLY, new DriveFile.DownloadProgressListener() {
                @Override
                public void onProgress(long bytesDown, long bytesExpected) {
                    //mToast("Downloading... (" + bytesDown + "/" + bytesExpected + ")");;
                }
            })
                    .setResultCallback(restoreContentsCallback);
        }
    });
}

static final private ResultCallback<DriveApi.DriveContentsResult> restoreContentsCallback =
        new ResultCallback<DriveApi.DriveContentsResult>() {
            @Override
            public void onResult(DriveApi.DriveContentsResult result) {
                if (!result.getStatus().isSuccess()) {
                    mToast("Unable to open file, try again.");
                    return;
                }

                utilsM.dbClose();

                db_file = getDbPath();
                String path = db_file.getPath();

                if ( !db_file.exists())
                    db_file.delete();

                db_file = new File(path);

                DriveContents contents = result.getDriveContents();
                //debug("driveId:(2)" + contents.getDriveId());

                try {
                    FileOutputStream fos = new FileOutputStream(db_file);
                    BufferedOutputStream bos = new BufferedOutputStream(fos);
                    BufferedInputStream in = new BufferedInputStream(contents.getInputStream());

                    byte[] buffer = new byte[1024];
                    int n, cnt = 0;


                    //debug("before read " + in.available());

                    while( ( n = in.read(buffer) ) > 0) {
                        bos.write(buffer, 0, n);
                        cnt += n;
                        debug("buffer: " + buffer[0]);
                        debug("buffer: " + buffer[1]);
                        debug("buffer: " + buffer[2]);
                        debug("buffer: " + buffer[3]);
                        bos.flush();
                    }

                    //debug(" read done: " + cnt);

                    bos.close();

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                mToast(act.getResources().getString(R.string.restoreComplete));
                DialogFragment_Sync.dismissDialog();

                utilsM.dbOpen();
                mRecyclerView.invalidate();
                mAdapter.notifyDataSetChanged();
                contents.discard(api);

            }
        };






static final private ResultCallback<DriveApi.DriveContentsResult> backupContentsCallback = new ResultCallback<DriveApi.DriveContentsResult>() {

    @Override
    public void onResult(DriveApi.DriveContentsResult result) {
        if (!result.getStatus().isSuccess()) {
            mToast("Error while trying to create new file contents");
            return;
        }

        String mimeType = MimeTypeMap.getSingleton().getExtensionFromMimeType("db");
        MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                .setTitle(GOOGLE_DRIVE_FILE_NAME) // Google Drive File name
                .setMimeType(mimeType)
                .setStarred(true).build();
        // create a file on root folder
        Drive.DriveApi.getRootFolder(api)
                .createFile(api, changeSet, result.getDriveContents())
                .setResultCallback(backupFileCallback);
    }
};
static final private ResultCallback<DriveFolder.DriveFileResult> backupFileCallback = new ResultCallback<DriveFolder.DriveFileResult>() {
    @Override
    public void onResult(DriveFolder.DriveFileResult result) {
        if (!result.getStatus().isSuccess()) {
            mToast("Error while trying to create the file, try again.");
            DialogFragment_Sync.dismissDialog();
            return;
        }
        mfile = result.getDriveFile();
        mfile.open(api, DriveFile.MODE_WRITE_ONLY, new DriveFile.DownloadProgressListener() {
            @Override
            public void onProgress(long bytesDownloaded, long bytesExpected) {
                DialogFragment_Sync.setProgressText("Creating backup file... ("+bytesDownloaded+"/"+bytesExpected+")");
            }
        }).setResultCallback(backupContentsOpenedCallback);
    }
};
static final private ResultCallback<DriveApi.DriveContentsResult> backupContentsOpenedCallback = new ResultCallback<DriveApi.DriveContentsResult>() {
    @Override
    public void onResult(DriveApi.DriveContentsResult result) {
        if (!result.getStatus().isSuccess()) {
            DialogFragment_Sync.dismissDialog();
            mToast("Error opening file, try again.");
            return;
        }

        DialogFragment_Sync.setProgressText("Backing up..");

        DriveContents contents = result.getDriveContents();
        BufferedOutputStream bos = new BufferedOutputStream(contents.getOutputStream());
        byte[] buffer = new byte[1024];
        int n;

        try {
            FileInputStream is = new FileInputStream(getDbPath());
            BufferedInputStream bis = new BufferedInputStream(is);

            while( ( n = bis.read(buffer) ) > 0 ) {
                bos.write(buffer, 0, n);
                DialogFragment_Sync.setProgressText("Backing up...");
            }
            bos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        contents.commit(api, null).setResultCallback(new ResultCallback<Status>() {
            @Override
            public void onResult(Status status) {
                DialogFragment_Sync.setProgressText("Backup completed!");
                mToast(act.getResources().getString(R.string.backupComplete));
                DialogFragment_Sync.dismissDialog();
            }
        });
    }
};


来源:https://stackoverflow.com/questions/32290860/drive-api-download-upload-sql-database

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