简体   繁体   中英

Android: Button onClick get random data from ArrayList

I make a filter with java for chose a specific continent and when you click refresh you get a random filtered data this is my code with java

    public class Util {

    public static CountriesData getCountrie(){

        List<Country> mList = new ArrayList<>();
        mList.add(new Country(R.drawable.ae, "Emarat","asia"));
        mList.add(new Country(R.drawable.tm, "Turkmenistan","asia"));
        mList.add(new Country(R.drawable.bj, "Benin","Afriqua"));
        mList.add(new Country(R.drawable.va, "Seal of Virginia ","N.America"));
        mList.add(new Country(R.drawable.us, "USA","N.America"));
        mList.add(new Country(R.drawable.at, "Austria","Europe"));
        mList.add(new Country(R.drawable.pt, "Portugal","Europe"));
        mList.add(new Country(R.drawable.ki, "Kiribati ","S.America"));
        mList.add(new Country(R.drawable.cu, "Cuba","S.America"));
        mList.add(new Country(R.drawable.ht, "Haiti","S.America"));

        return new CountriesData(mList);

    }
}

my question is how make a code for my button to get data when i click

   mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showRandomCountry();
        }
    });

    }

public void showRandomCountry(){
    schuffleAsia();
   // int r = new Random().nextInt(mList.size());

   mImageView.setImageResource(mList.get().getMcountry());
 //  mTextView.setText(mList.get(m).getmFact());

`

Place this function in your Util class:-

 public Country getRandomCountry() {  
     return mList.get(new Random().nextInt(list.size()));//To get random item from the array.
 }

And For Getting Shuffled Array Use This function :-

 public ArrayList<Country> getShuffledList(int sizeOfArray) {
     Util util = new Util();
     List<Country> shuffledList = new ArrayList<>();

     for (int i = 0; i < sizeOfArray; i++) {
         shuffledList.add(util.getRandomCountry());
     }
     return shuffledList; 
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM