Firebase: How to load random data into a Recyclerview?

Asked

Viewed 379 times

4

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

I want to load items randomly in Recyclerview when Activity is loaded.

Is there any way to do this? Firebase unfortunately does not have a Random Query, they 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);
    }
}
  • You can do a query to search, for example, twenty different images and then on Android scrambles via Java and displays only 10 of them. Since it’s only txt, then don’t spend too much on the internet.

  • The idea of Mr_anderson is not recommended because you will be forcing the user to use more internet than they really need.

  • You can create a javascript function that generates random numbers and place as a firebase function.

1 answer

0

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

query = mDatabase.orderByChild("id").startAt(gerarAleatorio()).limitToFirst(6); 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.