Gabrielle
Gabrielle

Reputation: 4991

Put items in a string array?

I have a little question. I want to put some strings in an String[]. How can I do this?

I tried

String[] categorys;
for (int i = 0; i < jArray.length(); i++) {
                        JSONObject jsdata = jArray.getJSONObject(i);
                        String myString = jsdata.getString("id_category");
                        String namecategory = jsdata.getString("category_name");
                        System.out.println("Category name" + namecategory);
                        categorys[i] = namecategory;
                    }

but I get 07-28 16:40:01.719: ERROR/AndroidRuntime(452): Caused by: java.lang.ArrayIndexOutOfBoundsException

I don't know how to use an array of Strings. Need some help.Thanks...

Upvotes: 1

Views: 323

Answers (2)

Jon Martin
Jon Martin

Reputation: 3390

You're trying to set the value of an element of the array which doesn't exist (your array has no elements). You need to initialize the length of the array.

Upvotes: 1

DeeV
DeeV

Reputation: 36045

You need to allocate the array.

String[] categorys = new String[jArray.length()];

Upvotes: 5

Related Questions