-1

Im trying to pull individual strings from a string array at random, and display it on screen(in android studio). But i cant seem to find a solution anywhere. Its a simple string array, and i need to pull one at a click of a button. My string array is pretty standard and set up like this:

<string-array name="string_array1">
        <item>Sentence 1</item>
        <item>Sentence 2</item>
    </string-array>
  • 2
    Use a regular array - plenty of solutions http://stackoverflow.com/questions/8065532/how-to-randomly-pick-an-element-from-an-array - http://stackoverflow.com/questions/13340516/random-element-from-string-array – BR89 Oct 07 '16 at 11:59
  • 1
    Can't find a solution for what? Just retrieve the array and then generate a random number for the index – Tim Oct 07 '16 at 12:04

2 Answers2

0

You can user java String array or ArrayList of String in Activity like:

Java String Array Example in Activity :

1)define an Array

 String string_array1[]={"Sentence 1","Sentence 2"}; 

Get value from the array :

Sting zeroIndexValue=string_array1[0];
Sting oneIndexValue=string_array1[1];

2) ArrayList Example:

define ArrayList of String:

ArrayList<String> string_List=new ArrayList<String>();

Add value to List:

string_List.add("Sentence 1");
string_List.add("Sentence 2");

Get value from List:

string_List.get(0);
string_List.get(1);
Arun kumar
  • 1,894
  • 3
  • 22
  • 28
0

fetch array from string file

String[] string_array1 = getResources().getStringArray(R.array.string_array1);

Now generate random value and fetch it from array.

Random rand = new Random()
int Low = 0;
int High = string_array1.length-1;
int value = rand.nextInt(High-Low) + Low; //It will generate random number in the given range only.

String printed_value = string_array1[value];
Ravi
  • 34,851
  • 21
  • 122
  • 183