I want to get a random list item from a list on click of button in android. Can someone guide me to a tutorial or example where I can find how this can be done, or if someone has already done something like this can i see a sample code. I'm clueless as how to get by it. Need help.
public class RandomActivity extends Activity {
String arr[]={"A","B","C","D","E"};
ListView list; p v onCreate(Bundle saved) {
list = (ListView)findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1,arr);
list.setAdapter(adapter);
}
public void onRandom(View v){
list.getAdapter().getItem(new Random().nextInt(list.getCount()));
}
} Still not getting the size() method so i substitutedit with getCount().But not generating a random value;
Use the Random class (http://developer.android.com/reference/java/util/Random.html)
list.get(new Random().nextInt(list.size()))
list.random()
If the list is empty, it will throw NoSuchElementException. Docs
If you can't use Kotlin, then @tom's answer is your way to go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With