using AsyncTask to display data in ListView

前端 未结 2 1292
猫巷女王i
猫巷女王i 2020-12-11 09:30

I need me a little help. I need to use asynctask to display data in ListView. But I don\'t know how becouse I\'m new in Android programming ... thank you ve

相关标签:
2条回答
  • 2020-12-11 10:02

    Try this

    new MyAsyncTask.execute("http://10.10.10.10/data.php");
    

    Declare the task as

    class MyAsyncTask extends AsyncTask<String, Integer, ArrayList<HashMap<String, String>> > {
    
        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
    
        @Override
        protected ArrayList<HashMap<String, String>> doInBackground(String... params) {
    
            JSONObject json = JSONfunctions.getJSONfromURL(params[0]);
    
            try {
                JSONArray  ip = json.getJSONArray("ip");
    
                for (int i=0;i<ip.length();i++) {                     
                    HashMap<String, String> map = new HashMap<String, String>();    
                    JSONObject e = ip.getJSONObject(i);
    
                    map.put("id",  String.valueOf(i));
                    map.put("data1", e.getString("date"));
                    map.put("data2", "Location:" +  e.getString("location") + "   Status:" + e.getString("status"));
                    mylist.add(map);            
                } 
                return mylist
            } catch (JSONException e) {
                Log.e("log_tag", "Error parsing data "+e.toString());
            }
            return null;
        }
    
        @Override
        protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
            ListAdapter adapter = new SimpleAdapter(YourActivity.this, result , R.layout.main, 
                    new String[] { "data1", "data2" }, 
                    new int[] { R.id.item_title, R.id.item_subtitle });
            YourActivity.this.setListAdapter(adapter); // If Activity extends ListActivity
            final ListView lv = getListView();
            lv.setTextFilterEnabled(true);
    
        }
    

    Hope it helps.

    0 讨论(0)
  • 2020-12-11 10:09

    Do not download any data in your onCreate() - if it takes too long then you will get ANR exception (Activity Not Responding). You should use AsyncTask as in your question. For AsyncTask you have very good example on android site:

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

    you should put JSONfunctions.getJSONfromURL() inside doInBackground()

    and all whats below in onPostExecute()

    0 讨论(0)
提交回复
热议问题