Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

Firebase Conditional list data retrieval android

I have below table rule in my firebase database

"tests": {
  "$user_id": {
    ".read": "$user_id===auth.uid",
    ".write": "$user_id===auth.uid",

    "$testId": {
      "duration": {
        ".validate": "newData.val().length>1"
      },
      "date": {
        ".validate": "newData.val().length>1"
      },
      "status": {
        ".validate": "newData.val()==='Pending' || newData.val()==='Completed'"
      }
    }
  }
},

Basically tests table will have 2 status, pending and completed and user will have 2 buttons in application for respective status of the test.

I have below FirebaseRecyclerAdapter to list the data.

final DatabaseReference testsRef = FirebaseDatabase.getInstance().getReference(Constants.TEST_TABLE).child(FirebaseAuth.getInstance().getCurrentUser().getUid());
FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter <Tests, TestListHolder > (
  Tests.class,
  R.layout.test_list_card,
  TestListHolder.class,
  testsRef
) {
  @Override
  protected void populateViewHolder(final TestListHolder viewHolder, final Tests model, final int position) {
      testsRef.child(adapter.getRef(position).getKey()).orderByChild("status")
      .equalTo(viewType).addValueEventListener(new ValueEventListener() {
      @Override
      public void onDataChange(DataSnapshot dataSnapshot) {
        //fill the view data
      }

      @Override
      public void onCancelled(DatabaseError databaseError) {
      }
    });

  }
};

So whenever presses Pending or Completed button, I will be passing viewType value as Pending/Completed respectively. But the above orderByChild isn't working and everytime all the data will be fetched in both the views and I believe proper reference of database is not fetched. Could someone help me to achieve this?

Here is the sample data if anyone insist:

"jxW41BgS12edasWtUkZA2G0eLhf2" : { //logged in user id
    "-KfFFioKvMDlAyqw43Yb" : { //testid
      "duration" : 4,
      "date" : 1489552731888,
      "status" : "Completed"
    },
    "-KfFGqIdenjwNdfs232EQ" : {//testid
      "duration" : 5,
      "date" : 1489552731888,
      "status" : "Pending",
    }
  }

Upvotes: 1

Views: 601

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599641

To display only the pending tests:

DatabaseReference testsRef = FirebaseDatabase.getInstance().getReference(Constants.TEST_TABLE).child(FirebaseAuth.getInstance().getCurrentUser().getUid());
Query pendingTestsQuery = testsRef.orderByChild("status").equalTo(viewType);
FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter <Tests, TestListHolder > (
  Tests.class,
  R.layout.test_list_card,
  TestListHolder.class,
  pendingTestsQuery
) {
  @Override
  protected void populateViewHolder(final TestListHolder viewHolder, final Tests model, final int position) {
      // TODO: display model in the viewHolder

  }
};

Upvotes: 1

Related Questions