Josh Joe
Josh Joe

Reputation: 65

How to read / query data from one userID Firebase Android

I want to retrieve data for a given user ID, which I am storing as a value in the database under each user. My database structure looks like below:

user: {
    UserID: { 
       uniqueId: {
         Name: ""
         Email: ""
         userId: ""
    }

    UserID: { 
       uniqueId: {
         Name: ""
         Email: ""
         userId: ""
    }
}

I tried this but it doesn't seem to work as it doesn't display anything on the app:

FirebaseUser user = mAuth.getCurrentUser();
df.child("UsersTable").orderByChild("userid").equalTo(user.getUid())).addChildEventListener

even when I try to give a specific value like below, it still does not read from firebase: ------------- Updated:

I want to get all data from userID. so for example, I want to retrieve all information from fmXWU324VHdDb8v6h7gvNjRojnu33, which will be name, email and userid.

UserTable
{
  "fmXWU324VHdDb8v6h7gvNjRojnu33" : {
    "-KbJtw467nl6p253HZ537" : {
      "Name" : "name1",
      "Email" : "[email protected]",
      "userid" : "fmXWU324VHdDb8v6h7gvNjRojnu33"
    }
  },
  "pJtC45fW0MMi352UiPWnWdIS7h88" : {
    "-Kb012ls9iMnzEL723o9I" : {
      "Name" : "name2",
      "Email" : "[email protected]",
      "userid" : "pJtC45fW0MMi352UiPWnWdIS7h88"
    },
    "-Kb0aq0q25FJq38256SrC" : {
      "Name" : "name3",
      "Email" : "[email protected]",
      "userid" : "pJtC45fW0MMi352UiPWnWdIS7h88"
    },
    "-Kb0atopfK64F6jy124Qi1u" : {
      "Name" : "name3",
      "Email" : "[email protected]",
      "userid" : "pJtC45fW0MMi352UiPWnWdIS7h88"
  }
}

Update 2:

     DatabaseReference df= FirebaseDatabase.getInstance()
                        .getReference("user").child(getCurrentUser().getUid());   

df.addChildEventListener(new ChildEventListener() {
                    @Override
                    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                        get(dataSnapshot);
                    }
            ....
            ...

Update 3:

I assume based on what I am looking for (getting all data under defined userId) the query should look something like this:

df.child("UserTable").child(user.getUid())).addChildEventListener(new ChildEventListener() 

However, this is throwing this error:

Can't convert object of type java.lang.String to type com.android.example.UserTable

Upvotes: 0

Views: 4924

Answers (4)

Uttam Panchasara
Uttam Panchasara

Reputation: 5865

Try Using addChildEventListener and Query like following..

mReference.child("user").orderByChild("userId").equalTo(user.getUid()).addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {

        //deal with data object
    }

    @Override
    public void onChildChanged(DataSnapshot dataSnapshot, String s) {

    }

    @Override
    public void onChildRemoved(DataSnapshot dataSnapshot) {

    }

    @Override
    public void onChildMoved(DataSnapshot dataSnapshot, String s) {

    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

OR use addValueEventListener

mReference.child("user").orderByChild("userId").equalTo(user.getUid()).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

             //deal with data object

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            //toastMsg(databaseError.getMessage());
            Log.e(TAG, "onCancelled: " + databaseError.getMessage());
        }
    });

Upvotes: 1

Charitha Ratnayake
Charitha Ratnayake

Reputation: 379

Please get a idea from below code.

Order objects:

Order objects

DatabaseReference mDatabaseReference = FirebaseDatabase.getInstance()
                .getReference();
DatabaseReference node = mDatabaseReference.child("order")

node.orderByChild("timestamp").equalTo("-KZFQLVAv_kARdfnNnib")
                   .addValueEventListener(mValueEventListener);

private ValueEventListener mValueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            Log.i(TAG, "onDataChange: " + snapshot.getValue());
            // Your code
        }

        @Override
        public void onCancelled(DatabaseError error) {
            Log.w(TAG, "onCancelled: " + error.getMessage());
        }
    };

This return the first order object. Hope you get the point Thanks! :)

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

A Firebase Database query inspects the child nodes directly under the location that you execute it on. If you want to order on a child property of those nodes (i.e. use orderByChild()), that property must exist at a fixed path under each child nodes.

In your case, you have two nested dynamic children, which means you:

  • can query a known user for their results ordered by score
  • can't query across all users for their results ordered by score

If you want to allow the latter query, you'll need to change your data model to allow it. For example, by keeping a list of all results across all players:

ResultsTable:{
    "-KbJtw467nl6p253HZ537" : {
      "Name" : "name1",
      "Email" : "[email protected]",
      "userid" : "fmXWU324VHdDb8v6h7gvNjRojnu33"
    },
    "-Kb012ls9iMnzEL723o9I" : {
      "Name" : "name2",
      "Email" : "[email protected]",
      "userid" : "pJtC45fW0MMi352UiPWnWdIS7h88"
    },
    "-Kb0aq0q25FJq38256SrC" : {
      "Name" : "name3",
      "Email" : "[email protected]",
      "userid" : "pJtC45fW0MMi352UiPWnWdIS7h88"
    },
    "-Kb0atopfK64F6jy124Qi1u" : {
      "Name" : "name3",
      "Email" : "[email protected]",
      "userid" : "pJtC45fW0MMi352UiPWnWdIS7h88"
    }
}

Upvotes: 0

Dibzmania
Dibzmania

Reputation: 1994

Use something like the below code which i am using in my application and it works -

public static void storagesSetup(final Context context){

        if(!hasSignedInUser()) {
            **your business logic here**
            return;
        }

        // Write a message to the database
        final DatabaseReference databaseRef = FirebaseDatabase.getInstance()
                .getReference("cart").child(getCurrentUser().getUid());

        // Read from the database
        databaseRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // This method is called once with the initial value and again
                // whenever data at this location is updated.

                **put your business logic here**

            }

            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                Log.w(TAG, "Failed to read value.", error.toException());
            }
        });
    }

Upvotes: 0

Related Questions