问题 如何将Android应用与Google表格电子表格相关联?


我正在尝试使用需要使用Google电子表格API的Android应用。我是新手,所以我从api的第3版开始: https://developers.google.com/google-apps/spreadsheets/ 

我按照所有步骤,将所有jar文件下载到 lib 我的项目文件夹中的子文件夹然后像往常一样添加到Eclipse中的构建路径。因此虽然没有Java示例来执行Oauth 2.0,但我只是尝试声明:

SpreadsheetService service = new SpreadsheetService("v1");

但是,当我模仿这个简单的行时,它给了我一个错误:

java.lang.NoClassDefFoundError: com.google.gdata.client.spreadsheet.SpreadsheetService

我正在使用文档中包含的所有jar,我有导入:

import com.google.gdata.client.spreadsheet.SpreadsheetService;

但我完全迷失了。我不知道还有什么可以开始,连接到Google API并使用电子表格。


992
2017-09-18 14:01


起源

此错误是因为它没有获得SpreadsheetService类。您添加了哪些jar文件? code.google.com/p/google-api-java-client/downloads/... 你用过这个图书馆吗? - Scorpion
您是否设置了项目的构建路径?如果不是我建议请先做那件事然后再试一次。 - Scorpion
我已经按照文档中的所有步骤进行操作,并且我在Eclipse中构建了包含所有库的路径。但仍然得到相同的错误。 - user1680435
库:gdata,javamail,google-api-java-client:所有这些都在应用程序的路径中(lib子文件夹)它编译得很好但是一旦我运行它,Eclipse就会抛出这个错误。 - user1680435
我一直在研究这个问题几个小时,我只知道SpreadsheetService所需的库是jar:gdata-spreadsheet-meta-3.0和gdata-spreadsheet-3.0它只能编译这两个库但却得到同样的错误。 :( - user1680435


答案:


没有OAuth 2.0的示例代码。但是为了安全起见,它建议执行OAuth。您还必须添加以下权限。

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCOUNT_MANAGER"/>
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

示例代码: -

try {
    SpreadsheetEntry spreadsheet;
    service = new SpreadsheetService("Spreadsheet");
    service.setProtocolVersion(SpreadsheetService.Versions.V3);
    service.setUserCredentials("username", "password");//permission required to add in Manifest
    URL metafeedUrl = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
    feed = service.getFeed(metafeedUrl, SpreadsheetFeed.class);

    List<SpreadsheetEntry> spreadsheets = feed.getEntries();
    if (spreadsheets.size() > 0) {
        spreadsheet = spreadsheets.get(i);//Get your Spreadsheet
   }
} catch (Exception e) {
    e.printStackTrace();
}

5
2017-10-16 17:30



我想我没有指定的Jars,因为我无法像你放在那里的第一行那样创建一个Spreadsheet类。我不知道还能做什么。唯一的选择是重新开始并逐步完成。 - user1680435
冷静下来,不要感到沮丧。回答我的一些问题,你是否在项目中包含了gdata-core-1.0.jar和guava-11.0.1.jar? - Scorpion
我的错误实际上是一个SpreadsheetEntry而不是电子表格。如果您因为需要而添加,请添加我上面说的2jars,然后重试。我认为这对你有用。 - Scorpion
service.getFeed给了我一个ParseException,说“无法识别的内容类型:application / binary” - Nels Beckman


非常感谢Scorpion!有用!!我一直在尝试这个问题太久了。 好的,这是我的解决方案: 我开始了一个新项目并包括这些罐子:

gdata-client-1.0
gdata-client-meta-1.0
gdata-core-1.0
gdata-spreadsheet-3.0
gdata-spreadsheet-meta-3.0
guava-13.0.1  

和我的代码:

    SpreadsheetService spreadsheet= new SpreadsheetService("v1");
    spreadsheet.setProtocolVersion(SpreadsheetService.Versions.V3);

    try {
        spreadsheet.setUserCredentials("username", "password");
        URL metafeedUrl = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
        SpreadsheetFeed feed = spreadsheet.getFeed(metafeedUrl, SpreadsheetFeed.class);

        List<SpreadsheetEntry> spreadsheets = feed.getEntries();
        for (SpreadsheetEntry service : spreadsheets) {             
            System.out.println(service.getTitle().getPlainText());
       }
    } catch (AuthenticationException e) {           
        e.printStackTrace();
    }

当然这是在不在主线程中的不同线程中执行的。 OAuth 2.0没有java文档,但我会尝试,如果我不能这样做,我会在这里问。 再次,非常感谢,我希望在我这个时间工作的时候帮助你。 :)


4
2017-10-17 12:19



Fo Oauth 2.0请仔细阅读 blog.doityourselfandroid.com/2011/08/06/oauth-2-0-flow-android - Scorpion
我很抱歉,我把我的答案都放在了,因为这正是我所做的并为我工作的t mean that you didn帮助它只是一种向其他人说出的方式,可以帮助他们。谢谢,对不起我的错误。还要感谢Oauth 2.0链接,我会尝试一下。 - user1680435


这是一个复杂的过程,但它可以完成!我写了一篇 博客文章 让基础知识运行起来。我也发表了一篇文章 开源项目 这实际上很有用,但仍然很少。它使用OAuth,因此可以直接从Android的权限模型中获取权限(没有硬编码的电子邮件/密码!)。

