如何使用android应用程序创建和上传谷歌电子表格?
我在这上面花了太多时间,所以我想问一下。我想用android创建并上传谷歌电子表格。我知道我应该使用驱动API来实现这一点。我知道如何使用此API(甚至excel文件)创建文件,但当setMimeType设置为application/vnd.google apps.spreadsheet时,我在设备上收到一个错误:尝试创建文件时出错。如何使用android应用程序创建和上传谷歌电子表格?,android,spreadsheet,google-drive-android-api,Android,Spreadsheet,Google Drive Android Api,我在这上面花了太多时间,所以我想问一下。我想用android创建并上传谷歌电子表格。我知道我应该使用驱动API来实现这一点。我知道如何使用此API(甚至excel文件)创建文件,但当setMimeType设置为application/vnd.google apps.spreadsheet时,我在设备上收到一个错误:尝试创建文件时出错。 @Override public void onConnected(Bundle connectionHint) { super.onConnec
@Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
// create new contents resource
Drive.DriveApi.newDriveContents(getGoogleApiClient())
.setResultCallback(driveContentsCallback);
}
final private ResultCallback<DriveContentsResult> driveContentsCallback = new
ResultCallback<DriveContentsResult>() {
@Override
public void onResult(DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create new file contents");
return;
}
final DriveContents driveContents = result.getDriveContents();
// Perform I/O off the UI thread.
new Thread() {
@Override
public void run() {
// write content to DriveContents
OutputStream outputStream = driveContents.getOutputStream();
Writer writer = new OutputStreamWriter(outputStream);
try {
writer.write("Hello World!");
writer.write("Hello World!");
writer.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("Orders")
.setMimeType("application/vnd.google-apps.spreadsheet")
.setStarred(true).build();
// create a file on root folder
Drive.DriveApi.getRootFolder(getGoogleApiClient())
.createFile(getGoogleApiClient(), changeSet, driveContents)
.setResultCallback(fileCallback);
}
}.start();
}
};
final private ResultCallback<DriveFileResult> fileCallback = new
ResultCallback<DriveFileResult>() {
@Override
public void onResult(DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create the file");
return;
}
showMessage("Created a file with content: " + result.getDriveFile().getDriveId());
storeId(result.getDriveFile().getDriveId());
kill_activity();
}
};v
@覆盖
未连接的公共无效(捆绑连接提示){
super.onConnected(connectionHint);
//创建新内容资源
Drive.DriveApi.newDriveContents(getGoogleAppClient())
.setResultCallback(DriveContentScalBack);
}
最终私有结果回调驱动器contentscallback=new
ResultCallback(){
@凌驾
public void onResult(DriveContentsResult结果){
如果(!result.getStatus().issucess()){
showMessage(“尝试创建新文件内容时出错”);
返回;
}
final DriveContents DriveContents=result.getDriveContents();
//在UI线程外执行I/O。
新线程(){
@凌驾
公开募捐{
//将内容写入驱动器内容
OutputStream OutputStream=driveContents.getOutputStream();
Writer Writer=新的OutputStreamWriter(outputStream);
试一试{
作家。写(“你好,世界!”);
作家。写(“你好,世界!”);
writer.close();
}捕获(IOE异常){
Log.e(标记,e.getMessage());
}
MetadataChangeSet changeSet=新建MetadataChangeSet.Builder()
.setTitle(“订单”)
.setMimeType(“application/vnd.google apps.spreadsheet”)
.setStarred(true).build();
//在根文件夹上创建文件
Drive.DriveApi.getRootFolder(getGoogleAppClient())
.createFile(GetGoogleAppClient(),变更集,驱动内容)
.setResultCallback(文件回调);
}
}.start();
}
};
final private ResultCallback fileCallback=new
ResultCallback(){
@凌驾
public void onResult(DriveFileResult){
如果(!result.getStatus().issucess()){
showMessage(“尝试创建文件时出错”);
返回;
}
showMessage(“创建了一个包含以下内容的文件:+result.getDriveFile().getDriveId());
storeId(result.getDriveFile().getDriveId());
杀死_活动();
}
};v
GDAA目前不支持创建Google文档文件。您必须在Android应用程序中使用。GDAA目前不支持创建Google文档文件。您必须在Android应用程序中使用。您可以从Android应用程序在google drive中上传excel电子表格,如下所示
我想你知道谷歌安卓网站上的
现在使用创建excel工作表
现在,按照下面的步骤,将Google SignIn与应用程序中的驱动器范围(Drive.scope_文件)集成
现在,将最终副本和最后一份副本粘贴到活动中的活动代码下面,然后在saveFileToDrive(file_path)方法中给出excel工作表路径
public类UploadFileInGoogleDriveActivity扩展活动{
私有静态最终字符串TAG=“tejadroid quickstart”;
私有静态最终整数请求\代码\符号\输入=0;
私人谷歌签名客户端mGoogleSignInClient;
专用驱动器客户端mDriveClient;
专用驱动器资源客户端mDriveResourceClient;
@凌驾
创建时受保护的void(@Nullable Bundle savedInstanceState){
super.onCreate(savedInstanceState);
签名();
}
/**
*开始登录活动。
*/
私人无效签名(){
Log.i(标签“开始登录”);
mGoogleSignInClient=buildGoogleSignInClient();
startActivityForResult(mGoogleSignInClient.getSigningent(),请求\代码\登录);
}
/**
*建立一个谷歌登录客户端。
*/
私有GoogleSignInClient构建GoogleSignInClient(){
谷歌签名签名签名签名=
新建GoogleSignionOptions.Builder(GoogleSignionOptions.DEFAULT\u登录)
.requestScopes(驱动器.SCOPE\u文件)
.build();
返回GoogleSignIn.getClient(这是signInOptions);
}
@凌驾
受保护的void onActivityResult(最终int请求代码、最终int结果代码、最终意图数据){
super.onActivityResult(请求代码、结果代码、数据);
开关(请求代码){
案例请求、代码、登录:
Log.i(标签“登录请求代码”);
//在用户登录后调用。
if(resultCode==RESULT\u OK){
Log.i(标记“已成功登录”);
//在此处使用上次登录的帐户,因为它已具有驱动器作用域。
mDriveClient=Drive.getDriveClient(this,GoogleSignIn.getLastSignedAccount(this));
//构建驱动器资源客户端。
mDriveResourceClient=
Drive.getDriveResourceClient(this,GoogleSignIn.getLastSignedAccount(this));
//来自SD卡的Excel工作表路径
最终字符串filePath=“/storage/simulated/0/Expense Manager/ExpenseReport/Ex
public class UploadFileInGoogleDriveActivity extends Activity {
private static final String TAG = "tejadroid-quickstart";
private static final int REQUEST_CODE_SIGN_IN = 0;
private GoogleSignInClient mGoogleSignInClient;
private DriveClient mDriveClient;
private DriveResourceClient mDriveResourceClient;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
signIn();
}
/**
* Start sign in activity.
*/
private void signIn() {
Log.i(TAG, "Start sign in");
mGoogleSignInClient = buildGoogleSignInClient();
startActivityForResult(mGoogleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);
}
/**
* Build a Google SignIn client.
*/
private GoogleSignInClient buildGoogleSignInClient() {
GoogleSignInOptions signInOptions =
new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(Drive.SCOPE_FILE)
.build();
return GoogleSignIn.getClient(this, signInOptions);
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_SIGN_IN:
Log.i(TAG, "Sign in request code");
// Called after user is signed in.
if (resultCode == RESULT_OK) {
Log.i(TAG, "Signed in successfully.");
// Use the last signed in account here since it already have a Drive scope.
mDriveClient = Drive.getDriveClient(this, GoogleSignIn.getLastSignedInAccount(this));
// Build a drive resource client.
mDriveResourceClient =
Drive.getDriveResourceClient(this, GoogleSignIn.getLastSignedInAccount(this));
// Excel Sheet path from SD card
final String filePath = "/storage/emulated/0/Expense Manager/ExpenseReport/ExpenseDiary.xls";
saveFileToDrive(filePath);
}
break;
}
}
/**
* Create a new file and save it to Drive.
*/
private void saveFileToDrive(final String filePath) {
// Start by creating a new contents, and setting a callback.
Log.i(TAG, "Creating new contents.");
mDriveResourceClient
.createContents()
.continueWithTask(
new Continuation<DriveContents, Task<Void>>() {
@Override
public Task<Void> then(@NonNull Task<DriveContents> task) throws Exception {
return createFileIntentSender(task.getResult(), new File(filePath));
}
})
.addOnFailureListener(
new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "Failed to create new contents.", e);
}
});
}
/**
* Creates an {@link IntentSender} to start a dialog activity with configured {@link
* CreateFileActivityOptions} for user to create a new photo in Drive.
*/
private Task<Void> createFileIntentSender(DriveContents driveContents, File file) throws Exception {
Log.i(TAG, "New contents created.");
OutputStream outputStream = driveContents.getOutputStream();
InputStream in = new FileInputStream(file);
try {
try {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
outputStream.write(buf, 0, len);
}
} finally {
outputStream.close();
}
} finally {
in.close();
}
// Create the initial metadata - MIME type and title.
// Note that the user will be able to change the title later.
MetadataChangeSet metadataChangeSet =
new MetadataChangeSet.Builder()
.setMimeType("application/vnd.ms-excel")
.setTitle("ExcelSheet.xls")
.build();
// Set up options to configure and display the create file activity.
CreateFileActivityOptions createFileActivityOptions =
new CreateFileActivityOptions.Builder()
.setInitialMetadata(metadataChangeSet)
.setInitialDriveContents(driveContents)
.build();
return mDriveClient
.newCreateFileActivityIntentSender(createFileActivityOptions)
.continueWith(
new Continuation<IntentSender, Void>() {
@Override
public Void then(@NonNull Task<IntentSender> task) throws Exception {
startIntentSenderForResult(task.getResult(), REQUEST_CODE_CREATOR, null, 0, 0, 0);
return null;
}
});
}
}