如何上传从Android应用一个数据库文件,谷歌驱动器? [英] How to upload a db file to google drive from android application?

查看:172
本文介绍了如何上传从Android应用一个数据库文件,谷歌驱动器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的应用程序,以谷歌驱动器上传数据库文件。我能够创建在谷歌驱动器中的文件夹,但我没有得到如何上传数据库文件。

I want to upload a db file from my app to google drive. I am able to create a folder in google drive but I am not getting how to upload db file .

这是我的code。

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.Toast;


import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveFile;
import com.google.android.gms.drive.DriveFolder;
import com.google.android.gms.drive.DriveFolder.DriveFolderResult;
import com.google.android.gms.drive.DriveId;
import com.google.android.gms.drive.Metadata;
import com.google.android.gms.drive.MetadataChangeSet;
import com.google.android.gms.drive.DriveApi.DriveContentsResult;

import com.google.api.client.http.FileContent;
//import com.google.api.services.drive.Drive;
import com.google.api.services.drive.Drive.Files;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;

//import com.google.api.services.drive.Drive;


public class MainActivity extends BaseDemoActivity {

    private final static String TAG = "MainActivity";
    DriveId folderId;
    private static Uri  fileUri;


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

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


    final ResultCallback<DriveFolder.DriveFileResult> fileCallBack = new ResultCallback<DriveFolder.DriveFileResult>() {
        @Override
        public void onResult(DriveFolder.DriveFileResult driveFileResult) {

            if (!driveFileResult.getStatus().isSuccess()) {
                Log.v(TAG, "Error while trying to create the file");
                return;
            }
            //Initialize mFile to be processed in AsyncTask
            DriveFile mfile = driveFileResult.getDriveFile();
            new EditContentsAsyncTask(MainActivity.this).execute(mfile);

        }
    };

         public void saveToDrive()
         {
               fileUri = Uri.fromFile(new java.io.File(Environment.getDataDirectory().getPath()
                        + "/data/com.example.dbupload/databases/Student"));

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


         }


    public class EditContentsAsyncTask extends ApiClientAsyncTask<DriveFile, Void, Boolean> {

        public EditContentsAsyncTask(Context context) {
            super(context);
        }

        @Override
        protected Boolean doInBackgroundConnected(DriveFile... args) {
            DriveFile file = args[0];
            try {

                DriveContentsResult driveContentsResult = file.open(
                        getGoogleApiClient(), DriveFile.MODE_WRITE_ONLY, null).await();


                if (!driveContentsResult.getStatus().isSuccess()) {
                    return false;
                }

                DriveContents driveContents = driveContentsResult.getDriveContents();



                //edit the outputStream
                DatabaseHandler db = new DatabaseHandler(MainActivity.this);
                String inFileName = getApplicationContext().getDatabasePath(db.getDatabaseName()).getPath();
                //DATABASE PATH

                FileInputStream is = new FileInputStream(inFileName);
                BufferedInputStream in = new BufferedInputStream(is);
                byte[] buffer = new byte[8 * 1024];

                BufferedOutputStream out = new BufferedOutputStream(driveContents.getOutputStream());
                int n = 0;
                while ((n = in.read(buffer)) > 0) {
                    out.write(buffer, 0, n);
                }
                in.close();


                com.google.android.gms.common.api.Status status =
                        driveContents.commit(getGoogleApiClient(), null).await();
                return status.getStatus().isSuccess();
            } catch (IOException e) {
                Log.e(TAG, "IOException while appending to the output stream", e);
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (!result) {
                showMessage("Error while editing contents");
                return;
            }
            showMessage("Successfully edited contents");
        }
    }

    private String getMimeType(String string) {
        // TODO Auto-generated method stub
        return null;
    }
}

我可以在驱动器上创建一个文件夹。任何一个可以请帮我,我应该做上传数据库文件?

I am able to create a folder in drive. can any one please help me what I should do for uploading a db file?

推荐答案

首先,事实证明我看到这些进口:

First, the fact that I'm seeing these imports:

import com.google.api.client.http.FileContent;
...
import com.google.api.services.drive.Drive;

表明您正在混合 GDAA 和的 REST API。除非你想在麻烦不要做。

indicates that you're mixing GDAA and the REST Api. Do not do it unless you want to get in trouble.

所以,当你有你的FolderId,它是你的DB文件的父母,我presume(如果数据库文件是一个SQLite的类型,您的MIME类型应为应用程序/ x-sqlite3的' )。

So, when you got your FolderId, it is a parent of your 'DB' file, I presume (and if the DB file is a SQLite type, your MIME TYPE should be 'application/x-sqlite3').

不管怎样,在GDAA,你首先把你的java.io.File(即重新presents的DB)到的内容。而且你必须提供的(如文件的标题,MIME类型,标志...)。你得到了元数据的权利,这是你绊倒的内容。下面的代码片段应该做你所需要的(不要抱着我的责任,我抨击一起在5分钟内 - 无检测)

Anyway, in GDAA, you first have to turn your java.io.File (that represents the 'DB') into content. And you have to supply metadata (like file title, mime type, flags ...). You got the metadata right, it is the content you tripped over. The following snippet should do what you need (don't hold me accountable, I slammed it together in 5 minutes - no testing)

/******************************************************************
   * create file in GOODrive
   * @param pFldr parent's ID
   * @param titl  file name
   * @param mime  file mime type  (application/x-sqlite3)
   * @param file  file (with content) to create
   */
  static void saveToDrive(final DriveFolder pFldr, final String titl, 
                                      final String mime, final java.io.File file) {
    if (getGoogleApiClient() != null && pFldr != null && titl != null && mime != null && file != null) try {
      // create content from file
      Drive.DriveApi.newDriveContents(getGoogleApiClient()).setResultCallback(new ResultCallback<DriveContentsResult>() {
        @Override
        public void onResult(DriveContentsResult driveContentsResult) {
          DriveContents cont = driveContentsResult != null && driveContentsResult.getStatus().isSuccess() ?
            driveContentsResult.getDriveContents() : null;

          // write file to content, chunk by chunk   
          if (cont != null) try {
            OutputStream oos = cont.getOutputStream();
            if (oos != null) try {
              InputStream is = new FileInputStream(file);
              byte[] buf = new byte[4096];
              int c;
              while ((c = is.read(buf, 0, buf.length)) > 0) {
                oos.write(buf, 0, c);
                oos.flush();
              }
            }
            finally { oos.close();}

            // content's COOL, create metadata
            MetadataChangeSet meta = new Builder().setTitle(titl).setMimeType(mime).build();

            // now create file on GooDrive
            pFldr.createFile(getGoogleApiClient(), meta, cont).setResultCallback(new ResultCallback<DriveFileResult>() {
              @Override
              public void onResult(DriveFileResult driveFileResult) {
                if (driveFileResult != null && driveFileResult.getStatus().isSuccess()) {
                  // BINGO
                } else {
                  // report error
                }
              }
            });
          } catch (Exception e) { e.printStackTrace(); }
        }
      });
    } catch (Exception e) { e.printStackTrace(); }
  }

我注意到,你适应官方 GDAA演示为您的项目。如果这还不够,或是铺天盖地,你也可以看看这个演示,即采用不同的方法来同样的问题。

I noticed, you're adapting the 'official' GDAA DEMO for your project. In case it is not sufficient or overwhelming, you may also look at this demo, that takes a different approach to the same problem.

好运

这篇关于如何上传从Android应用一个数据库文件,谷歌驱动器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