使用服务帐户从android更新google表单?

fnvucqvd  于 2022-12-16  发布在  Android
关注(0)|答案(2)|浏览(103)

我需要帮助,用Android应用程序记录数据到Google工作表使用服务帐户。我读了数百个线程,大多是使用过时的谷歌凭据,不工作。有人能帮助或有一个想法如何写一行(数据)在Google工作表?

更新日期:

在我的成绩单上,我加上了这句话:

implementation 'com.google.android.gms:play-services-auth:19.0.0'
implementation 'pub.devrel:easypermissions:0.3.0'
implementation('com.google.api-client:google-api-client-android:1.23.0') {
    exclude group: 'org.apache.httpcomponents'
}
implementation('com.google.apis:google-api-services-sheets:v4-rev581-1.25.0') {
    exclude group: 'org.apache.httpcomponents'
}
implementation 'com.google.oauth-client:google-oauth-client-jetty:1.23.0'

下面是我的类,用于从google sheet中读取,如google示例中所示:

public class GoogleSheetHelper {
private static final String APPLICATION_NAME = "Google Sheets API Java Quickstart";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final String TOKENS_DIRECTORY_PATH = "tokens";
private static final List<String> SCOPES = Collections.singletonList(SheetsScopes.SPREADSHEETS_READONLY);
private static final String CREDENTIALS_FILE_PATH = "/credentials.json";

private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT, Context context) throws IOException {
    // Load client secrets.
    //InputStream in = GoogleSheetHelper.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
    InputStream in = context.getAssets().open("credentials.json");;
    if (in == null) {
        throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
    }
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
    File tokenFolder = new File(Environment.getExternalStorageDirectory() +
            File.separator + TOKENS_DIRECTORY_PATH);
    if (!tokenFolder.exists()) {
        boolean success = tokenFolder.mkdirs();
        if( !success ){
            throw new RuntimeException("File Error in writing new folder");
        }
    }
    FileDataStoreFactory f = new FileDataStoreFactory(tokenFolder);
    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(f)
            .setAccessType("offline")
            .build();
    //LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
public static void napravi(Context context) throws IOException, GeneralSecurityException {
    // Build a new authorized API client service.
    //final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    final NetHttpTransport HTTP_TRANSPORT = new com.google.api.client.http.javanet.NetHttpTransport();
    final String spreadsheetId = "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms";
    final String range = "Class Data!A2:E";
    Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT, context))
            .setApplicationName(APPLICATION_NAME)
            .build();
    ValueRange response = service.spreadsheets().values()
            .get(spreadsheetId, range)
            .execute();
    List<List<Object>> values = response.getValues();
    if (values == null || values.isEmpty()) {
        System.out.println("No data found.");
    } else {
        System.out.println("Name, Major");
        for (List row : values) {
            System.out.printf("%s, %s\n", row.get(0), row.get(4));
        }
    }
}

因为我在MainActivity中遇到了NetworkOnMainThreadException异常,所以我在Thread中调用了这个异常:

