从服务器获取数据并在单独的线程中显示listview

时间:2017-08-15 12:11:58

标签: android multithreading listview

我想从seprate线程访问和填充ListView ......但是它的对象在新线程中没有它的范围......它的解决方案是什么?

ListView FilesListView;
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    FilesListView= (ListView)findViewById(R.id.remoteFilesListView);



new Thread ( new Runnable() {

        @Override
        public void run() {

    // fetch data from server…
    String xmlFormServer = Worker.getXmlresponse();
    Log.d("Response from Serever", xmlFormServer;


    // FilesListView object of Listview is not accessable in this thread to populate data… 
        }
    }).start();

}

2 个答案:

答案 0 :(得分:0)

您应该为ListView实现适配器

尝试按照下面的模式

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    FilesListView = (ListView) findViewById(R.id.remoteFilesListView);

    adapter = new SimpleAdapter(/*...*/); // implement your custom adapter or use native
 //        1. set adapter into FileListView
    FilesListView.setAdapter(adapter);

    new AsyncTask<Void, Void, List>() {

        @Override
        protected List doInBackground(Void... params) {
            String xmlFormServer = Worker.getXmlresponse();
            Log.d("Response from Serever", xmlFormServer;

 //                2. READ YOUR DATA HERE

            List result = null; //

 //                3. send result to ui thread
            return result;
        }

        @Override
        protected void onPostExecute(List list) {
 //                the method executes on ui thread
 //                4. put your data into adapter
 //                you should implement the method or create native adapter
            adapter.setDate(list);
 //                5. refresh list - only UI THREAD can do this
            adapter.notifyDataSetChanged();
            super.onPostExecute(list);
        }
    }.execute();
}

答案 1 :(得分:0)

您无法在其他线程上填充填充ListView / RecyclerView或任何其他视图或组件。

必须在MainThread(UIThread)上。

查看此链接,了解有关Android中UIThread及其工作原理的更多信息。

What is the Android UiThread (UI thread)

但是,您可以异步地将逻辑或IO操作放在不同的线程上,然后您可以将结果填充到UI线程上。

一种方法是使用AsyncTask。

https://developer.android.com/reference/android/os/AsyncTask.html

像这样......

new AsyncTask<Void, Void, String >() {

    // Runs on Worker thread
    @Override
    protected String doInBackground(Void... params) {
        String xmlFormServer = Worker.getXmlresponse();
        return xmlFormServer;
    }

    // Runs on Ui thread
    @Override
    protected void onPostExecute(String data) {
        if(data != null){
            adapter.setDate(data);
            adapter.notifyDataSetChanged();
        }

    }
}.execute();