java - 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;
}
解决方案
SharedPreferences
使用String
键,而不是int
. SharedPreferences
当您使用 string literal读取或写入时"i"
,您并没有按照您的想法对项目进行索引。您正在存储一个值,并且可能多次写入它。
推荐阅读
- ide - Office JS Excel 插件的首选 IDE
- php - 特定 wordpress 管理页面上的挂钩脚本
- ios - 从IOS应用程序同时多次查询数据库导致崩溃
- python - 使用 numpy 表示具有未知结构的(可能很大)图的有效方法?
- sql-server - 如何从一台服务器调用 MS SQL 服务器作业到另一台服务器作业 - 互连 2 SQL 服务器作业
- r - 添加扩展 snaive 的自定义预测功能
- r - 在计算平均值时,如何仅包含满足特定条件的行?
- jenkins - 安装后无法看到 Jenkins 主页
- jquery - 使用 jQuery 设置输入值后更新 Angular 8 模型
- python - 如何将句子输入中的空格替换为输出中的破折号