【发布时间】:2016-04-07 14:48:50
【问题描述】:
我正在尝试使用YouTube Data API。他们创建了一个 Java 客户端。 Here is the sample 我试图跟随它向他们的服务器发送请求。我不能拥有这个
// Call the API and print results.
SearchListResponse searchResponse = search.execute();
List<SearchResult> searchResultList = searchResponse.getItems();
在主线程中,因为 Android 不允许在主线程上联网。所以我尝试使用AsyncTask
public class youtubeSearchTask extends AsyncTask<YouTube.Search.List, Void, SearchListResponse> {
@Override
protected SearchListResponse doInBackground(YouTube.Search.List... params) {
SearchListResponse a;
try {
a = params[0].execute();
} catch (java.io.IOException ioe) {
ioe.printStackTrace();
}
return a;
}
@Override
protected void onPostExecute(SearchListResponse searchResponse) {
List<SearchResult> searchResultList = searchResponse.getItems();
List<String> videoIds = new ArrayList<String>();
if (searchResultList != null) {
// Merge video IDs
for (SearchResult searchResult : searchResultList) {
videoIds.add(searchResult.getId().getVideoId());
}
Joiner stringJoiner = Joiner.on(',');
String videoId = stringJoiner.join(videoIds);
// Call the YouTube Data API's youtube.videos.list method to
// retrieve the resources that represent the specified videos.
try {
YouTube.Videos.List listVideosRequest = youtube.videos().list("snippet, statistics").setId(videoId);
new videoSearchTask().execute(listVideosRequest);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
我试过了
return params[0].execute();
来自doInBackground 方法,但它让我考虑了可能的IOException。所以我更改了代码,现在它说的是variable 'a' might not have been initialized。我该怎么办?
【问题讨论】:
标签: java android-asynctask youtube-data-api google-client