Grux
Grux

Reputation: 584

Adding strings to ArrayList from strings.xml

I have been parsing html to get the title of a specific link. I am able to add this string to the string array but I want to add a string from a string array which resides in my strings.xml resource.

int i = 1;
String time = null;
for (Element title : rels) {
    time = getResources().getStringArray(R.array.times)[i];
    titleArray.add(time + title.attr("title"));
    i++;
}

Here is my strings resource:

<string-array name="times">
    <item name="1">12:00 am</item>
    <item name="2">12:30 am</item>
    <item name="3">1:00 am</item>
    <item name="4">1:30 am</item>
    <item name="5">2:00 am</item>
</string-array>

I'm getting this error in LogCat:

04-06 01:44:08.837: E/AndroidRuntime(30938): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=48; index=48

I have 48 strings in this string array, which is exactly the same number of strings I'm parsing from the html. I'm not sure why my app is force closing. Does anyone know?

Upvotes: 1

Views: 1730

Answers (2)

Zeer0
Zeer0

Reputation: 119

your loop should start from 0 index

    int i = 0;
    String time = null;
    for (Element title : rels) {
        time = getResources().getStringArray(R.array.times)[i];
        titleArray.add(time + title.attr("title"));
        i++;
    }

Upvotes: 1

Jason C
Jason C

Reputation: 40315

Array indices start at 0 not 1. Change i to start at 0:

int i = 0;

Upvotes: 3

Related Questions