Reputation: 19
I've a problem but i really don't understand why. The problem is when i want to add an element in my ArrayList
.
Here is my code :
ArrayList<Integer> lesCasesCoches = new ArrayList<Integer>();
lesCasesCoches.clear();
Log.w("Test", "je beug pas" + idCasier);
for (int f = 0; f < laCave.requeteIdCasier.size(); f++) {
if (laCave.requeteIdCasier.get(f) == idCasier) {
Log.w("Test", "size" + f);
Log.w("Test", "id casier" + laCave.requeteIdCasier.get(f));
Log.w("Test", "id case" + laCave.requeteIdCase.get(f));
int casesAdd = laCave.requeteIdCase.get(f);
Log.w("Test", "que vaut add" + casesAdd);
lesCasesCoches.add(casesAdd);
Log.w("test", "Cases cochés" + lesCasesCoches.get(f));
}
}
Here is my error log:
test: je beug pas2
test: size2
test: id casier2
test: id case5
test: que vaut add5
==> here the bug message
delvikvm: threadid=1: thread exiting with uncaught exception ( group=0x415072a0)
java.lang.indexOutOfBoundsException: Invalid index 2, size is 1
Sorry for my bad english. Thank you very much for the time you spend for me
Upvotes: 0
Views: 73
Reputation: 4707
The error is actually caused by logging:
Log.w("test", "Cases cochés" + lesCasesCoches.get(f));
Explanation:
test: je beug pas2
test: size2
test: id casier2
test: id case5
test: que vaut add5
java.lang.indexOutOfBoundsException: Invalid index 2, size is 1
From the debug log, you add the first Integer
5 from casesAdd
into lesCasesCoches
when f
is 2. Since this is the first time you add the number, the size()
of lesCasesCoches
is 1. Then, when you call the problematic line, you're trying to access the third (from 0-based index) element of lesCasesCoches
, resulting in IndexOutOfBoundsException
.
The solution is to either remove the line if it's not really needed, or to use lesCasesCoches.get(lesCasesCoches.size() - 1)
to get the last added Integer
from lesCasesCoches
.
Upvotes: 0
Reputation: 1871
It probably happens because of this statement if (laCave.requeteIdCasier.get(f) == idCasier)
because if it's not true then for loop will go forward and increase f hence it won't match with
lesCasesCoches.add(casesAdd);
Log.w("test","Cases cochés"+lesCasesCoches.get(f));
so instead of getting f'th item you should get the last one
Log.w("test","Cases cochés"+lesCasesCoches.get(lesCasesCoches.size()-1));
Upvotes: 0
Reputation: 1850
Change
Log.w("test","Cases cochés"+lesCasesCoches.get(f));
to
Log.w("test","Cases cochés"+lesCasesCoches.get(lesCasesCoches.size()-1));
Upvotes: 2
Reputation: 703
I think this make exception error.
Log.w("test","Cases cochés"+lesCasesCoches.get(f));
change this.
Log.w("test","Cases cochés"+casesAdd);
Upvotes: 1
Reputation: 2355
Few things here: 1) why do you need to clear an Array you just created? 2) you access laCave.requeteIdCase and laCave.requeteIdCasier at the position f but f is only bound to laCave.requeteIdCasier.size(). That probably is crashing because requeteIdCase has lesser elements than requeteIdCasier (whatever those terms mean :) )
Upvotes: 0