这是我的代码,我收到以下错误消息:
“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/