Java SharedReferences错误索引超出范围

Java SharedReferences错误索引超出范围,java,android,sharedpreferences,indexoutofboundsexception,Java,Android,Sharedpreferences,Indexoutofboundsexception,我正在尝试使用SharedReferences方法在中保存Arraylist。我遇到的问题是,我的索引超出了范围,但我不明白为什么: @Override public void onPause() { super.onPause(); // Always call the superclass method first data = getSharedPreferences(filename,0); SharedPreferences.Editor editor0 =

我正在尝试使用SharedReferences方法在中保存Arraylist。我遇到的问题是,我的索引超出了范围,但我不明白为什么:

@Override
public void onPause() {
    super.onPause();  // Always call the superclass method first
    data = getSharedPreferences(filename,0);
    SharedPreferences.Editor editor0 = data.edit();
    editor0.putInt("shareddifficulty", difficulty);
    editor0.putInt("sharedmoves", moves);
    editor0.putInt("sharedpicture",resource);
    editor0.putInt("ID_size", ID.size());

    for(int i=0;i<ID.size();i++){
        editor0.remove("ID_"+i);
        editor0.putInt("ID_" + i, ID.get(i));  
    }
    editor0.commit();               
}

public void onResume(){
    super.onResume();
    data = getSharedPreferences(filename,0);
    difficulty = data.getInt("shareddifficulty", 0);
    moves = data.getInt("sharedmoves",0);
    int listsize = data.getInt("ID_size", 0);
    resource = data.getInt("sharedpicture", 0);
    for(int i=0; i < listsize;i++){
         ID.set(i,data.getInt("ID_" + i,0));
    }
    for(int i=0;i<listsize;i++){
        crops.set(ID.get(i),cropsshuffle.get((ID.get(i))));
    }

}

private void divideImages(位图bmp){
int width=bmp.getWidth();
浮球w_比率=(浮球)w/宽度;
int scaledwidth=(int)(bmp.getWidth()*w_比率);
int scaledheight=(int)(bmp.getHeight()*w_比率);
Bitmap scaledbmp=Bitmap.createScaledB位图(bmp,scaledwidth,scaledheight,true);
转换(难度){
案例0:

对于(int i=0;i,从上面的代码中,我无法告诉您错误在哪里

但是当您尝试访问
数组
中不在数组中的项目时,会出现
索引自动边界异常

示例:

String[] myArray = new String[10];
myArray[10] = "test";
这将解析为
IndexOutofBoundsException
,因为您的数组仅来自0-9


根据上述简单的错误示例,尝试找出代码中出现的错误。否则,请发布更具体的代码,因为正如您所看到的,您的错误围绕着
数组

我制作了一个库来简化这类任务,只需包含我的库:

    compile 'com.cesarferreira.quickutils:library:2.2.1'
初始化它:

QuickUtils.init(context);
然后,您可以轻松地保存/读取/删除所需的任何位置:

QuickUtils.prefs.save(key, value);
QuickUtils.prefs.getInt(key, defaultValue);
QuickUtils.prefs.remove(key);

所有文档

您也应该发布数组初始化和填充,使用提供的代码,我们无法确定会发生什么,但这有点困难,因为函数很长,您需要知道的唯一一件事是crops是位图的数组列表,ID是一个带整数的列表,大小与CROPE相同s、 如果你真的想,我也可以把代码放在上面。你是否尝试用调试器跟踪你的代码,以查看哪些内容被保存到SharedRefs中,以及你到底要检索什么?
ID.set(i,data.getInt(“ID_“+i,0));
会给你带来麻烦,因为数组ID在恢复时为空,因此没有元素。你可以改为更好的方法。add()他们
    compile 'com.cesarferreira.quickutils:library:2.2.1'
QuickUtils.init(context);
QuickUtils.prefs.save(key, value);
QuickUtils.prefs.getInt(key, defaultValue);
QuickUtils.prefs.remove(key);