java.lang.IndexOutOfBoundsException : Index: 1, 大小 : 0 at java. util.ArrayList.get(ArrayList.java:437)

标签 java android android-studio

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

最佳答案

SharedPreferences 使用 String 键,而不是 int。当您使用字符串文字 "i" 读取或写入 SharedPreferences 时,您并没有按照您认为的方式对项目建立索引。您正在存储一个值,并且可能会多次重写它。

关于java.lang.IndexOutOfBoundsException : Index: 1, 大小 : 0 at java. util.ArrayList.get(ArrayList.java:437),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61794642/

相关文章:

android - 使用Firebase设置群聊的阅读状态

java - 在 Android Studio 中构建 Google Endpoints 后端时出现 403 禁止错误

android - Gradle构建在Android Studio中无限执行

java - 尝试删除记录时如何修复 Spring-Boot 中的 "violates foreign key constraint"。使用@ManyToMany

java - java中如何循环执行sql语句

android - NDK 应用程序 onDestroy 清理 - 如何分离当前线程

android - 显示和隐藏 AdMob 横幅以获得更好的性能?

android - 如何在 Android Studio 中添加 header 搜索路径?

java - 需要创建用户在 swing 应用程序中输入的信息并将其写入文件

java - 无法弄清楚如何将结果输出到 JLabel 而不是 System.out.println