我正在尝试将数据库文件发送到Google云端硬盘,我导入了必要的libreries,但是当我尝试将文件上传到GoogleDrive时,我获得了NPE。
public class Main extends BaseDemoActivity {
private Drive service;
@Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
// create new contents resource
com.google.android.gms.drive.Drive.DriveApi.newDriveContents(getGoogleApiClient())
.setResultCallback(driveContentsCallback);
}
final private ResultCallback<DriveContentsResult> driveContentsCallback = new
ResultCallback<DriveContentsResult>() {
@Override
public void onResult(final DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create new file contents");
return;
}
new Thread() {
@Override
public void run() {
try {
java.io.File externalDB = new java.io.File(Environment.getExternalStorageDirectory(), getString(R.string.app_name) + "/data.crypt");
java.io.File fileContent = new java.io.File(externalDB.getPath());
FileContent mediaContent = new FileContent("application/x-sqlite3", fileContent);
com.google.api.services.drive.model.File body =
new com.google.api.services.drive.model.File();
body.setTitle("data.crypt");
body.setMimeType("application/x-sqlite3");
com.google.api.services.drive.model.File file =
service.files().insert(body, mediaContent).execute();
if (file != null) {
Log.d("GoogleDrive", "File Uploaded");
}
} catch (UserRecoverableAuthIOException e) {
//startActivityForResult(e.getIntent(), REQUEST_AUTHORISATION);
} catch (IOException e) {
e.printStackTrace();
}
}
}
.start();
}
};
...
...
NPE的路线 com.google.api.services.drive.model.File file = service.files()。insert(body,mediaContent).execute();
日志
01-17 11:48:32.387 11372-12201/? E/AndroidRuntime: FATAL EXCEPTION: Thread-34061
01-17 11:48:32.387 11372-12201/? E/AndroidRuntime: Process: chris.con, PID: 11372
01-17 11:48:32.387 11372-12201/? E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.api.services.drive.Drive$Files com.google.api.services.drive.Drive.files()' on a null object reference
01-17 11:48:32.387 11372-12201/? E/AndroidRuntime: at chris.con.Main$1$1.run(Main.java:51)
答案 0 :(得分:0)
嗯,日志消息告诉您private Drive service
未初始化。
这里的主要问题是,您正在混淆两个独立的API以与Drive配合使用。一个来自Google Play Sevices,包含com.google.android.gms.drive
,另一个来自带有包com.google.api.services.drive
的google-api-java。你应该只坚持其中一个,根据我的经验,它应该是com.google.api.services
中的一个。 Play Services中的错误具有更多错误,功能更少,如果您希望在需要时同步数据而不是在库感觉要同步数据时,您通常会达到速率限制。
您可以像这样初始化api.services驱动器(例如)
GoogleAccountCredential credential = new GoogleAccountCredential(this, "oauth2:" + DriveScopes.DRIVE_FILE);
mDrive = new Drive.Builder(
new NetHttpTransport(), JacksonFactory.getDefaultInstance(), credential)
.setApplicationName("Your App")
.build();
之后你可以service.files().insert
。你不需要创造内容&#34;首先使用com.google.api.services
API。