我想将特定元素从其原始位置移动到第0个索引。我尝试了以下
private void reoderArrayList() {
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> list = getPackageManager().queryIntentActivities( mainIntent, 0);
Collections.sort(list, new ResolveInfo.DisplayNameComparator( getPackageManager()));
if (list != null && !list.isEmpty()) {
for(ResolveInfo resolveInfo : list){
List<ResolveInfo> applist = getAppList();
if (applist != null && !applist.isEmpty()) {
for(ResolveInfo info : applist){
if(resolveInfo.activityInfo.applicationInfo.packageName.equals(info.packageName)){
list.remove(resolveInfo);
list.add(0,resolveInfo);
}
}
}
}
for (ResolveInfo resolveInfo : list) {
//do something
}
}
}
我想将指定的元素移动到第0个位置,将第0个位置的前一个元素移动到索引1,依此类推。我从AsyncTask的doInBackground()
调用了这个方法。但这会产生以下异常。
FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:200)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
at java.lang.Thread.run(Thread.java:1096)
Caused by: java.util.ConcurrentModificationException
如何处理此异常?
先谢谢
答案 0 :(得分:0)
for(ResolveInfo info : applist){
if(resolveInfo.activityInfo.applicationInfo.packageName.equals(info.packageName)){
list.remove(resolveInfo);
list.add(0,resolveInfo);
}
}
你不应该这样做。而是使用迭代器。
Iterator iterator = applist.iterator();
while(iterator.moveToNext()){
iterator.remove();
//Do other stuff over here.
}
原因是您在循环时无法从数组中删除。
答案 1 :(得分:0)
试试这个
List<ResolveInfo> templist=new ArrayList<ResolveInfo>();
ResolveInfo info=new ResolveInfo();
in for loop add like this
info=resolveInfo;
然后在forloop外面这样做
templist.addAll(list);
templist.remove(info);
list.clear();
list.add(info);
list.addAll(templist);