Kepedizer
Kepedizer

Reputation: 856

String Array only returns one string in android

I'm trying to display a string inside a textView object. currently I'm only getting the first string in the string array.

   public void onClick(View v) {
        Resources res = getResources();
        String[] hintsStr = res.getStringArray(R.array.hints);
        TextView hintShow = (TextView)findViewById(R.id.hintShow);
        int rndInd = (int) Math.random()*5;
        //hintShow.setText(rndInd);
        hintShow.setText(hintsStr[rndInd]);
        //System.out.print(rndInd);
    }

Upvotes: 0

Views: 86

Answers (3)

Pratik Dasa
Pratik Dasa

Reputation: 7439

First initialize Random Class and then get value,see below code

Randon random=new Random();
int value = random.nextInt(10);

It will work for sure.

Upvotes: 0

Campig
Campig

Reputation: 121

You are casting the result of Math.rand() to int so the result is always 0, you can do int rndInd = (int)(Math.random()*5); or even better use the solution that ssantos suggested

Upvotes: 1

ssantos
ssantos

Reputation: 16536

Try this to generate your random numbers.-

Random rand = new Random();
int rndInd = rand.nextInt(5); // Will get a rand number between 0 and 4

Also, you should instantiate rand object just once, as an instance variable outside onClick method.

Upvotes: 2

Related Questions