java.lang.IllegalStateException:适配器的内容已更改(Signalr)

时间:2015-08-10 09:56:18

标签: android

在我的Android应用中显示以下异常。我正在使用单个列表视图和单个适配器。我正在使用2个不同的回调函数(来自signalr)更新列表视图,但一次只有一个。

异常显示:

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. Make sure your adapter calls notifyDataSetChanged() when its content changes. [in ListView(2131361927, class android.widget.ListView) with Adapter(class com.indus.TAP.PanelDisplay$LogAdaptor)]
08-04 11:42:34.624: E/AndroidRuntime(7133):

代码:

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        LogAdaptor log = (LogAdaptor) lvLog.getAdapter();
        log.notifyDataSetChanged();
        lvLog.post(new Runnable() {
            @Override
            public void run() {
                lvLog.smoothScrollToPosition(lvLog.getCount());
            }
        });
    }
});

2 个答案:

答案 0 :(得分:0)

有两个要点:

  1. 确保在模型更改时调用notifyDataSetChanged方法
  2. 如果您在后台线程中更改模型,请使用广播来通知数据更改

答案 1 :(得分:0)

如果您的SignalR是一项服务,您可以尝试这样

    @Override
    public void onCreate() {
        super.onCreate();
        mHandler = new Handler(Looper.getMainLooper());
    }

    private startSignalR(...) {
      ...
      mHub.on("broadcastMessage",
                new SubscriptionHandler1<String>() {
                    @Override
                    public void run(final String msg) {
                        ...
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                // Update adapter and call notifyDataSetChanged here                                 
                            }
                        });
                    }
                }
                , String.class);
      ...
   }

更新: 尝试在notifyDataSetChanged之后执行延迟执行,例如:

adapter.notifyDataSetChanged();                    
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
     @Override
     public void run() {
         ...
         ...                            
     }
}, 1000);