调用notifyDataSetChanged()会抛出异常

时间:2010-10-07 15:53:19

标签: java android adapter

我有一个ListView,我绑定到适配器。适配器是我的主类的受保护成员。我有一个侦听器线程,它接收数据并更新我的适配器的源列表。当我调用适配器的notifyDataSetChanged()方法时,抛出异常:

  

运行时异常:PhoneLayoutInflater(LayoutInflater).inflate(int,   ViewGroup,boolean)line:322

我已经读过必须在UI线程上调用notifyDataSetChanged()方法,而我正在这样做。实际上,为了确保,我甚至在UI线程上更新了ListView的数据源。我在侦听器线程中所做的就是更新一个包含数据的受保护成员。这是我正在做的一个例子(请注意,我没有调用AsyncTask的代码部分,但它是从侦听器触发的):

public class main extends Activity() {

 protected LinkedList<HashMap<String, String>> adapterDataList = new LinkedList<HashMap<String, String>>();
 protected MyDataObject dataObject;
 protected SimpleAdapter dataAdapter;

 @Override
 public void onCreate(Bundle savedInstanceState) {

     //call parent oncreate
     super.onCreate(savedInstanceState);

  //display the main form
  setContentView(R.layout.main);

  //get a handle on the score list view elements
  ListView dataList = (ListView)(findViewById(R.id.datalist));

  //link the adapter and the data source
  dataAdapter = new SimpleAdapter(this, adapterDataList, R.layout.row, new String[]{"name","address"}, new int[]{R.id.username,R.id.address});

  dataList.setAdapter(dataAdapter);

 }

 protected void refreshData() {
  adapterDataList.clear();
  Iterator<MyData> iter = MyDataObject.iterator();
  while(iter.hasNext()) {
   HashMap<String, String> item = new HashMap<String, String>()
   item.put("name", iter.name);
   item.put("address", iter.address);
   adapterDataList.add(item);
  }

  dataAdapter.notifyDataSetChanged();
 }

 private class DataTask extends AsyncTask<Data, Void, Data> {
  protected void onPostExecute(Data data) {
   dataObject = data;
   runOnUiThread (new Runnable() { public void run() {
    refreshScores();
   }});
  }
 }

 ...
}

有没有人对我为什么会遇到此异常有任何指示或想法?非常感谢任何帮助。

修改 以下是布局文件,如下所示: main.xml中:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ptl="http://schemas.android.com/apk/res/com.mod0.pubtrivialive"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/datalistcontainer">

    <ListView android:id="@+id/datalist" 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

</LinearLayout>

row.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal"
  android:paddingBottom="6dip"
  android:paddingTop="4dip">

  <TextView android:id="@+id/name"
  android:layout_width="80dip"
  android:layout_height="wrap_content" />

  <TextView android:id="@+id/address"
  android:layout_height="wrap_content"
  android:layout_weight="1" />

</LinearLayout>

1 个答案:

答案 0 :(得分:0)

这看起来不正确dataList.clear();。您确定要在dataList而不是adapterDataList上打电话给您明确的意思吗?