Search code examples
javaandroidarraylistandroid-viewmodelobservers

How to recieve 5 random Objects from Room database and add them to a new ArrayList


  1. I have method personViewModel.getNoobs(); which returns List<Person> from Room database;
  2. I have new ArrayList<Person> currentNoobList; in my Activity.

I need to take 5 random Persons from database and add them to currentNoobList in onCreate().

As far as I know, I need to use .observe in order to get random Objects from that List<Person> which I get using method getNoobs(); but I cannot understand how to write this code correctly. Could you help?

Thanks!


Solution

  • If you are using Java 8 onward, something like this would work, provided that there are >= 5 elements in the list:

    List<Person> personList = personViewModel.getNoobs();
    Random random = new Random();
    IntStream.range(0,5).forEach(val ->
                  currentNoobList.add(personList.remove(random.nextInt(personList.size()))));
    

    If you are unable to use Java 8, this answer could come in handy.

    Given that you are using a Room Database, you could add an annotated method stub in your DAO interface and make appropriate changes such that you can directly get your results via your database. Something like this in your DAO:

    @Query("SELECT * FROM person ORDER BY RANDOM() LIMIT 5")
        public List<Person> getFiveRandomPersons();
    

    Typically an observer would observe a subject; Checkout Observer Pattern. Given there isn't much information, I believe you are using Livedata, since you mentioned .observe in context with the Room Database. This documentation and this codelab might give you some idea on the usage of observe().