Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/189.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 从SharedReferences向arraylist添加项时发生IndexOutOfBoundsException_Android_Exception_Arraylist_Sharedpreferences_Indexoutofboundsexception - Fatal编程技术网

Android 从SharedReferences向arraylist添加项时发生IndexOutOfBoundsException

Android 从SharedReferences向arraylist添加项时发生IndexOutOfBoundsException,android,exception,arraylist,sharedpreferences,indexoutofboundsexception,Android,Exception,Arraylist,Sharedpreferences,Indexoutofboundsexception,我的arraylist有点问题,我需要一个解决方法来避免IndexOutOfBoundsException异常 以下是我添加项目的方式: for(Map.Entry<String,?> entry : getAll().entrySet()){ // this is a map with all my sharedprefs list.add((Integer) entry.getValue(), myItem); } 它抛出异常,因为它需要从0开始

我的arraylist有点问题,我需要一个解决方法来避免IndexOutOfBoundsException异常

以下是我添加项目的方式:

    for(Map.Entry<String,?> entry : getAll().entrySet()){ // this is a map with all my sharedprefs
        list.add((Integer) entry.getValue(), myItem);
    }
它抛出异常,因为它需要从0开始


有人有办法吗?谢谢

问题是您无法访问
数组列表中尚不存在的
索引
,由于
Map
没有排序,您可能试图在拥有有效元素索引
0
之前在索引
1
处插入,或者在拥有有效索引
0
1
之前在索引
2
处插入

编辑:

您可以使用

ArrayList<String> arr = new ArrayList<String>(getAll().entrySet());
arraylistarr=newarraylist(getAll().entrySet());
然后使用循环,这个问题的“解决方法”是在开始添加到特定位置之前,用所有0或其他值预先填充列表。例如:

int mapSize = mPrefMap.size(); 
for(int i = 0; i < mapSize; i++){
    listOfStuff.add(0);
}
int-mapSize=mPrefMap.size();
对于(int i=0;i
添加一个等于首选项贴图大小的数字0将基本上将这些位置的所有位置初始化为0。然后,您可以返回并以您现在的方式添加特定的值


我仍然不明白为什么您不只是使用标准的
SharedReference
类。这将避免使用这种变通方法,并节省您为
ArrayList
设置默认值所浪费的时间

在这里定义
列表
。它是一个简单的数组列表。它不会扔npe!尝试执行
ArrayList arr=new ArrayList()为什么不直接使用
SharedReference
?当有一个非常好的类来完成您正在尝试完成的工作时,此“解决方案”似乎不必要地复杂。MAP条目将按自然顺序获取值。。字母顺序..这正是问题所在,它试图在“0”之前添加“1”
ArrayList<String> arr = new ArrayList<String>(getAll().entrySet());
int mapSize = mPrefMap.size(); 
for(int i = 0; i < mapSize; i++){
    listOfStuff.add(0);
}