Java 完成搜索后不显示ListView

Java 完成搜索后不显示ListView,java,android,listview,youtube-api,Java,Android,Listview,Youtube Api,我试图将ArrayList中的项显示到ListView,但遇到问题。当包含ListView的SearchActivity开始时,我会看到一个空白屏幕。有人能告诉我为什么吗 这里是SearchActivity.Java(顺便说一下,prettyprint函数用字符串填充ArrayList) package com.example.activity2; 导入java.util.ArrayList; 导入java.util.Iterator; 导入android.app.Activity; 导入and

我试图将ArrayList中的项显示到ListView,但遇到问题。当包含ListView的SearchActivity开始时,我会看到一个空白屏幕。有人能告诉我为什么吗

这里是SearchActivity.Java(顺便说一下,prettyprint函数用字符串填充ArrayList)

package com.example.activity2;
导入java.util.ArrayList;
导入java.util.Iterator;
导入android.app.Activity;
导入android.app.SearchManager;
导入android.content.Intent;
导入android.os.Bundle;
导入android.view.Menu;
导入android.view.MenuItem;
导入android.widget.ArrayAdapter;
导入android.widget.ListView;
导入com.google.api.services.youtube.model.SearchResult;
公共类SearchActivity扩展了活动{
ListView lst;
@凌驾
创建时受保护的void(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u search\u activity);
Intent=getIntent();
if(Intent.ACTION_SEARCH.equals(Intent.getAction())){
String query=intent.getStringExtra(SearchManager.query);
ArrayList结果=新建ArrayList();
Iterator it=results.Iterator();
prettyPrint(it,query);
lst=(ListView)findViewById(R.id.list);
ArrayAdapter=newArrayAdapter(这个,android.R.layout.simple\u list\u item\u 1,SearchYoutube.ytstuff);
lst.setAdapter(适配器);
}
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(R.menu.search,menu);
返回true;
}
@凌驾
公共布尔值onOptionsItemSelected(菜单项项){
//处理操作栏项目单击此处。操作栏将
//自动处理Home/Up按钮上的点击,只要
//在AndroidManifest.xml中指定父活动时。
int id=item.getItemId();
if(id==R.id.action\u设置){
返回true;
}
返回super.onOptionsItemSelected(项目);
}
}
以下是相应的xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.activity2.SearchActivity"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/list"
        android:layout_width="309dp"
        android:layout_height="309dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="52dp" >
    </ListView>

</LinearLayout>

更新:

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 ArrayList<String> ytstuff = 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;

    /**
     * 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();
            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<27;i=i+2)
                    for (int j= 1;j <28;i=i+2)
                        if (j-i == 1)
                        {
                ytstuff.set(i,rId.getVideoId()); //first thing is video id
                ytstuff.set(j,singleVideo.getSnippet().getTitle()); //second thing is title
                        }
            }
        }
    }

}
package com.example.activity2;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.util.ArrayList;
导入java.util.Iterator;
导入java.util.List;
导入java.util.Properties;
导入com.google.api.client.googleapis.json.GoogleJsonResponseException;
导入com.google.api.client.http.HttpRequest;
导入com.google.api.client.http.HttpRequestInitializer;
导入com.google.api.services.youtube.youtube;
导入com.google.api.services.youtube.model.ResourceId;
导入com.google.api.services.youtube.model.SearchListResponse;
导入com.google.api.services.youtube.model.SearchResult;
导入com.google.api.services.youtube.model.缩略图;
/**
*打印与搜索词匹配的视频列表。
*
*@作者杰里米·沃克
*/
公共类搜索YouTube{
公共静态ArrayList=新ArrayList();
/**
*定义一个全局变量,该变量标识
*包含开发人员的API密钥。
*/
私有静态最终字符串属性\u FILENAME=“youtube.PROPERTIES”;
返回的私有静态最终长视频数=25;
/**
*定义将要使用的Youtube对象的全局实例
*发出YouTube数据API请求。
*/
私有静态YouTube YouTube;
/**
*初始化YouTube对象以搜索YouTube上的视频。然后
*显示结果集中每个视频的名称和缩略图。
*
*@param args命令行args。
*/
公共静态void main(字符串[]args){
//从属性文件中读取开发人员密钥。
属性=新属性();
试一试{
InputStream in=SearchActivity.class.getResourceAsStream(“/”+属性\u文件名);
属性。荷载(in);
}捕获(IOE异常){
System.err.println(“读取“+PROPERTIES\u FILENAME+”:“+e.getCause()时出错)
+“:”+e.getMessage());
系统出口(1);
}
试一试{
//此对象用于发出YouTube数据API请求
//争论是必需的,但既然我们什么都不需要
//初始化当HttpRequest初始化时,我们重写
//接口并提供无操作功能。
youtube=new youtube.Builder(Auth.HTTP_传输,Auth.JSON_工厂,新的HttpRequestInitializer(){
公共无效初始化(HttpRequest请求)引发IOException{
}
}).setApplicationName(“youtube cmdline搜索示例”).build();
//提示用户输入查询术语。
字符串queryTerm=getInputQuery();
//定义检索搜索结果的API请求。
YouTube.Search.List Search=YouTube.Search().List(“id,snippet”);
//从Google开发者控制台为设置开发者密钥
//未经身份验证的请求。请参阅:
// https://console.developers.google.com/
字符串apiKey=properties.getProperty(“youtube.apiKey”);
search.setKey(apiKey);
search.setQ(queryTerm);
//将搜索结果限制为仅包含视频。请参阅:
// https://developers.google.com/youtube/v3/docs/search/list#type
search.setType(“视频”);
//为了提高效率,只检索
//应用程序使用。
search.setFields(“项(id/kind、id/videoId、片段/标题、片段/缩略图/默认值/url)”;
search.setMaxResults(视频数量)
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 ArrayList<String> ytstuff = 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;

    /**
     * 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();
            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<27;i=i+2)
                    for (int j= 1;j <28;i=i+2)
                        if (j-i == 1)
                        {
                ytstuff.set(i,rId.getVideoId()); //first thing is video id
                ytstuff.set(j,singleVideo.getSnippet().getTitle()); //second thing is title
                        }
            }
        }
    }

}