你需要一些东西来启动“选择帐户意图”:

    View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
         Intent intent = AccountPicker.newChooseAccountIntent(null, null, new String[]{"com.google"},
                 false, null, null, null, null);
         startActivityForResult(intent, 1);

        if (AUTO_HIDE) {
            delayedHide(AUTO_HIDE_DELAY_MILLIS);
        }
        return false;
    }
};

然后当该意图返回时,您可以尝试使用返回的令牌(尽管注意,如果这是用户第一次必须明确授权您的程序;那就是UserRecoverableAuthException):

    protected void onActivityResult(final int requestCode, final int resultCode,
        final Intent data) {
    if (requestCode == 1 && resultCode == RESULT_OK) {
        final String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
        System.err.println(accountName);

        (new AsyncTask<String, String,String>(){
            @Override
            protected String doInBackground(String... arg0) {
                try {
                    // Turn account name into a token, which must
                    // be done in a background task, as it contacts
                    // the network.
                    String token = 
                            GoogleAuthUtil.getToken(
                                    FullscreenActivity.this, 
                                    accountName, 
                                    "oauth2:https://spreadsheets.google.com/feeds https://docs.google.com/feeds");
                    System.err.println("Token: " + token);

                    // Now that we have the token, can we actually list
                    // the spreadsheets or anything...
                    SpreadsheetService s =
                            new SpreadsheetService("Megabudget");
                    s.setAuthSubToken(token);

                    // Define the URL to request.  This should never change.
                    // (Magic URL good for all users.)
                    URL SPREADSHEET_FEED_URL = new URL(
                        "https://spreadsheets.google.com/feeds/spreadsheets/private/full");

                    // Make a request to the API and get all spreadsheets.
                    SpreadsheetFeed feed;
                    try {
                        feed = s.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
                        List<SpreadsheetEntry> spreadsheets = feed.getEntries();

                        // Iterate through all of the spreadsheets returned
                        for (SpreadsheetEntry spreadsheet : spreadsheets) {
                          // Print the title of this spreadsheet to the screen
                          System.err.println(spreadsheet.getTitle().getPlainText());
                        }
                    } catch (ServiceException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } catch (UserRecoverableAuthException e) {
                    // This is NECESSARY so the user can say, "yeah I want
                    // this app to have permission to read my spreadsheet."
                    Intent recoveryIntent = e.getIntent();
                    startActivityForResult(recoveryIntent, 2);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (GoogleAuthException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return null;
            }}).execute();
  } else if (requestCode == 2 && resultCode == RESULT_OK) {
      // After the user YAYs or NAYs our permission request, we are
      // taken here, so if we wanted to grab the token now we could.
  }

}

3
2017-08-15 20:12



我试过@ 2 nov 2015下载你的应用程序,但它没有用 - Din Islam Milon
您下载了应用程序或尝试从源代码构建?该应用程序似乎在Android M上为我工作。什么不起作用? @DinIslamMilon - Nels Beckman
它就像一个魅力。今天我已经从Play商店再次下载了你的应用程序,现在它工作得很好。谢谢。 - Din Islam Milon
最佳答案!谢谢NB! - Fasiha


(2017年2月) 问题(和大多数答案)现在已经过时了:1) GData API 是上一代Google API。虽然并非所有GData API都已被弃用, 所有 现代 Google API 做  使用 Google数据协议,2)谷歌 发布了一个新的Google表格API (v4;不是GData)2016年,3) Android Studio 现在是Eclipse上的首选IDE。要使用Google API,您需要获得 适用于Android的Google API客户端库 (或者对于更一般的Java, 适用于Java的Google API客户端库)。现在你已经准备好了。

要开始,最新的 表格API 比所有旧版本强大得多。最新的API提供旧版本中不可用的功能,即为开发人员提供对Sheet的编程访问,就像使用用户界面一样(创建冻结行,执行单元格格式化,调整行/列,添加数据透视表,创建图表等)。 )。

那就是说,是的,当没有足够好的(工作)示例浮动时,这很难,对吧?在官方文档中,我们尝试在尽可能多的语言中加入“快速启动”示例,以帮助您前进。本着这种精神,这里是 Android快速入门代码示例 以及更一般的 Java快速入门代码示例。为方便起见,这里是 表格API JavaDocs参考

另一个答案建议使用OAuth2进行数据授权,您可以使用上面的快速入门中的此auth代码段,以及右侧 范围

// Sheets RO scope
private static final String[] SCOPES = {SheetsScopes.SPREADSHEETS_READONLY};
    :

// Initialize credentials and service object
mCredential = GoogleAccountCredential.usingOAuth2(
        getApplicationContext(), Arrays.asList(SCOPES))
        .setBackOff(new ExponentialBackOff());

如果您对Python不“过敏”,我使用Sheets API(非移动设备)制作了几个带有更多“真实世界”示例的视频:

最后,请注意Sheets API执行 文件如上所述的定向功能。对于 文件等级访问,即导入,导出等,你使用的 Google Drive API 代替;专门针对手机,使用 Google Drive Android API。希望这可以帮助!


3
2018-03-02 03:25



你有任何Android应用程序的例子,它将保存在Google表格中的数据,并从工作表到可见。我检查谷歌示例代码仍然我对此感到困惑。如果你知道任何示例PLZ帖子链接它将帮助我很多。 - YBDevi
我个人没有,但除了上面链接的快速入门之外,请查看其他SO问答: stackoverflow.com/questions/40781620 - wescpy
感谢您的链接,我将尝试从中获取信息。 - YBDevi