Skip to content Skip to sidebar Skip to footer

Show Random String

i am trying to display a random string each time a button is pressed from a set of strings defined in strings.xml . this is an example of the strings ID's

Solution 1:

You can define your strings in an array which will help simplify this task (res/values/array.xml):

<string-arrayname="myArray"><item>string 1</item><item>string 2</item><item>string 3</item><item>string 4</item><item>string 5</item></string-array>

You can then create an array to hold the strings and select a random string from the array to use:

privateString[] myString; 

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

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

Example code:

package com.test.test200;

import java.util.Random;

import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.widget.TextView;

publicclassTestextendsActivity {
/** Called when the activity is first created. */private String[] myString;
    privatestaticfinalRandomrgenerator=newRandom();

@OverridepublicvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    Resourcesres= getResources();

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

    Stringq= myString[rgenerator.nextInt(myString.length)];

    TextViewtv= (TextView) findViewById(R.id.text1);
    tv.setText(q);
}
}

Solution 2:

create string array in res/values/array.xml:

<?xml version="1.0" encoding="utf-8"?><resources><string-arrayname="custom_array"><item>aalia</item><item>asin</item><item>sonakshi</item><item>kajol</item><item>madhuri</item></string-array></resources>

then in your activity write the code

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

        String randomStr = array[new Random().nextInt(array.length)];

        text_dialog.setText(""+randomStr);

Solution 3:

Why do you need this?

R.string.q0

Assuming getString(RandomQ) is a valid statement, I would think

int RandomQ = rgenerator.nextInt(5) + 1;

would work just fine.

Also, as a side note: A lot of times those autofixes in your IDE are unreliable and unsafe to use. Unless you know why it's telling you to do something, don't do it.

Post a Comment for "Show Random String"