new Thread(() -> {
        try {
            GoogleSheetHelper.napravi(getApplicationContext());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        runOnUiThread(()->{
            // OnPostExecute stuff here
        });
    }).start();

但我现在得到了这个异常:

2020-11-26 06:50:06.447 30966-31002/hr.krkec.orchestrabarcodeapp E/AndroidRuntime: FATAL EXCEPTION: Thread-3
Process: hr.krkec.orchestrabarcodeapp, PID: 30966
java.lang.NoClassDefFoundError: Failed resolution of: Ljava/awt/Desktop;
    at com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp.browse(AuthorizationCodeInstalledApp.java:129)
    at com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp.onAuthorization(AuthorizationCodeInstalledApp.java:113)
    at com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp.authorize(AuthorizationCodeInstalledApp.java:81)
    at hr.krkec.orchestrabarcodeapp.Helpers.GoogleSheetHelper.getCredentials(GoogleSheetHelper.java:75)
    at hr.krkec.orchestrabarcodeapp.Helpers.GoogleSheetHelper.napravi(GoogleSheetHelper.java:89)
    at hr.krkec.orchestrabarcodeapp.MainActivity.lambda$onCreate$1$MainActivity(MainActivity.java:112)
    at hr.krkec.orchestrabarcodeapp.-$$Lambda$MainActivity$dMONIKNVXAJxtq31-j2RI7GKpKk.run(Unknown Source:2)
    at java.lang.Thread.run(Thread.java:764)
 Caused by: java.lang.ClassNotFoundException: Didn't find class "java.awt.Desktop" on path: DexPathList[[zip file "/data/app/hr.krkec.orchestrabarcodeapp-DmJDmyzrsZ1Fz0c3Wtg9xg==/base.apk"],nativeLibraryDirectories=[/data/app/hr.krkec.orchestrabarcodeapp-DmJDmyzrsZ1Fz0c3Wtg9xg==/lib/x86, /data/app/hr.krkec.orchestrabarcodeapp-DmJDmyzrsZ1Fz0c3Wtg9xg==/base.apk!/lib/x86, /system/lib, /vendor/lib]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:93)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    at com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp.browse(AuthorizationCodeInstalledApp.java:129) 
    at com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp.onAuthorization(AuthorizationCodeInstalledApp.java:113) 
    at com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp.authorize(AuthorizationCodeInstalledApp.java:81) 
    at hr.krkec.orchestrabarcodeapp.Helpers.GoogleSheetHelper.getCredentials(GoogleSheetHelper.java:75) 
    at hr.krkec.orchestrabarcodeapp.Helpers.GoogleSheetHelper.napravi(GoogleSheetHelper.java:89) 
    at hr.krkec.orchestrabarcodeapp.MainActivity.lambda$onCreate$1$MainActivity(MainActivity.java:112) 
    at hr.krkec.orchestrabarcodeapp.-$$Lambda$MainActivity$dMONIKNVXAJxtq31-j2RI7GKpKk.run(Unknown Source:2) 
    at java.lang.Thread.run(Thread.java:764) 

我哪里做错了?

xienkqul

xienkqul1#

如果您正在寻找通过Android SDK在Android应用中使用Google Sheets API的方法,这可能会对您有所帮助。

设置适用于Android的Google工作区APIhttps://developers.google.com/gsuite/guides/android

  • 先决条件:*
  • 必须拥有Google帐户
  • Android Studio SDK 1.2或更高版本
  • 适用于API 23或更高版本的Android SDK包

准备项目:
在您的Android项目中,包含一个build.gradle文件,其依赖关系如下:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:25.0.1'
    compile 'com.google.android.gms:play-services-auth:15.0.1'
    compile 'pub.devrel:easypermissions:0.3.0'
    compile('com.google.api-client:google-api-client-android:1.23.0') {
        exclude group: 'org.apache.httpcomponents'
    }
    compile('com.google.apis:google-api-services-<API>-<VERSION>') {
        exclude group: 'org.apache.httpcomponents'
    }
}

请确保将API版本替换为Google Workspace API和版本。例如,Google Sheets API将目标编译为“com.google.apis:google-api-services-sheets:v4-rev 581 -1.25.0
服务通过身份验证后,执行API调用的过程与任何Google Workspace Java快速入门中所示的过程相同。
Java快速入门过程总结:
1.打开Google工作表API
1.准备项目
1.设置样品
1.运行示例
有关Java快速入门的详细信息,请参阅此处:https://developers.google.com/sheets/api/quickstart/java

pprl5pva

pprl5pva2#

您需要为AuthorizationCodeInstalledApp提供自己的浏览器

return new AuthorizationCodeInstalledApp(flow, receiver, new AuthorizationCodeInstalledApp.Browser() {
    @Override
    public void browse(String url) throws IOException {
        // open browser here on the url
    }
}).authorize("user");

相关问题