我正在开发一款Android应用,它包含一项功能,即用户使用他们的Google帐户登录后,我们将访问他们的Google工作表以获取数据库。我试图搜索Google Spreadsheet Api但不清楚如何使用它。
当然,我可以从下面的代码中获取公开表格中的数据,但问题是获取私人表格。
private List<String> getDataFromApi() throws IOException {
String spreadsheetId = "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms";
String range = "Class Data!A2:E";
List<String> results = new ArrayList<String>();
ValueRange response = this.mService.spreadsheets().values()
.get(spreadsheetId, range)
.execute();
List<List<Object>> values = response.getValues();
if (values != null) {
results.add("Name, Major");
for (List row : values) {
results.add(row.get(0) + ", " + row.get(4));
}
}
return results;
}
我也在某个地方搜索并找到了下面的代码,但它抛出了NoSuchMethodError异常,我很困惑什么是&#34;用户名&#34;和#34;密码&#34;在line spreadsheet.setUserCredentials。
中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();
}
所以任何人都知道如何做到这一点或有示例代码请分享我。提前谢谢!
答案 0 :(得分:2)
最后,我找到了我的问题的解决方案,现在我在这里发帖,以帮助其他任何面临同样问题的人克服它。
首先,转到https://console.developers.google.com并创建与您的项目相关联的新OAuth客户端ID凭据。
现在在你的android项目中,在依赖项中添加这些库:
dependencies { compile 'com.google.android.gms:play-services-auth:9.2.1' compile files('libs/gdata-client-1.0.jar') compile files('libs/gdata-client-meta-1.0.jar') compile files('libs/gdata-core-1.0.jar') compile files('libs/gdata-core-1.0-sources.jar') compile files('libs/gdata-spreadsheet-3.0.jar') compile files('libs/gdata-spreadsheet-meta-3.0.jar') compile files('libs/guava-10.0.1.jar') compile files('libs/jsr305-1.3.9.jar') }
在AndroidManifest.xml中添加以下权限:
uses-permission android:name =&#34; android.permission.INTERNET&#34;
uses-permission android:name =&#34; android.permission.GET_ACCOUNTS&#34;
同时在<application></application>
标记中添加:
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
CODE如下:
public class DownloadDatabaseActivity extends AppCompatActivity {
private static final String TAG = "my_log";
public static ProgressDialog mProgressDialog;
String spreadsheetName;
String worksheetName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download_database);
Button btnDownload = (Button) findViewById(R.id.btnDownload);
btnDownload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText etSpreadsheetName = (EditText) findViewById(R.id.etSpreadsheetName);
EditText etWorksheetName = (EditText) findViewById(R.id.etWorksheetName);
spreadsheetName = etSpreadsheetName.getText().toString();
worksheetName = etWorksheetName.getText().toString();
Intent intent = AccountPicker.newChooseAccountIntent(null, null,
new String[]{"com.google"}, false, null, null, null, null);
startActivityForResult(intent, 1);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
Log.d(TAG, "--> enter first if");
final String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
new DownloadTask(this).execute(accountName, spreadsheetName, worksheetName);
} else if (requestCode == 2 && resultCode == RESULT_OK) {
Log.d(TAG, "--> enter second if");
}
}
////////////////////////////////////////////////////////////////////////////
private class DownloadTask extends AsyncTask<String, Void, String> {
private Context context;
// constructor
public DownloadTask(Context context) {
this.context = context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
showProgressDialog(context);
}
@Override
protected String doInBackground(String... params) {
String mEmail = params[0]; // your google account name
String mType = "com.google";
Account account = new Account(mEmail, mType);
String scopes = "oauth2:https://spreadsheets.google.com/feeds "
+ "https://www.googleapis.com/auth/plus.login "
+ "https://www.googleapis.com/auth/drive";
String token = null;
try {
token = GoogleAuthUtil.getToken(getApplicationContext(), account, scopes);
} catch (IOException e) {
Log.e(TAG, e.getMessage());
} catch (UserRecoverableAuthException e) {
Intent recoveryIntent = e.getIntent();
startActivityForResult(recoveryIntent, 2);
} catch (GoogleAuthException e) {
Log.e(TAG, e.getMessage());
}
try {
SpreadsheetService service = new SpreadsheetService("MySpreadsheetIntegration-v1");
service.setAuthSubToken(token);
URL SPREADSHEET_FEED_URL = new URL(
"https://spreadsheets.google.com/feeds/spreadsheets/private/full");
SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
Log.d(TAG, "spreadsheets.size() = " + spreadsheets.size());
for (SpreadsheetEntry spreadsheet : spreadsheets) { // outer for loop
if (spreadsheet.getTitle().getPlainText().equalsIgnoreCase(params[1])) { // your spreadsheet name
List<WorksheetEntry> worksheets = spreadsheet.getWorksheets();
for (WorksheetEntry worksheet : worksheets) { // inner for loop
String title = worksheet.getTitle().getPlainText();
if (title.equalsIgnoreCase(params[2])) { // your worksheet name
Log.d(TAG, "Worksheet name: " + title);
URL listFeedUrl = worksheet.getListFeedUrl();
ListFeed listFeed = service.getFeed(listFeedUrl, ListFeed.class);
Log.d(TAG, "Number of row = " + listFeed.getTotalResults());
// scan through each row in worksheet
for (ListEntry row : listFeed.getEntries()) {
String rowTitle = row.getTitle().getPlainText();
ArrayList<String> currentRow = new ArrayList<>();
// get elements in current row stored in ArrayList
for (String element : row.getCustomElements().getTags()) {
if (!row.getCustomElements().getValue(element).equals(rowTitle))
currentRow.add(row.getCustomElements().getValue(element));
}
// Log.d(TAG, "currentRow.size() = "+currentRow.size());
// do your work here with the data received
}`
break; // break inner
}
}
break; // break outer
}
}
} catch (Exception e) {
e.printStackTrace();
}
return token;
}
@Override
protected void onPostExecute(String token) {
Log.d(TAG, "Token Value: " + token);
hideProgressDialog();
}
}
}
答案 1 :(得分:1)
您在setUserCredentials
中设置的用户名和密码是用于验证对服务器的请求的凭据。关于如何获取私人表格的问题,我认为documentation可以帮助您。有关更多示例和信息,请查看此example code。