Android:如何使 ListView 定期更新?

发布于 2024-08-19 20:42:19 字数 3949 浏览 4 评论 0原文

我从来没有以简单的方式完成这个工作。抱歉,如果我说得有点含糊的话。我将尝试详细说明我正在尝试做的事情。我正在尝试构建一个从网络服务获取数据的列表视图。一旦初始化了列表视图,我想继续定期轮询网络服务器并更新列表视图的内容。为此,我正在做这样的事情:

public class SampleAutoUpdateList extends Activity {

     //Autoupdate handler
     private Handler handler = new Handler();
     private Runnable updater = new Runnable() {

     public void run() {

       /*
        * Update the list 
        */

       try {
          Log.i("UPDATE", "Handler called");
          searchAdapter = getFeed(URL);
          searchAdapter.notifyDataSetChanged();
          handler.postDelayed(this, Configuration.REFRESH_INTERVAL);
       } catch(Exception e) {
          Log.e("UPDATE ERROR", e.getMessage());
       }

      }

     };

     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);
      setContentView(R.layout.linearmode);
      this.context = this;

      searchAdapter = getFeed(URL);
      LinearLayout l2 = (LinearLayout) findViewById(R.id.secondaryLayout);
      ListView list = new ListView(context);
      l2.addView(list);
      // display UI
      UpdateDisplay(list);
      updater.run();
     }

     private SearchAdapter getFeed(String URL) {
        try
        {
            SearchHandler handler = new SearchHandler();

            URL url = new URL(URL);

            String data = convertStreamToString(url.openStream());
            data = data.substring(data.indexOf('['), data.length()-1);
                    handler.parseJSON(data);

            return handler.getFeed();
        }
        catch (Exception ee)
        {
            // if we have a problem, simply return null
            Log.e("getFeed", ee.getMessage());
            return null;
        }
    }

    private void UpdateDisplay(View searchView) {
        // TODO Auto-generated method stub
        // TODO Auto-generated method stub
        searchList = (ListView) searchView;

        myProgressDialog = ProgressDialog.show(this,       
                "Please wait...", "Loading search....", true); 

        new Thread() { 
            public void run() { 
                try{ 

                    Thread.sleep(2000); 
                } catch (Exception e) {  } 

                runOnUiThread(new Runnable() { 

                    @Override 
                    public void run() { 

                        if (searchAdapter == null)
                        {
                            Log.e("ERROR", "No Feed Available");
                            return;
                        }

                        searchAdapter.setContext(context);
                        searchList.setAdapter(searchAdapter);
                        searchList.setSelection(0);
                    } 
                }); 

                // Dismiss the Dialog 
                myProgressDialog.dismiss(); 
            } 
        }.start(); 
    }
}

SearchHandler 类很简单:

public class SearchHandler  extends DefaultHandler {
    SearchAdapter _adapter;
    SearchItem _item;

    public SearchHandler()
    {
    }

    public SearchAdapter getFeed()
    {
        return _adapter;
    }

