2013-02-18 29 views
0

我有一個活動,但3個佈局。 ListView是登錄後顯示的佈局的一部分。這就是爲什麼我無法設置ArrayAdapter onCreate,因爲我的ListView尚未初始化。我嘗試了以下this教程,但我無法重現這些步驟。在本教程中,作者做了一切創建。Android從JSON數組中添加ListView項目

我試圖做這樣說:

ArrayList<String> listItems=new ArrayList<String>(); 
ArrayAdapter<String> adapter; 

... 

    public class getcontacts extends AsyncTask<Void, Void, Boolean> { 
    @Override 
    protected Boolean doInBackground(Void... params) { 

...HERE I AM FETCHING DATA... 

listItems.add(json_data.getString("login") + " " + derp); 
} 

@Override 
    protected void onPostExecute(final Boolean success) { 
     getc = null; 


     ac = new addcontacts(); 
     ac.execute(true); 

這裏是addcontacts類的代碼:

public class addcontacts extends ListActivity { 


    protected void onCreate() { 


     adapter=new ArrayAdapter<String>(this, 
        android.R.layout.simple_list_item_1, 
        listItems); 
     setListAdapter(adapter); 

     adapter.notifyDataSetChanged(); 

    } 
    protected void execute(final Boolean success) { 

    done = true; 
    } 


} 

而且佈局:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical" > 



<TextView 
    android:id="@+id/textView1" 
    android:layout_width="match_parent" 
    android:layout_height="188dp" 
    android:layout_weight="0.53" 
    android:text="Fetching contact list" /> 

<ListView 
    android:id="@+id/listView1" 
    android:layout_width="match_parent" 
    android:layout_height="106dp" > 
</ListView> 

</LinearLayout> 

的ListView不包含任何東西。我在調試器中檢查過listItems有所有項目,所以適配器有問題。

+0

您不像通過顯式的Contstructor那樣實例化活動。你也應該注意你寫的東西,'onCreate()'需要一個Bundle作爲參數。使用'@ Override'註解,它會使得更容易。另外,請使用適當的命名規則,並告訴我們每個類是如何設置的。如果AsyncTask和ListActivity都是同一個文件的一部分,不要將它們分開。 – 2013-02-18 18:44:15

+0

這裏是完整的代碼:http://pastebin.com/dA6dcZRv – Disa 2013-02-18 18:55:08

回答

1

我建議您採取下列措施:

  1. Activity類初始化ListViewAdapter空列表。
  2. 創建BaseAdapter的子類以獲得對其的更多控制。
  3. 通過Adapter並通過構造函數列表Adapter
  4. 在您的AsyncTask子類中通過AdapterList
  5. 在您的doInBackground()方法執行從服務器獲取數據和 將每個項目添加到List
  6. 如果你想創建懶適配器所以每個產品加入List,打電話 publishProgress()onProgressUpdate()方法調用 yourAdapter.notifyDataSetChanged()
  7. 如果沒有,工作完成後,在onPostExecute()方法調用 yourAdapter.notifyDataSetChanged()
  8. 現在它應該可以工作。

你完成了。

+0

你能給一些示例代碼? – Disa 2013-02-18 18:53:51

+0

這裏是非常相似的例子['Android自定義ListView與圖像和文本'](http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/)其中數據從XML中解析並用更新動態添加到List中。 – Sajmon 2013-02-18 18:56:51

+0

看起來很複雜。還有另一種更簡單的方法嗎? – Disa 2013-02-18 19:02:45

相關問題