1

I am having issues trying to display some data on the screen.

Example of my data:

enter image description here

What i want:

I want to be able to display the data -

QUOTE

AUTHOR

on the two text fields I have.

However, i want the data to be fetched randomly when a user goes to that page.

so if i go to home page and come back to quote page it might show me the 3rd quote and if i close app and open again, it might show me the 5th quote. I do not want to display them all at once in a list.

I have tried:

How to fetch data from firebase real time database in android

Get random data android firebase database in RecyclerView

my current code:

name = findViewById(R.id.author);
    quote = findViewById(R.id.quote);

    auth = FirebaseAuth.getInstance();
    user = auth.getCurrentUser();

    databaseReference = FirebaseDatabase.getInstance().getReference("Quotes");

    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for(DataSnapshot datas: dataSnapshot.getChildren()){
                String authorName = datas.child("AUTHOR").getValue().toString();
                String quoteGiven = datas.child("QUOTE").getValue().toString();

                name.setText(authorName);
                quote.setText(quoteGiven);
            }
        }
AHPV
  • 77
  • 7
  • i get this error for trying the random recylerviewer one java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference – AHPV Dec 10 '19 at 20:54

1 Answers1

1

Found out why it was not working, it was in the wrong order. Here is the final answer

name = findViewById(R.id.author);
    quote = findViewById(R.id.quote);
    btn = findViewById(R.id.button);

    auth = FirebaseAuth.getInstance();
    user = auth.getCurrentUser();

    databaseReference = FirebaseDatabase.getInstance().getReference("Quotes");
    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            int count = (int) dataSnapshot.getChildrenCount();
            for(DataSnapshot datas: dataSnapshot.getChildren()){
                int rand = new Random().nextInt(count);
                    for (int i = 0; i < rand; i++) {
                        String authorName = datas.child("AUTHOR").getValue().toString();
                        String quoteGiven = datas.child("QUOTE").getValue().toString();
                        name.setText(authorName);
                        quote.setText(quoteGiven);
                    }
            }
        }
AHPV
  • 77
  • 7