Android中ListView 适配器数据如果更改后,没有在UI线程及时调用适配器Adapter的通知更新方法将会抛出异常。
直接操作适配器的数据不安全。
网络的数据解析也是耗时任务,比如JSON转换。以下以JSON为例。
虽然ListView正逐渐被CardView取代,但是基本思路还是一样的。
这里在实践中总结了2种思路。
1.克隆数据方式
非UI线程{
加载网络数据。
new List copyList=adaperList.clone().
JSON字符转换成JAVA对象。
add to copyList.
}
UI线程的回调 (copyList){ //Handler
if(刷新){
adaperList.clear();
}
for (item:copyList){
adaperList.add(item);
}
}
2.直接传参
非UI线程{
加载网络数据。
new List copyList.
JSON字符转换成JAVA对象。
add to copyList.
}
UI线程的回调 (copyList){//Handler
if(刷新){
adaperList.clear();
}
for (item:copyList){
adaperList.add(item);
}
传参可以使用直接类型,也可以通过序列化List通过Bundle传参Handler