Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

java - Select next value firebase android

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?

question from:https://stackoverflow.com/questions/65893855/select-next-value-firebase-android

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();    
        }
      }    
  });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...