0

Situation:

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++;
    }
}

Question:

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!!

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I would like to know whether this will then affect the size of the selection_Question? this is because if just to select using criteria, then the size of the selection_Question would be smaller than all_question, and then those remaining slot at the back would it be affected?
I mean is it possible to create a string ready to start from nothing and when there are new items just keep to add in and expands... but not to reserve at first place...or does it matter actually? (ps: i have checked all_question is not blank, it contains 400 items, and i have checked all_question[0] it shows the string, so as [100]. [200])
Sounds like you want an ArrayList instead of an array.
@pearmak - As Geobits mentioned, you should look into ArrayList. Will reduce quite a lot of your work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.