首页 > 解决方案 > java.lang.IndexOutOfBoundsException:索引:1,大小:0 在 java.util.ArrayList.get(ArrayList.java:437)

问题描述

这是我的代码,我收到以下错误消息:
“java.lang.IndexOutOfBoundsException:索引:1,大小:0”请帮忙。我的应用程序应该使用 AllWords 列表我不知道为什么当我使用 SharedPrefrences 添加很多单词时它的大小为 0。

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_library);

        sp = getSharedPreferences("Words", Context.MODE_PRIVATE);
        word1 = findViewById(R.id.word1);

        AllWords = GetAllWords();

        word1.setText(AllWords.get(1).toString());
    }

    public List<String> GetAllWords (){
        List<String> AllWords = Collections.synchronizedList(new ArrayList<String>());
       for(int i=0 ; i<sp.getInt("size",0) ; i++){
            AllWords.add(sp.getString("i",""));
        }
        return AllWords;
    }

标签: javaandroidandroid-studio

解决方案


SharedPreferences使用String键,而不是int. SharedPreferences当您使用 string literal读取或写入时"i",您并没有按照您的想法对项目进行索引。您正在存储一个值,并且可能多次写入它。


推荐阅读