Firebase: How to load random data into a RecyclerView?

2

I am using a Query to load only 6 Firebase database items in the RecyclerView but so far I can only sort using the orderByChild, limitToFirst or last. Everything is working fine but ...

I want to randomly load items into RecyclerView when activity is loaded.

Is there any way to do this? Firebase, unfortunately, does not have a Random Query, all follow defined orders.

My code:

mDatabase = FirebaseDatabase.getInstance().getReference().child("Category");
query = mDatabase.limitToFirst(6); 

@Override
protected void populateViewHolder(final CategoryViewHolder viewHolder, Category model, int position) {
    viewHolder.setImage(getApplicationContext(), model.getImagem());
    viewHolder.mView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        });
    }
};

mImagesList.setAdapter(firebaseRecyclerAdapter);

My adapter:

public static class CategoryViewHolder extends RecyclerView.ViewHolder {
    View mView;

    public CategoryViewHolder(View itemView) {
        super(itemView);
        mView = itemView;
    }

    public void setImage(Context ctx, String image1) {
        ImageView image = (ImageView) mView.findViewById(R.id.photo);
        Picasso.with(ctx).load(image1).into(image);
    }
}
    
asked by anonymous 04.02.2017 / 17:39

1 answer

0

I recommend you add one more variable to your model class. Something like an "id". And store random values in it (0 to 15 for example). Then you create a method that generates random values (let's call this gerarAleatorio() method). So, when you want random data, you can use the query like this:

query = mDatabase.orderByChild("id").startAt(gerarAleatorio()).limitToFirst(6); 
    
24.02.2017 / 19:33