"sicknessEntries" : [ null, {
"daysSick" : 1,
"sickness" : "Flu",
"type" : "Viral",
"userId" : "K9lPzGCb1AUdNqNywurwNueunv42"
},
-K9lP-zGCb1AUdNqNywurwN {
"daysSick" : 2,
"sickness" : "Pneumonia",
"type" : "Bacterial",
"userId" : "abcd"
},
-NywurwNueunv42 {
"daysSick" : 1,
"severity" : "Medium",
"sickness" : "Shingles",
"type" : "Viral",
"userId" : "user123"
},
{
"daysSick" : 1,
"severity" : "Medium",
"sickness" : "Flu",
"type" : "Viral",
"userId" : "K9lPzGCb1AUdNqNywurwNueunv42"
} ]
For the above json it shows different type of child i have to retrieve only value of the key "sickness" whether it is in the direct child or in the sub child?
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot friendSnapshot: dataSnapshot.getChildren()) {
System.out.println(friendSnapshot.child("sickness").getValue());
}
}
public void onCancelled(DatabaseError databaseError) {
}
});
If i use the above code it can get only the main child values for the key "sickness" (i.e. it returns the both Flu, Flu only not the others). But i have to get all the sub child values too which have the same key. How to retrieve it?
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference refUsers = database.getReference("/childname");
refUsers.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
try {
Iterable<DataSnapshot> children = dataSnapshot.child("sicknessEntries").getChildren();
List<SickModel> sickList = new ArrayList<>();
for (DataSnapshot child : children) {
SickModel sickmodel = child.getValue(SickModel.class);
sickList.add(sickmodel);
}
Try the above code snippet,for retrieving array of sickmodel.
Where sickmodel has daysSick ,sickness,type,userId
Related
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = database.child("words");
Query word = ref.orderByChild("lang1").equalTo("home");
word.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Word w = singleSnapshot.getValue(Word.class);
Log.i(String.valueOf(R.string.app_name), new Gson().toJson(w));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Log.e(TAG, "onCancelled", databaseError.toException());
}
});
Could you tell me what am I doing wrong? Here I am, trying to get some "Words" from DB & send Json to Console...
UPD: Imported JSON file
{
"words" : {
"1" : {
"id" : 1,
"lang1" : "s1",
"lang2" : "d1",
"type" : "a"
} ,
"2" : {
"id" : 2,
"lang1" : "s2",
"lang2" : "d2",
"type" : "a"
} // ...
}
}
This is my JSON Structure:
{
"users" : {
"userKey1" : {
"deviceToken" : "deviceTokenID",
"displayName" : "Name here",
"dob" : "28/6/2017",
"email" : "efg#wxy.com",
"gender" : "M"
},
"userKey2" : {
"deviceToken" : "deviceTokenID",
"displayName" : "Name here",
"dob" : "28/1/2017",
"email" : "abc#xyz.com",
"gender" : "M",
}
}
}
In my android Firebase file, I type this:
Query findUser = mDatabase.child("users").orderByChild("email").equalTo("abc#xyz.com");
findUser.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.i("findUser","Snapshot: " + dataSnapshot.toString());
}
#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) {
}
});
I get the following log:
06-28 22:06:50.190 30962-30962/in.sample.project I/findUser: Snapshot: DataSnapshot { key = users, value = null }
I do not know why I am getting null when cleary I have a child who's email node matches "abc#xyz.com".
You need a foreach loop to get the user in your findUser query because your query contains a collection.
Query findUser = mDatabase.child("users").orderByChild("email").equalTo("abc#xyz.com");
put this part in your eventlistener
....
public Iterable<DataSnapshot> getChildren (){
for (DataSnapshot child : parent.getChildren()) {
....
}
}
Needed to add security rules.
rules: {
"users" : {
".indexOn": "email",
}
}
I guess, that did the trick. Hope it helps someone. :)
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" : "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"
}
}
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
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());
}
});
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());
}
});
}
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" : "something1#something.com",
"userid" : "fmXWU324VHdDb8v6h7gvNjRojnu33"
},
"-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"
}
}
Please get a idea from below code.
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! :)
I am trying to find the uid from firebase. Let's say I have 3 users in my database, and I want to find the 3rd user uid.
Here is json formate witch is just export from firebase:
{
"-KVKrXu70Ziw0iRw46l5" : {
"age" : 20,
"emailId" : "ameerhamza",
"name" : "hamza"
},
"-KVKrkVy5OojpsSUEI24" : {
"age" : 20,
"emailId" : "ameerhamza",
"name" : "hamza"
},
"-KVKrkzXy9duyiZq5bM0" : {
"age" : 21,
"emailId" : "ameerhamzaaaa",
"name" : "hamza"
},
"-KVKrl5Ax7ptodMYywzg" : {
"age" : 22,
"emailId" : "ameerhamza",
"name" : "hamza"
},
"-KVKrr7E6b4-3x6tuwOX" : {
"age" : 23,
"emailId" : "ameerhamza",
"name" : "hamza"
},
"-KVKruES01regClm6tWW" : {
"age" : 24,
"emailId" : "ameerhamza",
"name" : "hamza"
}
}
Here is code what I done. But it is not working for me.
final FirebaseDatabase database = FirebaseDatabase.getInstance();
myRef = database.getReference();
DatabaseReference newRef = myRef.push();
i++;
Student s = new Student("ameerhamza",i,"hamza");
newRef.child(newRef.getKey()).setValue(s);
final Query queryRef = myRef.orderByChild("emailId").equalTo("ameerhamzaaaa");
queryRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d("Firebase UID ",dataSnapshot.getKey());//it always null
Student s = dataSnapshot.getValue(Student.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
You're creating an extra child and you're searching within the parent. Try something like this:
final FirebaseDatabase database = FirebaseDatabase.getInstance();
myRef = database.getReference();
DatabaseReference newRef = myRef.push();
i++;
Student s = new Student("ameerhamza",i,"hamza");
newRef.setValue(s);
myRef
.orderByChild("emailId")
.equalTo("ameerhamzaaaa")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, Student> data = dataSnapshot.getValue(new GenericTypeIndicator<Map<String, Student>>() {});
Map.Entry<String, Student> entry = data.entrySet().iterator().next();
String uid = entry.getKey();
Student s = entry.getValue();
Log.d("Firebase UID ", uid);
}
#Override
public void onCancelled(DatabaseError databaseError) {
// handle error
}
});
It probably doesn't give you the exact id but should give you a better understanding of what's happening.
All Right fox after so much hard work, finaly i get my ANS , Here is how i get the UID from firebase, i use the Firebase Recyler Adapter to get Data From firebase and next you see your self what i done
adapter = new FirebaseRecyclerAdapter<Student, myViewHolader>(
Student.class,R.layout.item_row,myViewHolader.class,myRef
) {
#Override
protected void populateViewHolder(myViewHolader viewHolder, Student model, int position) {
Log.e("myFirebase UID",adapter.getRef(position).getKey());
}
};
recyclerView.setAdapter(adapter);
I am having trouble with a firebase call that I want to compare if the value is simply true or false. Here is my attempt:
Firebase followingRef = currentUserPath.child("/following");
followingRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(final DataSnapshot dataSnapshot, String s) {
firebaseRef.child("people/" + dataSnapshot.getKey()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
Boolean isFollowing = (Boolean) dataSnapshot.getValue();
if(isFolloiwng) {
User user = snapshot.getValue(User.class);
user.setUserId(dataSnapshot.getKey());
application.getFollowingRecyclerViewAdapter().add(user, application.getFollowingRecyclerViewAdapter());
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
...//OnChildChanged,Moved,etc... no code in here
At the path I want to reference in currentUserPath.child("following"); it looks like this:
EDIT: Replace Picture with actual JSON:
"users" : {
"10206287838487450" : {
"following" : {
"10208425049208936" : true,
"107214969710378" : false,
"1789986447904975" : true
},
"id" : "ae80f030-dea0-4909-944f-0e490847b6ab",
"name" : "Stephen",
"posts" : {
"-KN_oJAgTNJHwJbqY3qk" : true,
"-KN_oN9_Xmw5ULnBRYM7" : true,
"-KN_obYGug9Tdrzufbqc" : true,
"-KNefMk2nX0sOsUx0btx" : true
},
"userId" : "10206287838487450"
},
"people" : {
"10206287838487450" : {
"id" : "9e7ee838-a60a-4588-bc1c-93b98f74356d",
"name" : "Bob",
"userId" : "10206287838487450"
},
"10208425049208936" : {
"id" : "fe6f97e3-0efb-4afb-a322-a1c586f75fb7",
"name" : "Jack",
"userId" : "10208425049208936"
},
"107214969710378" : {
"id" : "ae80f030-dea0-4909-944f-0e490847b6ab",
"name" : "Rick",
"userId" : "107214969710378"
},
"108421236267392" : {
"id" : "c72b35d9-380b-4552-8b05-7426d378fa14",
"name" : "Tommy",
"userId" : "108421236267392"
},
"1112460595485164" : {
"id" : "383692f0-0aba-4d29-afb8-80beefe678c6",
"name" : "Stanley",
"userId" : "1112460595485164"
},
"1789986447904975" : {
"id" : "1ae43255-c040-4b1e-959e-fcdf03e13a45",
"name" : "Link",
"userId" : "1789986447904975"
}
},
I'm very confused because every time I try to cast the dataSnapshot.getValue() to a Boolean, I always get isFollowing = true which is clearly not correct because in my data, there is only 2 values that are true as seen above, not all 3. The confusing thing is how come I can't retrieve the Boolean correctly. I have tried to do Boolean isFollowing = (Boolean) dataSnapshot.getValue(Boolean.class) also but this doesn't work. The Firebase documentation says that when retrieving data, a Boolean can be a type of data we can retrieve but I can't seem to retrieve it correctly. Any help would be appreciated. Thanks!
Works for me:
Firebase ref = new Firebase("https://stackoverflow.firebaseio.com/38671701/users");
Firebase currentUserPath = ref.child("10206287838487450");
Firebase firebaseRef = ref.child("10206287838487450");
Firebase followingRef = currentUserPath.child("/following");
System.out.println("Listening for children on "+followingRef);
followingRef.addChildEventListener(new ChildEventListenerBase() {
#Override
public void onChildAdded(final DataSnapshot dataSnapshot, String s) {
firebaseRef.child("people/" + dataSnapshot.getKey()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
Boolean isFollowing = (Boolean) dataSnapshot.getValue();
System.out.println(dataSnapshot.getKey()+"="+isFollowing);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
});
Listening for children on https://stackoverflow.firebaseio.com/38671701/users/10206287838487450/following
10208425049208936=true
107214969710378=false
1789986447904975=true
Try something like this:
Firebase followingRef = currentUserPath.child("following");
followingRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot: dataSnapshot.getChildren()){
Log.d(TAG, snapshot.getKey();
Log.d(TAG, snapshot.getValue();
//Do your operations here
}
}
}
Change a model class
boolean value
To
Boolean value