gpt4 book ai didi

android - 如何从 Android 应用程序上传数据库文件到谷歌驱动器?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:27:45 25 4
gpt4 key购买 nike

我想从我的应用程序上传一个数据库文件到谷歌驱动器。我可以在谷歌驱动器中创建一个文件夹,但我不知道如何上传数据库文件。

这是我的代码。

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

我可以在驱动器中创建一个文件夹。谁能帮我上传数据库文件我应该怎么做?

最佳答案

首先,我看到了这些导入:

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

表示您正在混合 GDAAREST阿皮。除非您想进入trouble,否则不要这样做.

因此,当您获得 FolderId 时,我认为它是您的“DB”文件的父级(如果 DB 文件是 SQLite 类型,您的 MIME TYPE 应该是“application/x-sqlite3”)。

无论如何,在 GDAA 中,您首先必须将 java.io.File(表示“DB”)转换为内容。而且您必须提供元数据(如文件标题、MIME 类型、标志...)。你得到了正确的元数据,这是你绊倒的内容。以下代码段应该可以满足您的需求(不要追究我的责任,我在 5 分钟内将其拼凑在一起 - 未进行测试)

/******************************************************************
* 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 DEMO为您的项目。万一还不够或压倒性的,你也可以看看这个demo ,这对同一个问题采用了不同的方法。

祝你好运

关于android - 如何从 Android 应用程序上传数据库文件到谷歌驱动器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33491984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com