Android java.lang.IndexOutOfBoundsException。。。但是为什么呢?
经过3个小时的尝试,我决定在这里询问,看看是否有人能为我提供解决此错误的方法:java.lang.IndexOutOfBoundsException:无效索引4,大小为4 这是我的密码Android java.lang.IndexOutOfBoundsException。。。但是为什么呢?,android,arraylist,progress-bar,Android,Arraylist,Progress Bar,经过3个小时的尝试,我决定在这里询问,看看是否有人能为我提供解决此错误的方法:java.lang.IndexOutOfBoundsException:无效索引4,大小为4 这是我的密码 private ProgressBar progressBar; private int progressStatus = 0; private Handler handler = new Handler(); -------------------- status.setText(getString
private ProgressBar progressBar;
private int progressStatus = 0;
private Handler handler = new Handler();
--------------------
status.setText(getString(R.string.init));
progressBar.setVisibility(View.VISIBLE);
final Map<String,?> keys = prefs.getAll(); //4 prefs atm inside.
final ArrayList<String> props = new ArrayList<String>();
final ArrayList<String> values = new ArrayList<String>();
if (keys != null) {
for(final Map.Entry<String,?> entry : keys.entrySet()) {
props.add(entry.getKey());
values.add(entry.getValue().toString());
}
final int total = props.size();
progressBar.setMax(total);
new Thread(new Runnable() {
public void run() {
while (progressStatus < total) {
progressStatus += 1;
handler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressStatus);
if (props.get(progressStatus) != null) {
writeProps(props.get(progressStatus), values.get(progressStatus));
status.setText(getString(R.string.writing) + ": " + props.get(progressStatus));
}
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (progressStatus == total) {
handler.post(new Runnable() {
public void run() {
progressBar.setVisibility(View.GONE);
progressStatus = total + 1;
myVoidOnFinish();
}
});
}
}
}).start();
}
主要问题在这里
while (progressStatus < total) {
progressStatus += 1;
}
while(progressStatus
检查进度状态的值,它不应大于3,而在代码中,它在最后是4,而索引仅从0到3。请相应地设置进度状态的值
试试这个
while (progressStatus < total-1) {
progressStatus += 1;
}
while(progressStatus
您正在使用一个额外的索引,因为最多可以使用3个索引。所以请从零开始,使用小于等于检查,而不是小于等于 问题是您正在设置progressstatus值,如下所示
final int total = props.size();
progressBar.setMax(total);
在下面的一行中,你试图获得道具的价值
writeProps(props.get(progressStatus), values.get(progressStatus));
请注意,对于4的总大小,您的progressStatus将为4。但是道具和价值的最大指数将是3。这就是问题所在
可以将该值设置为比大小小1,如所示
final int total = props.size() - 1;
您好,您正在获取java.lang.IndexOutOfBoundsException:索引4无效,大小为4,这意味着索引应仅具有0到3的值,请检查该值。从映射中获取值后,增量
progressStatus
,因为如果映射大小为4,则当前progressStatus
值为1,2,3,4
final int total = props.size() - 1;