user2921885
user2921885

Reputation: 189

Firebase Database sort by time of unknown node

I am trying to retrieve the following in time order:

Firebase Database Structure

Where the known value is the current token of the authenticated user but the unknown value is a user that has been created before, from a server environment.

    mDatabase = FirebaseDatabase.getInstance().getReference("users");

    mDatabase.child("users").child(user.getUid());

    mDatabase.child(user.getUid()).addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {


            GenericTypeIndicator<Map<String, Object>> t = new GenericTypeIndicator<Map<String, Object>>() {
            };
            Map<String, Object> map = dataSnapshot.getValue(t);

            assert map != null;


            for (Object e : map.values()) {
                list.add(e.toString());
            }

            for (Object e : map.keySet()) {
                list1.add(e.toString());
            }

I have tried to use orderByChild("time") on the addValueEventListener but I do not think its working as I can not point the right location in the database as I am unable to get the value of the user

Edit:

            try {
                for (int i = list1.size()-1; i == list1.size()-1; i++) {

                    String guestname = String.valueOf(dataSnapshot.child(list1.get(i)).child("username").getValue());
                    String guestemail = String.valueOf(dataSnapshot.child(list1.get(i)).child("email").getValue());
                    String guestpassword = String.valueOf(dataSnapshot.child(list1.get(i)).child("password").getValue());

                    Log.w(TAG, "Name of newest value is " + guestname);
                    Log.w(TAG, "Email of newest value is " + guestemail);
                    Log.w(TAG, "Password of newest value is " + guestpassword);
                    guestname1 = guestname;
                    guestpassword1 = guestpassword;
                    guestemail1 = guestemail;
                }

Upvotes: 0

Views: 354

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600016

You'll want to use orderByChild() for that:

mDatabase = FirebaseDatabase.getInstance().getReference("users");

Query query = mDatabase.child(user.getUid()).orderByChild("time")

query.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    for (dataSnapshot childNode: dataSnapshot.getChildren()) {
      System.out.printl(childNode.getKey()); //this is the unknown key you marked
      System.out.printl(childNode.child("time").getValue(Long.class));
    }
  }

  ...

Upvotes: 1

Related Questions