我有一个函数prettyPrint(),它应该在进行Youtube搜索后用字符串填充数组。当我尝试使用ArrayAdapter从另一个活动访问它时,应用程序崩溃了,logcat告诉我数组为空。
这是我定义方法prettyPrint()的类,SearchYoutube.java(这是最后一个方法):
package com.example.activity2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.ResourceId;
import com.google.api.services.youtube.model.SearchListResponse;
import com.google.api.services.youtube.model.SearchResult;
import com.google.api.services.youtube.model.Thumbnail;
/**
* Print a list of videos matching a search term.
*
* @author Jeremy Walker
*/
public class SearchYoutube {
public static List<SearchResult> searchListResults = new ArrayList();
/**
* Define a global variable that identifies the name of a file that
* contains the developer's API key.
*/
private static final String PROPERTIES_FILENAME = "youtube.properties";
private static final long NUMBER_OF_VIDEOS_RETURNED = 25;
public static String [] ytstuff = new String[(int) NUMBER_OF_VIDEOS_RETURNED];
/**
* Define a global instance of a Youtube object, which will be used
* to make YouTube Data API requests.
*/
private static YouTube youtube;
/**
* Initialize a YouTube object to search for videos on YouTube. Then
* display the name and thumbnail image of each video in the result set.
*
* @param args command line args.
*/
public static void main(String[] args) {
// Read the developer key from the properties file.
Properties properties = new Properties();
try {
InputStream in = SearchActivity.class.getResourceAsStream("/" + PROPERTIES_FILENAME);
properties.load(in);
} catch (IOException e) {
System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause()
+ " : " + e.getMessage());
System.exit(1);
}
try {
// This object is used to make YouTube Data API requests. The last
// argument is required, but since we don't need anything
// initialized when the HttpRequest is initialized, we override
// the interface and provide a no-op function.
youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
}
}).setApplicationName("youtube-cmdline-search-sample").build();
// Prompt the user to enter a query term.
String queryTerm = getInputQuery();
// Define the API request for retrieving search results.
YouTube.Search.List search = youtube.search().list("id,snippet");
// Set your developer key from the Google Developers Console for
// non-authenticated requests. See:
// https://console.developers.google.com/
String apiKey = properties.getProperty("youtube.apikey");
search.setKey(apiKey);
search.setQ(queryTerm);
// Restrict the search results to only include videos. See:
// https://developers.google.com/youtube/v3/docs/search/list#type
search.setType("video");
// To increase efficiency, only retrieve the fields that the
// application uses.
search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
// Call the API and print results.
SearchListResponse searchResponse = search.execute();
List<SearchResult> searchResultList = searchResponse.getItems();
searchListResults = searchResultList;
if (searchResultList != null) {
prettyPrint(searchResultList.iterator(), queryTerm);
}
} catch (GoogleJsonResponseException e) {
System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
} catch (IOException e) {
System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
}
/*
* Prompt the user to enter a query term and return the user-specified term.
*/
private static String getInputQuery() throws IOException {
String inputQuery = "";
System.out.print("Please enter a search term: ");
BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
inputQuery = bReader.readLine();
if (inputQuery.length() < 1) {
// Use the string "YouTube Developers Live" as a default.
inputQuery = "YouTube Developers Live";
}
return inputQuery;
}
/*
* Prints out all results in the Iterator. For each result, print the
* title, video ID, and thumbnail.
*
* @param iteratorSearchResults Iterator of SearchResults to print
*
* @param query Search query (String)
*/
public static void prettyPrint(Iterator<SearchResult> iteratorSearchResults, String query) {
if (!iteratorSearchResults.hasNext()) { }
while (iteratorSearchResults.hasNext()) {
SearchResult singleVideo = iteratorSearchResults.next();
ResourceId rId = singleVideo.getId();
// Confirm that the result represents a video. Otherwise, the
// item will not contain a video ID.
if (rId.getKind().equals("youtube#video")) {
Thumbnail thumbnail = singleVideo.getSnippet().getThumbnails().getDefault();
for (int i=0;i<25;i=i+2)
{
for (int j= 1;j <26;i=i+2)
{
if (j-i == 1)
{
ytstuff[i] = rId.getVideoId(); //first thing is video id
ytstuff[j] = singleVideo.getSnippet().getTitle(); //second thing is title
}
}
}
}
}
}
}
这是我调用prettyPrint()的活动,SearchActivity.java
package com.example.activity2;
import java.util.ArrayList;
import java.util.Iterator;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.api.services.youtube.model.SearchResult;
public class SearchActivity extends Activity implements AdapterView.OnItemClickListener {
ListView lst;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_activity);
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
Iterator<SearchResult> it = SearchYoutube.searchListResults.iterator();
SearchYoutube.prettyPrint(it, query);
lst = (ListView) findViewById(R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,SearchYoutube.ytstuff);
lst.setAdapter(adapter);
lst.setOnItemClickListener(this);
}
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view,int i, long l)
{
TextView temp= (TextView) view;
Toast.makeText(this,temp.getText()+""+i,Toast.LENGTH_SHORT).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.search, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
我有一种预感,我可能误解了Youtube API方法到底在做什么。如果我只是创建一个字符串数组并将其传递到适配器,那么SearchActivity中的代码就可以完美地工作,所以我认为SearchYoutube类有问题。
第二个for循环不会使j增加2,而是使i增加2。