3

In my firebase database, I have list of users that have different information under them. I would like to retrieve information from a single userId, which I will define in the code and I want to only get information from that user.

My data looks like;

UserTable
{
  "fmXWU324VHdDb8v6h7gvNjRojnu33" : {
    "-KbJtw467nl6p253HZ537" : {
      "Name" : "name1",
      "Email" : "something1@something.com",
      "userid" : "fmXWU324VHdDb8v6h7gvNjRojnu33"
    }
  },
  "pJtC45fW0MMi352UiPWnWdIS7h88" : {
    "-Kb012ls9iMnzEL723o9I" : {
      "Name" : "name2",
      "Email" : "something2@something.com",
      "userid" : "pJtC45fW0MMi352UiPWnWdIS7h88"
    },
    "-Kb0aq0q25FJq38256SrC" : {
      "Name" : "name3",
      "Email" : "something3@something.com",
      "userid" : "pJtC45fW0MMi352UiPWnWdIS7h88"
    },
    "-Kb0atopfK64F6jy124Qi1u" : {
      "Name" : "name3",
      "Email" : "something1@something.com",
      "userid" : "pJtC45fW0MMi352UiPWnWdIS7h88"
  }
} 

and I want to, say for example read and display all data from this user "fmXWU324VHdDb8v6h7gvNjRojnu33". I am not sure how I can do that. I tried this, which seems logical but it doesn't seem to work:

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

it gives this error:

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

In addition, I have tried:

df.child("UsersTable").child("userid").child(user.getUid()).ad‌​dChildEventListener(‌​new ChildEventListener() 

I can seem to figure out what I am doing wrong, as what I have tried seems logical and should work. Please can someone help me out.

EDITED:

public ArrayList<data> get(String userID){

      df.child("UsersTable").child(userID).ad‌​dChildEventListener(‌​new ChildEventListener()  {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        fetch(dataSnapshot);
    }

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

    @Override
    public void onChildRemoved(DataSnapshot dataSnapshot) {

    }

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

    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

return data;

Update

private void fetchData(DataSnapshot dataSnapshot)
{

    for (DataSnapshot ds : dataSnapshot.getChildren())
    {
        Userdetail userdetail =ds.getValue(Userdetail.class);
        userdetails.add(userdetail );
    }
}
wake-0
  • 3,918
  • 5
  • 28
  • 45
Josh Joe
  • 65
  • 1
  • 2
  • 9
  • Can you please add the code within child event listener. The error seems to propagate from there – Mohammad Aasif Jan 25 '17 at 12:50
  • Please see update – Josh Joe Jan 25 '17 at 12:57
  • Why are you using key inside u_id? – Rishabh Mahatha Jan 25 '17 at 13:12
  • its push Id to store entries from same user as unique. because 1 user can add multiple data under they id and I want each data to be unique and not override the previous – Josh Joe Jan 25 '17 at 13:15
  • ohk i add the solution check it – Rishabh Mahatha Jan 25 '17 at 13:18
  • You can read more about how to work with Firebase retrieve data in the official documentation: https://firebase.google.com/docs/database/admin/retrieve-data – Francisco Durdin Garcia Jan 25 '17 at 17:26
  • @FranciscoDurdinGarcia Thanks for the link. I am having 1 issue and I have search everyone but I can't seem to find a solution. I have a recylerview to which I am loading the data from Firebase, however, recylerview does not automatically show data and I have to click on a edittext to load the data. I think this might be because the layout/recylerview is not refreshing but I have tried almost everything I could find but I can't seem to fix it. Do you know a solution? – Josh Joe Jan 25 '17 at 17:36
  • @JoshJoe Are you calling `notifyDataSetChanged();`after set your new values? Also, why you are not using `FirebaseRecyclerAdapter` to works with `RecyclerView` and Firebase? The API give you some support classes to implement this kind of things more easily, as `RecyclerViews` and `Lists` – Francisco Durdin Garcia Jan 25 '17 at 17:39
  • @JoshJoe You can find a good example about how to use `FirebaseRecyclerAdapter` in the next question: http://stackoverflow.com/questions/36235919/how-to-use-a-firebaserecycleradapter-with-a-dynamic-reference-in-android – Francisco Durdin Garcia Jan 25 '17 at 17:40
  • Yes, I have tried but no luck – Josh Joe Jan 25 '17 at 17:43
  • I didn't come across FirebaseRecyclerAdapter when I started my project and I am 70% finish if I change now I will need to change 60% of the code. Which will be a nightmare :) – Josh Joe Jan 25 '17 at 17:44

3 Answers3

1

First initialize your database like this

mDatabase= FirebaseDatabase.getInstance().getReference().child("your_node_name");

then try setting a ValueEventListener to your Database reference. Inside the onDataChange method you can retrieve your data like this

public void onDataChange(DataSnapshot dataSnapshot) {
    User user= dataSnapshot.getValue(User.class);
}

EDIT:

ValueEventListener postListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        User user= dataSnapshot.getValue(User.class);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
};
mDatabase.addValueEventListener(postListener);
wake-0
  • 3,918
  • 5
  • 28
  • 45
Mufad
  • 191
  • 1
  • 15
  • Hi, sorry I am not sure how this would work because you haven't added any listener. – Josh Joe Jan 25 '17 at 13:01
  • Currently as my code is, I am able to retrieve data but the data is being retrieved from all users I want to only get from defined userid – Josh Joe Jan 25 '17 at 13:06
  • Thanks for the update, could I please check how I can retirve data only from one user (for a user which I give userid for) – Josh Joe Jan 25 '17 at 13:10
  • I was facing same situation with ChildEventListener, you can use a ValueEventListener in your database reference and change the reference to `mDatabase= FirebaseDatabase.getInstance().getReference().child("your_node_name").child("userID");` – Mufad Jan 25 '17 at 13:15
  • Do you know how I can delete specific entry from firebase, given a uId and pushID? – Josh Joe Jan 25 '17 at 14:11
  • You're welcome, just use `mDatabase.removeValue();` to remove the child! – Mufad Jan 25 '17 at 15:01
  • Also, I have my data being loaded in in recylerview from firebase. However, the recylerview does not automatically refresh and I to click an editbox to make the the appear on the app. Do you know how this can be fixed? – Josh Joe Jan 25 '17 at 16:08
1
  DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("UsersTable").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if(dataSnapshot.exists())
        {
            for(DataSnapshot userDetails : dataSnapshot.getChildren()) {
                Log.d("valueName:", userDetails.child("Name").getValue());
                Log.d("valueEmail:", userDetails.child("Email").getValue());
                Log.d("valueuserid:", userDetails.child("userid").getValue());
            }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

use this will solve your problem.

Rishabh Mahatha
  • 1,251
  • 9
  • 19
0

Add value event listener instead of child event listener.

df.child("UsersTable").child(user.getUid()).addValueEventListener(newValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
           if(dataSnapshot!=null){
             fetch(dataSnapshot);
           }
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });
Saurabh Padwekar
  • 3,888
  • 1
  • 31
  • 37