基于array []的适配器中的ListView IllegalStateException

时间:2013-11-21 14:30:33

标签: android android-listview android-adapter

我有一个适配器,它是一个嵌套类:

protected abstract class MyAdapter extends BaseAdapter {

    private Context context;
    private Data[] data;

    protected MyAdapter(Context context) {
        this.context = context;
    }

    public void setData(Data[] data) {
        this.data = data;
    }

    @Override
    public int getCount() {
        return data == null || data.length == 0 ? 0 : data.length * 2;
    }

    @Override
    public Object getItem(int i) {
        return data == null ? null : data[i / 2];
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ...
    }
         ///other methods not modifying data[]
}

我只在一个地方使用setData(Data []数据):

public void setNewData(Data[] data) {
    if (!Arrays.deepEquals(myAdapter.data, data)) {
        myAdapter.setData(data);
        myAdapter.notifyDataSetChanged();
    }

    updateVisibility();
}

在一个地方访问变量:

protected void updateVisibility() {
    Data[] localData = myAdapter.data;

    if (localData != null && localData.length > 0) {
        //do smth not related to localData[]
    } 
}

在谷歌播放中,我看到用户收到此错误:

java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. [in ListView(2131427598, class android.widget.ListView) with Adapter]
at android.widget.ListView.layoutChildren(ListView.java:1544)
at android.widget.AbsListView.onTouchEvent(AbsListView.java:4141)
at android.view.View.dispatchTouchEvent(View.java:7350)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2464)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2197)

但无法理解它来自何处。

增加:

我认为这就是原因:

在子类中,我重写了getCount()方法,并根据方向返回不同的数字。

    @Override
    public int getCount() {
        int count = super.getCount();

        if (isPortrait(context.getResources())) {
            count++;  
        }

        return count;
    }

我认为我应该在这里更新listView的缓存项目计数。 你怎么看?我是对的吗?

2 个答案:

答案 0 :(得分:2)

您确定在其他任何地方都不使用data setNewData数组吗?也许你重用这个数组并以某种方式更新它?当listView的项目内部listView的项目计数不等于适配器的getCount时,抛出此异常。重新检查您的代码。

答案 1 :(得分:0)

你在哪里调用setNewData?

如果在初始化适配器后调用它,请调用

http://developer.android.com/reference/android/widget/BaseAdapter.html#notifyDataSetChanged()