Reputation: 5027
I have a string array in the resource, which consists of all types of, say, questions.
If user clicks for All types, for example, to select all, then the selection_question
string array would copy all the items in all_question
.
Yet if user clicks for a specific type of questions, say, to select just animal related questions, then the selection_question
string array would copy all the items in all_question
that contains "animals" this word.
My code is as simple as follows:
declare:
String[] all_Question ;
String[] selection_Question;
OnCreate:
all_Question = getResources().getStringArray(R.array.all_Q_List);
all_numberofquestions = all_Question.length;
// reset
selection_numberofquestions = 0;
selection_Question = new String[0];
j =0;
if to select all:
for (int i = 0; i < all_numberofquestions ; i++)
{
selection_Question[i] = all_Question [i];
}
if to select based on some criteria:
for (int i = 0; i < all_numberofquestions ; i++)
{
if (all_Question [i].contains("animal"))
{
selection_Question [j] = all_Question [i];
j++;
}
}
It then popups with the following error as shown in Logcat:
03-04 22:14:10.568: E/AndroidRuntime(24917): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
I does not understand why it is Out of Bounds? How could the above codes be modified?
Thanks!!
Upvotes: 0
Views: 1035
Reputation: 45060
This is the problem.
selection_Question = new String[0];
It should have been
selection_Question = new String[all_numberofquestions];
Or even your all_question
could be blank/empty
.
Upvotes: 1