Home > database >  how to get Random data from Firebase in android studio
how to get Random data from Firebase in android studio

Time:02-27

I want to display random data or quotes from firebase Recyclerview in android studio using java. How to load random data from firebase?

 EntrepreneurRV = (RecyclerView) findViewById(R.id.EntrepreneurRV);
    EntrepreneurRV.setLayoutManager(new LinearLayoutManager(this));
    databaseReference = FirebaseDatabase.getInstance().getReference("Entrepreneur Quotes");
    EntrepreneurRV.setHasFixedSize(true);


    EntrepreneurList = new ArrayList<>();
    EntrepreneurAdapter = new EntrepreneurAdapter(this, EntrepreneurList);
    EntrepreneurRV.setAdapter(EntrepreneurAdapter);

    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                EntrepreneurModel EntrepreneurModel = dataSnapshot.getValue(EntrepreneurModel.class);
                EntrepreneurList.add(EntrepreneurModel);
            }

            EntrepreneurAdapter.notifyDataSetChanged();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });
}

CodePudding user response:

Collections.shuffle randomize the list and will show random data each time recyclerview is refreshed. Update your code like this:

 databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                EntrepreneurModel EntrepreneurModel = dataSnapshot.getValue(EntrepreneurModel.class);
                EntrepreneurList.add(EntrepreneurModel);
                Collections.shuffle(EntrepreneurList); 
            }
  • Related