![](/img/trans.png)
[英]Unable to upload file in specific folder in google drive using REST API
[英]How to upload a SQLite database file using the latest Google Sign-In and Drive REST api?
找不到任何未弃用的用于将我的数据库文件上传到 Google Drive 的代码片段。
我一直在使用 Android Studio,对使用 Java 进行编程的知识最少,到目前为止,我能够制作一个可以使用 SQLite 存储、编辑和删除数据的应用程序。 现在我需要将数据库备份到 Google Drive 并且我没有线索。 这是我一直在使用但没有用于测试目的的代码:
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestProfile()
.build();
GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(this.getIntent());
try {
GoogleSignInAccount account = task.getResult(ApiException.class);
GoogleAccountCredential mCredential = GoogleAccountCredential.usingOAuth2(Home.this.getApplicationContext(), Arrays.asList(new String[]{DriveScopes.DRIVE})).setBackOff(new ExponentialBackOff());
mCredential.setSelectedAccount(account.getAccount());
HttpTransport transport = AndroidHttp.newCompatibleTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
Drive mService = new com.google.api.services.drive.Drive.Builder(
transport, jsonFactory, mCredential)
.setApplicationName(Home.this.getString(R.string.app_name))
.build();
com.google.api.services.drive.model.File file = new com.google.api.services.drive.model.File();
file.setName("test");
List<String> parents = new ArrayList<>(1);
parents.add("parent_folder_id"); // Here you need to get the parent folder id
file.setParents(parents);
FileContent mediaContent = new FileContent(".txt", File.createTempFile("test", ".txt"));
mService.files().create(file, mediaContent).setFields("id").execute();
} catch (ApiException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
到目前为止,我已经设法让登录屏幕弹出,但我在“mCredential.setSelectedAccount(account.getAccount());”行上给了我一个 NullPointerException。
经过一些打击和试验,我终于能够实现这一目标。 如果您需要完整的代码,请告诉我。 下面的片段是关于如何将文件内容从本地 db 文件写入 Google Drive:
File metadata = new File().setName(Consts.GOOGLE_DRIVE_DBFILE_NAME);
metadata.setMimeType("application/x-sqlite3");
metadata.setDescription("MySugarDiary app backup file");
FileContent mediaContent = new FileContent("application/x-sqlite3", mContext.getDatabasePath(Conts.APP_DB_FILE_NAME));
// Update the metadata and contents.
mDriveService.files().update(fileId, metadata, mediaContent).execute();
Log.d(TAG, "Saved content to: " + Consts.GOOGLE_DRIVE_DBFILE_NAME);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.