5

後,用一個ArrayAdapter ListView控件重置我使用的是ListAdapter填充這樣一個ListView:如何獲取數據

static final String[] PROBLEMS = new String[] {"one", "two", "three" }; 

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

    setListAdapter(new ArrayAdapter<String>(this, R.layout.my_problems, PROBLEMS)); 

    ListView lv = getListView(); 
    lv.setTextFilterEnabled(true); 

之後,我想提出我的服務器遠程調用以獲取更多數據該列表與一個AsyncTask調用,並且當我從服務器獲取數據時,我不知道如何填充和重置ListView。到目前爲止,我有這樣的事情:

@Override 
    protected void onPostExecute(String result) 
    {  
      // Unwrap the stuff from the JSON string     
      String problem_title = null; 
      String problem_id = null; 

      try 
      { 
       JSONArray obj = new JSONArray(result); 
       JSONObject o = obj.getJSONObject(0);      

       Log.d("Title: " , "" + o.getString("problem_title"));  
       Log.d("id: " , "" + o.getString("problem_id"));  

       problem_title = o.getString("problem_title"); 
       problem_id = o.getString("problem_id"); 
      } 
      catch (Exception e) 
      { 
      } 

      // Now not sure what to do :) 
      // How do I reset the list that I had set up above? 
       } 

我可以使結果到適當的結構化數據重置列表中,但不知道如何做到這一點。有人可以幫忙嗎? :)

回答

16

我使用這種方式,

values = new ArrayList<String>(); 
    //put anything you want in values as start 
    adapter = new ArrayAdapter<String>(this,R.layout.notification, values); 
    setListAdapter(adapter); 

然後

//change values array with your new data then update the adapter 
    adapter.notifyDataSetChanged(); 

然後ListView中的內容將在時間改變執行此功能

+0

現在讓我說......我會告訴你如何去:) – GeekedOut 2012-03-10 15:22:18

+0

啊好吧,這是編譯!謝謝! – GeekedOut 2012-03-10 15:27:12

+0

沒問題,祝你好運 – 2012-03-10 15:30:10

3
adapter.notifyDataSetChanged(); 

是不錯的選擇要做到這一點,但有時候不會按我們的需要工作。在這種情況下,您可以再次設置適配器,並刷新您的列表視圖。但這不是一個好的選擇,因爲它再次生成整個listview,所以這會導致性能下降。而你的應用程序變得緩慢。

7

如果您只是想更改數據集,則不需要重新初始化適配器。試試下面的代碼 -

adapter.clear(); 
for(int i = 0;i<categoriesArray.length;i++){ 
    adapter.add(categoriesArray[i]); 
} 

如果需要的話,你可以更改通知適配器也是如此,雖然它不應該是必要的。

adapter.notifyDataSetChanged(); 

如果你靶向API級別11或以上,你就可以使用適配器的addAll()方法。因爲它更高效。

adapter.clear(); 
adapter.addAll(categoriesArray);