您的位置:首页 > 其它

List集合中的数据删除操作以及移除适配器中选中的项的问题

2017-05-19 17:01 363 查看
在for循环中操作list 并移除list中的项 如果for循环正序 当删除的时候 list的坐标会产生变化 会导致越界的问题我们可以倒叙删除for(int i=list.size();i>=0;i–){}或者用迭代器
Iterator it=list.iterator();

  while (it.hasNext()){

it.remove();

}
下面来说一下 我昨天遇到的问题列举手机里的apk文件 并选择删除当时的操作是 双for循环 找到对应标记
for(int i=0;i<listcheck.size();i++){
for(int j=0;j<listgroup.size();j++){
if(listcheck.get(i).name.equas(listgroup.get(j).name)){
listgroup.Remove(j);
}
}
}
这个操作在子线程里 在主线程里同时也对这个集合listgroup集合进行了操作 结果下标越界了 涉及到了线程安全 这里就说点解决方案为啥会这样我在主线程和子线程同时访问了listgroup 造成的访问异常 有可能我在子线程中的操作结束 后刚好被主线程用到我操作完成的数据 就会造成各种问题 越界 空指针等所以 应该用不同的list做对应处理后面我将集合操作放到主线程让主线程去操作就解决了问题下面贴一下代码
/**

* 移除apk选中的apk文件

*/

public void RemoveApk() {

Analytics.getInstance(PhotoClearApplication.getApplication().getApplicationContext())._sendEvent("安装包管理", "清理开始");

Firebase.getInstance(PhotoClearApplication.getApplication()).logEvent("安装包管理", "清理开始");

new Thread(new Runnable() {

@Override

public void run() {

List<MyFile> fileList = apkAdapter.getList();

for (int i = 0; i < fileList.size(); i++) {

for (int j = list_myfile.size() - 1; j >= 0; j--) {

if (fileList.get(i).getName().equals(list_myfile.get(j).getName())) {

list_myfile.get(j).ischeck = fileList.get(i).ischeck;

}

}

}

Iterator it = list_myfile.iterator();

while (it.hasNext()) {

MyFile files = (MyFile) it.next();

if (files.ischeck) {

File file = new File(files.getFilePath());

file.delete();

//                        it.remove();// 子线程中remove  两个线程同时操作的一个list集合 就会出现越界的问题将集合操作放到主线程里

}

}

handler.sendEmptyMessage(REMOVE);

}
}).start();
}
Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);switch (msg.what) {case REMOVE://将对集合的操作放到主线程来Iterator it = list_myfile.iterator();while (it.hasNext()) {MyFile files = (MyFile) it.next();if (files.ischeck) {it.remove();}}apkAdapter.notifyDataSetChanged();setHeaderShow(list_myfile, tvShowAs);list_myfile = apkAdapter.getData();btRemove.setBackgroundColor(getResources().getColor(R.color.removeButton));btRemove.setText(R.string.remove_apk_default);Analytics.getInstance(PhotoClearApplication.getApplication().getApplicationContext())._sendEvent(“安装包管理”, “清理结束”);Firebase.getInstance(PhotoClearApplication.getApplication()).logEvent(“安装包管理”, “清理结束”);break;`
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