Select next value firebase android

Tags: , , ,



I’d like to get first register and then the second one when user click in next button, and so on…

I have this:

 <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="47dp"
        android:onClick="next"
        android:text="Button" />

and this:

public void next(View view) {
    read();
}

My firebase is:

private void read() {

    mDatabase.child("question").child("cf").orderByKey().limitToFirst(1).addListenerForSingleValueEvent(new ValueEventListener() {

    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

        for (DataSnapshot recipeSnapshot: dataSnapshot.getChildren()) {

            lastKey = recipeSnapshot.getKey();

            String pergunta = Objects.requireNonNull(recipeSnapshot.child("question").getValue()).toString();
            Toast.makeText(MainActivity.this, pergunta, Toast.LENGTH_SHORT).show();    
        }
    }    
});

So when user open the activity I’d like to show the first value and when he clicks in button I’d like to show the second and so on.

Any ideas how to solve this?

Answer

You’ve already found how to limit the amount of data return by Firebase: .limitToFirst(1).

Not to get the next item in Firebase, you need to know at which item to start returning data. In your case that means you need to:

  1. Know the key of the node that you’re currently showing.
  2. Retrieve 2 nodes starting at that key.

Given that you already key lastKey, you can read the next result with:

private void read() {
    Query query = mDatabase.child("question").child("cf").orderByKey();

    if (lastKey != null) {
        query = query.startAt(lastKey).limitToFirst(2);
    }
    else {
        query = query.limitToFirst(1);
    }

    query.addListenerForSingleValueEvent(new ValueEventListener() {
      @Override
      public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        for (DataSnapshot recipeSnapshot: dataSnapshot.getChildren()) {
            lastKey = recipeSnapshot.getKey();

            String pergunta = Objects.requireNonNull(recipeSnapshot.child("question").getValue()).toString();
            Toast.makeText(MainActivity.this, pergunta, Toast.LENGTH_SHORT).show();    
        }
      }    
  });


Source: stackoverflow