    public void parseJSON(String data) {
        // TODO Auto-generated method stub
        _adapter = new SearchAdapter();
        JSONArray parseArray;
        try {
            parseArray = new JSONArray(data);
                    for (int i=0; i < parseArray.length(); i++) {

                SearchItem item = new SearchItem();

                JSONObject jsonUser = parseArray.getJSONObject(i);
                item.set_from(jsonUser.getString ("from"));
                item.set_msg(jsonUser.getString("msg"));
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

无论我做什么,处理程序都会被调用并获取新项目,但列表永远不会刷新...有关可能出现问题的任何想法?

I never got this working in a straightforward manner. Sorry if I'm being a little vague. I'll try to elaborate on what I'm trying to do. I am trying to build a listview that grabs its data from a webservice. Once I initialize a listview, I want to keep polling the webserver periodically and update the contents of the listview. For this I am doing something like this:

public class SampleAutoUpdateList extends Activity {

     //Autoupdate handler
     private Handler handler = new Handler();
     private Runnable updater = new Runnable() {

     public void run() {

       /*
        * Update the list 
        */

       try {
          Log.i("UPDATE", "Handler called");
          searchAdapter = getFeed(URL);
          searchAdapter.notifyDataSetChanged();
          handler.postDelayed(this, Configuration.REFRESH_INTERVAL);
       } catch(Exception e) {
          Log.e("UPDATE ERROR", e.getMessage());
       }

      }

     };

     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);
      setContentView(R.layout.linearmode);
      this.context = this;

      searchAdapter = getFeed(URL);
      LinearLayout l2 = (LinearLayout) findViewById(R.id.secondaryLayout);
      ListView list = new ListView(context);
      l2.addView(list);
      // display UI
      UpdateDisplay(list);
      updater.run();
     }

     private SearchAdapter getFeed(String URL) {
        try
        {
            SearchHandler handler = new SearchHandler();

            URL url = new URL(URL);

            String data = convertStreamToString(url.openStream());
            data = data.substring(data.indexOf('['), data.length()-1);
                    handler.parseJSON(data);

            return handler.getFeed();
        }
        catch (Exception ee)
        {
            // if we have a problem, simply return null
            Log.e("getFeed", ee.getMessage());
            return null;
        }
    }

    private void UpdateDisplay(View searchView) {
        // TODO Auto-generated method stub
        // TODO Auto-generated method stub
        searchList = (ListView) searchView;

        myProgressDialog = ProgressDialog.show(this,       
                "Please wait...", "Loading search....", true); 

        new Thread() { 
            public void run() { 
                try{ 

                    Thread.sleep(2000); 
                } catch (Exception e) {  } 

                runOnUiThread(new Runnable() { 

                    @Override 
                    public void run() { 

                        if (searchAdapter == null)
                        {
                            Log.e("ERROR", "No Feed Available");
                            return;
                        }

                        searchAdapter.setContext(context);
                        searchList.setAdapter(searchAdapter);
                        searchList.setSelection(0);
                    } 
                }); 

                // Dismiss the Dialog 
                myProgressDialog.dismiss(); 
            } 
        }.start(); 
    }
}

And the SearchHandler class is simple:

public class SearchHandler  extends DefaultHandler {
    SearchAdapter _adapter;
    SearchItem _item;

    public SearchHandler()
    {
    }

    public SearchAdapter getFeed()
    {
        return _adapter;
    }

    public void parseJSON(String data) {
        // TODO Auto-generated method stub
        _adapter = new SearchAdapter();
        JSONArray parseArray;
        try {
            parseArray = new JSONArray(data);
                    for (int i=0; i < parseArray.length(); i++) {

                SearchItem item = new SearchItem();

                JSONObject jsonUser = parseArray.getJSONObject(i);
                item.set_from(jsonUser.getString ("from"));
                item.set_msg(jsonUser.getString("msg"));
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

No matter what I do, the handler gets called and the new items are fetched, but the list is never refreshed... Any ideas on what could be going wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吖咩 2024-08-26 20:42:19

好吧,遵循您的代码有点困难,因为您只有代码的一小部分,并且几乎没有真正相关的位。例如,根据您的可用代码,您的列表应该永远为空,因为您从未将 searchAdapterListView 关联...至少在您显示的代码中。

话虽这么说,以下几行似乎特别奇怪:

        searchAdapter = getFeed(URL);
        searchAdapter.notifyDataSetChanged();

我将假设 getFeed() (未显示)创建某种新的 ListAdapter 。如果 getFeed() 正在创建一个新的 ListAdapter,则无需对其调用 notifyDataSetChanged(),因为其数据集还没有调用改变了——它是全新的。此外,除非您将此新的 ListAdapter 关联到您的 ListView,否则新的 ListAdapter 将不起作用。

如果我找错了树,请考虑在示例中添加一些行来显示 getFeed() 的实现以及使用 searchAdapter 的位置。

Well, it is a little bit difficult to follow your code, since you only have a fragment of it, and few of the really relevant bits. For example, based on your available code, your list should be forever empty, since you never associate the searchAdapter with a ListView...at least in the code you have shown.

That being said, the following lines seem particularly odd:

        searchAdapter = getFeed(URL);
        searchAdapter.notifyDataSetChanged();

I am going to assume that getFeed() (not shown) creates a new ListAdapter of some sort. If getFeed() is creating a new ListAdapter, there is no need to call notifyDataSetChanged() on it, as its data set hasn't changed -- it's brand new. Moreover, unless you are associating this new ListAdapter to your ListView, the new ListAdapter will have no effect.

If I'm barking up the wrong tree, consider adding lines to your sample showing the implementation of getFeed() and where you are using searchAdapter.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文