Search code examples
androidandroid-recyclerviewrealm

How can I shuffle the contents of a RealmResults object


I have a RealmResults object which holds output of a .where.findAll() query. I am showing contents of this object in a RecyclerView, but since the contents of the RealmResults object are static, it shows same set of records evertime the RecyclerView is opened. I want to shuffle (randomize) the contents of RealmResults so that I can show different values that are in the RealmResults in my RecyclerView. Please suggest some possible ways in which I can perform the same.


Solution

  • You should not randomize the list itself, you should randomize your access of it (the indices).

    Build a list that contains the indexes from [0, n-1]

    List<Integer> indices = new ArrayList<>(realmResults.size());
    for(int i = 0; i < realmResults.size(); i++) {
        indices.add(i);
    }
    

    Shuffle it

    Collections.shuffle(indices);
    

    Then when you pick the view holder data, index realm results with indexed random position

    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if(holder instanceof YourHolder) {
            YourHolder yourHolder = (YourHolder) holder;
            RealmData realmData = realmResults.get(indices.get(position));
            //init data for your holder
        }
    }