我有这个listview更新:
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
display.elemek.clear();
em1.new AsyncEmBase().execute();
}
}, 0, 1000);
public class AsyncEmBase extends AsyncTask<Void, ListView, Void> {
protected void onPreExecute() {
// display.dataAdapter.clear();
}
@Override
protected Void doInBackground(Void... params) {
readInputRegisters(); /*this only makes display.elemek.add("SomeString")*/
return null;
}
protected void onPostExecute(Void unsed) {
if (display.dataAdapter == null) {
display.dataAdapter = new ArrayAdapter<String>(
display.activity, android.R.layout.simple_list_item_1,
display.elemek);
display.lv.setAdapter(display.dataAdapter);
} else {
display.dataAdapter.notifyDataSetChanged();
}
}
}
它顺利运行但过了一会儿就停下来说:
11-27 15:21:05.769: E/AndroidRuntime(17991): 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(2131296261, class android.widget.ListView) with Adapter(class android.widget.ArrayAdapter)]
我尝试过更新listview,但没有什么是好的。 请帮帮我!
edit1:新错误:索引7无效,大小为0 但是我在开始插入数据之前清除了elemek arraylist
display.java:
public class display extends Fragment {
public static TextView ain1, ain2, ain3, ain4, dout1, dout2, din1, din2,
din3, din4, cin1, cin2, cin3, cin4, k1, k2, k3, k4, k5, k6, k7, k8;
public static Activity activity;
public static ListView lv;
public static ArrayList<String> elemek;
public static ArrayAdapter<String> dataAdapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.display, container, false);
ain1 = (TextView) rootView.findViewById(R.id.textView2);
activity = getActivity();
lv = (ListView) rootView.findViewById(R.id.listView1);
elemek = new ArrayList<String>();
return rootView;
}
答案 0 :(得分:0)
display.activity.runOnUiThread(...)
没用,因为onPostExecute()
已经在UI线程
我认为您不必调用notifyDataSetChanged()
,因为您之前正在设置适配器。
答案 1 :(得分:0)
删除所有的线程,因为你在onPostExecute()中不需要ui线程并添加如下:
if ( display.dataAdapter == null) {
display.dataAdapter = new ArrayAdapter<String>(
display.activity,
android.R.layout.simple_list_item_1, display.elemek);
display.lv.setAdapter(display.dataAdapter);
}else{
display.dataAdapter.notifyDataSetChanged();
}