Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to read items from string-array on android

Tags:

arrays

android

I got a problem with reading items from string-array one by one. For example, i got string-array with 10 items:

<string-array name="arr">
    <item>First</item>
    <item>Second</item>
    <item>...</item>
    <item>Tenth</item>
</string-array>

So i know how to display items randomly, im using this code

Resources res = getResources();

myString = res.getStringArray(R.array.arr);

int length=myString.length;
int index=rgenerator.nextInt(length);
String q = myString[index];

tv = (TextView) findViewById(R.id.text);
tv.setText(q);

And in TextView on every button click it displays random item from array.

Problem is, how to make display item from string-array not randomly. Like, it starts from displaying First, then on click it displays Second, and so on untill end of array.
Please help!

like image 615
user1671523 Avatar asked Jan 13 '23 20:01

user1671523


1 Answers

You can't initialize your testArray field this way, because the application resources still aren't ready. Change the code to:

package com.xtensivearts.episode.seven;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class Episode7 extends ListActivity {
String[] mTestArray;

/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    // Create an ArrayAdapter that will contain all list items
    ArrayAdapter<String> adapter;

    mTestArray =  = getResources().getStringArray(R.array.testArray);    

    /* Assign the name array to that adapter and 
    also choose a simple layout for the list items */ 
    adapter = new ArrayAdapter<String>(
    this,
    android.R.layout.simple_list_item_1,
    mTestArray);

    // Assign the adapter to this ListActivity
    setListAdapter(adapter);
    }
}
like image 146
Петър Петров Avatar answered Jan 16 '23 00:01

Петър Петров