0

I created array.xml in the res/values folder which contain 5 strings(avalaible_buses as the name of the array). pls how can i select strings randomly from this array and display it on textview. below is my attempt. seatNumber is the name of the textview.

public void seatNumber (View view) {     
String[] myArray = getResources().getStringArray(array.avalaible_buses);     
TextView seatNumber = (TextView) findViewById(R.id.seatNumber);     
Random random = new Random();     
seatNumber.setText(random.nextInt(myArray)); 
}
1
  • get a random index. decide between 0 and array.length -> that number - 1 is your index Commented Feb 22, 2021 at 7:01

2 Answers 2

1

Break the question down into smaller parts.

Generate a random number between 0 and the last index of your array

// get a random number between 0 and array length - 1 inclusive (last index)
Random random = new Random();     
int index = random.nextInt(myArray.length);

Update the UI

seatNumber.setText(myArray[index]);

Note

The array is defined as

String[] myArray = getResources().getStringArray(array.avalaible_buses);

The way this is written it seems that the array resource (available_buses) deals with actual buses, not seats on a bus. If this is correct, I would have expected a text (ui) control like busName.

If you are assigning a random number to a passenger (seat number) you will also need to keep track of who gets on and who gets off so as to avoid assigning the same random number to two people. In other words, the array changes based on availability.

Sign up to request clarification or add additional context in comments.

Comments

0

Change line #5 like following.

public void seatNumber (View view) {     
    String[] myArray = getResources().getStringArray(array.avalaible_buses);     
    TextView seatNumber = (TextView) findViewById(R.id.seatNumber);     
    Random random = new Random();     
    seatNumber.setText(myArray(random.nextInt(myArray.length)));  // Line #5
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.