Android/Java: Get random elements out of an arraylist

Shortform:

  Random randomGenerator = new Random();
  ArrayList sample = new ArrayList() {{ add("a"); add("b"); add("c"); add("d");}};
  String item = sample.get(randomGenerator.nextInt(sample.size()));

Slightly longer example:

//get your button from your layout file
  final Button button = (Button) findViewById(R.id.button);
//initialize your random number generator
  final Random randomGenerator = new Random();
//create your arraylist and fill with some stuff
  final ArrayList sample = new ArrayList() {{ add("a"); add("b"); add("c"); add("d");}};
    //set a listener to your button
      button.setOnClickListener(new View.OnClickListener()
      {
        public void onClick(View v)
          {
           //set the size of your list as the max number for your generator
           //get a random number and retrieve your element
             String item = sample.get(randomGenerator.nextInt(sample.size()));
           //set your random element to a textview
              ((TextView) findViewById(R.id.textView1)).setText(item);
          }
    });
Advertisements
This entry was posted in Android, Java, Programming, Snippets and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s