2013-02-18 30 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

相关问题