0

So i was making this app which displays an arrayList of different poems I first request the poems from API then the Asynctask returns the poems in the form of Arraylist i wand to show 20 random poems from the list.

This is the Asynctask code

private class TitleAsynctask extends AsyncTask<URL,Void,List<view>> {


        private ProgressDialog progressDialog;
        @Override
        public List<view> doInBackground(URL... urls){

            URL url = Query_utils.createurl(POEM_TITLE);
            String json = "";
            Log.d(LOG_TAG,"this worked");
            {
                try {
                    json = Query_utils.makehttprequest(url);
                    Log.d(LOG_TAG, "make Httprequest works");
                } catch (IOException e) {

                }
            }
            List<view> title_view = Query_utils.extracttitlefromjson(json);
            return title_view;

        }

        @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
        @Override
        protected void onPostExecute(List<view> data) {
            madapter.clear();


            if (data != null && !data.isEmpty()){
                madapter.addAll(data);
            }
        }

    }

and the onCreate code is

 TitleAsynctask task = new TitleAsynctask();
    URL url = Query_utils.createurl(POEM_TITLE);
            task.execute(url);


            ArrayList<view > arr = new ArrayList<view>();

            final ListView poem_Title_list = (ListView) findViewById(R.id.list_item);
            madapter = new title_adapter(this ,arr);
            poem_Title_list.setAdapter(madapter);
Vidhyanshu jain
  • 341
  • 1
  • 4
  • 16
  • Hope [this](http://stackoverflow.com/questions/5034370/retrieving-a-random-item-from-arraylist) helps – pooja Feb 27 '17 at 07:24

1 Answers1

0

I can think of two ways:

  1. Just use a random number generator to generate a number between 0 and the number of entries-1. The disadvantage with this method is that you can get repeats.

  2. Randomly sort the list after fetching. You can do this using Collections.shuffle(list) This way you won't get any repeats but you will sort the whole list which could be a waste if there are hundreds of entries and you only want to show 20.

theblitz
  • 6,683
  • 16
  • 60
  • 114
  • when i do that it give an exception saying the input size is 521(for example) and the size is 0 , i think that means when i use the ArrayList arr its size is 0, which it clearly is not. – Vidhyanshu jain Feb 27 '17 at 11:05
  • When are you doing the sort? You must do it inside the postExecute. You can't do it in onCreate itself since the fetch is asynchronous. – theblitz Feb 27 '17 at 11:52
  • i didn't sort but still it works until i don't call it to a different method – Vidhyanshu jain Feb 27 '17 at 21:42
  • Sorry, I didn't follow your meaning. Where do you call the method that accesses them? – theblitz Feb 28 '17 at 06:09