所以我需要傳遞一個密鑰(.p12
)文件SERVICE_ACCT_KEYFILE
,它直接存儲在我的Android項目中的res
文件夾下。我設置了setServiceAccountPrivateKeyFromP12File()
就象這樣:java.net.URL.getFile()null對象引用
private static GoogleCredential authorize() throws Exception {
return new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCT_EMAIL)
.setServiceAccountPrivateKeyFromP12File(new File(
PredictionSample.class.getResource("/" + SERVICE_ACCT_KEYFILE).getFile()))
.setServiceAccountScopes(Arrays.asList(PredictionScopes.PREDICTION,
StorageScopes.DEVSTORAGE_READ_ONLY))
.build();
}
這個例子完美的作品在Java中,但我想實現它在Android和我有以下錯誤:
Attempt to invoke virtual method 'java.lang.String java.net.URL.getFile()' on a null object reference
即使做它失敗:
String keyPath = "android.resource://" + MainActivity.PACKAGE_NAME + "/" + R.raw.pretense307cf970d6b1;
return new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCT_EMAIL)
.setServiceAccountPrivateKeyFromP12File(new File(
PredictionSample.class.getResource(keyPath).getFile()))
.setServiceAccountScopes(Arrays.asList(PredictionScopes.PREDICTION,
StorageScopes.DEVSTORAGE_READ_ONLY))
.build();
}
我該如何解決?
謝謝。
的Android資源和Java資源是不一樣的東西。看到文檔:https://developer.android.com/guide/topics/resources/providing-resources.html – njzk2
@ njzk2我意識到這一點,我試圖翻譯。但沒有成功。有任何想法嗎? –
您無法以「文件」的形式訪問原始資源。但是,我鏈接的文檔告訴你如何訪問文件的內容。 – njzk2