Drive API - 下载/上传sql数据库

时间:2015-08-29 21:32:43

标签: android google-drive-android-api

我目前正在下载我使用驱动器api上传的sql数据库。有一个备份肯定,但当我尝试打开文件时,我收到一个错误,该文件无法打开。

修改: 我解决了上面的问题。 现在我想最终上传和下载sql数据库。

我在互联网上找到了下载和上传的代码,但没有任何效果。

如何正确上传和下载我的sql数据库?

我的代码:

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 个答案:

答案 0 :(得分:3)

有一个解决方案,忘了提交我的文件。这是我的代码:

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();
            }
        });
    }
};