![](/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.