Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get random list item android

Tags:

android

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;

like image 595
Shashwat Avatar asked May 01 '26 16:05

Shashwat


2 Answers

Use the Random class (http://developer.android.com/reference/java/util/Random.html)

list.get(new Random().nextInt(list.size()))
like image 153
tom Avatar answered May 03 '26 08:05

tom


Since Kotlin 1.3:

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.

like image 33
luismiguelss Avatar answered May 03 '26 07:05

luismiguelss