【问题标题】:ListView does not display after completing search完成搜索后 ListView 不显示
【发布时间】:2014-08-08 22:49:57
【问题描述】:

我正在尝试将 ArrayList 中的项目显示到 ListView,但遇到了问题。当包含 ListView 的 SearchActivity 开始时,我得到一个空白屏幕。谁能告诉我为什么?

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

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.widget.ArrayAdapter;
import android.widget.ListView;

import com.google.api.services.youtube.model.SearchResult;

public class SearchActivity extends Activity {
    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);
          ArrayList<SearchResult> results = new ArrayList<SearchResult>();
          Iterator<SearchResult> it = results.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);
    }
    }

    @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);
    }
}

这里是对应的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>

更新:

搜索Youtube.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
                        }
            }
        }
    }

}

【问题讨论】:

  • 什么是SearchYoutube.ystuff?它是否包含results 列表?如果不是,则列表为空,因为您没有使用结果填充它。
  • ytstuff 是视频 ID 和标题的数组列表。它在漂亮打印中定义。这是 SearchYoutube 类中 prettyPrint 的定义:freetexthost.com/54gqkenur3
  • @AedonEtLIRA 当我看到像“ytstuff”这样的名字时......没有任何意义,除了混淆之外没有任何东西给代码带来任何东西^^
  • @martialdidit 同意。 OP,您可能应该将该符号更改为更具描述性的符号....
  • @martialdidit 注意到。不过,您对解决这个问题有什么建议吗?

标签: java android listview youtube-api


【解决方案1】:

那么是的,您的列表视图的适配器没有提供任何内容。这就是活动为空白的原因。此外,如果您没有传递 Intent.ACTION_SEARCH 操作,那么适配器将再次为空,从而导致空白活动。

【讨论】:

  • 好的,我正在传递这个意图。你能解释为什么 ytstuff ArrayList 没有被填充吗?我将使用 SearchYoutube 类编辑 OP。
  • @yoyoyo 因为results 是空的。您正在遍历一个空列表。
  • 哦,那么看看 SearchYoutube 类,会填充 searchResultList 吗?
  • @yoyoyo 没有。因为您传入的是空的 results 迭代器。迭代器 您的 while 循环要求结果迭代器至少有 1 个项目。
  • 是的,我明白了。但如果我要编辑成这样的东西。这应该没问题吧? freetexthost.com/g1gohfhi13 虽然我现在收到一个错误,说 searchResultList 无法解析或不是一个字段。
猜你喜欢
  • 1970-01-01
  • 2017-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多