好的我有一个sqlite数据库正在从用户那里收集数据 - 然后将这些信息发送到一个字符串数组,并在屏幕上显示以下代码 -
Array本身及其int
List<String> array = new ArrayList<String>();
int currentPos = 0;
这是下一个按钮
nextBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
currentPos++;
if (currentPos > array.size()) {
currentPos = 0;
}
textView.setText(array.get(currentPos));
}
});
这是上一个按钮
prevBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
currentPos --;
if (currentPos < 0) {
currentPos = array.size();
}
textView.setText(array.get(currentPos));
}
});
heres log cat with error
12-10 16:08:31.867 16630-16630/com.package.www.randomApp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.package.www.randomApp, PID: 16630
java.lang.IndexOutOfBoundsException: Invalid index 8, size is 8
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.package.www.randomApp.FavoritesMenu$2.onClick(FavoritesMenu.java:66)
at android.view.View.performClick(View.java:4654)
at android.view.View$PerformClick.run(View.java:19438)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5602)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
错误指向以下代码行
textView.setText(array.get(currentPos));
两个按钮都会弹出错误。
我知道这个错误意味着数组中调用的位置不存在这可能是我的数学错误,但我看不到它。
答案 0 :(得分:2)
试试这个
nextBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
currentPos++;
if (currentPos> array.size() - 1) currentPos= 0;
textView.setText(array.get(currentPos));
}
});
prevBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
currentPos --;
if (currentPos < 0) currentPos = array.size() - 1;
textView.setText(array.get(currentPos ));
}
});
答案 1 :(得分:1)
currentPos++;
if (currentPos> array.size()) currentPos= 0;
7变为8. 8不大于8.因此currentPos不会变为0.
修正:if (currentPos>= array.size()) currentPos= 0;
或者:if (currentPos> array.size() - 1) currentPos= 0;