Firebase getValue() not retrieving boolean correctly? - android

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

Related

Update field of a firebase key

I have a structure in the firebase with some keys, I would like to know how to update a field of the last key generated.
I need to retrieve the last key generated and update the data, how to do that ???
In Json format
What I would like to change "Status"
"-Kuxu1dX_aMcKZbqpGiQ" : {
"Status" : {
"status" : "Engano"
},
"data" : "26/9/2017 às 8h17",
"funcionario" : "João Cardoso",
"motivo" : "Carta",
"nome" : "Felipe Antunes",
"tempo" : -1506424666540,
"visita" : "null"
},
"-KuxuQuZzcTV5T-PHw18" : {
"Status" : {
"status" : "Engano"
},
"data" : "26/9/2017 às 8h19",
"funcionario" : "João Cardoso",
"motivo" : "Encomenda",
"nome" : "Felipe Antunes",
"tempo" : -1506424770025,
"visita" : "null"
}
To be able to make a change to an item, you'll first need to find that item with a query:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("7VCZ8oJSz...");
Query query = ref.orderByKey().limitToLast(1);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
childSnapshot.getRef().getChild("Status").setValue("New value");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "Query:onCancelled", databaseError.toException());
}
});
To achieve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference yourRef = rootRef.child("7VCZ8oJSz...");
Query query = yourRef.orderByKey().limitToLast(1);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
dataSnapshot.child("Status").child("status").setValue("yourNewValue");
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(eventListener);

How to get realtime database object filtered by param?

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"
} // ...
}
}

Get child names in Firebase

{
"items" : {
"Chemistry" : {
"-KiUOPW8TR_QcEeDbrAy" : {
"answer" : "ssssss",
"id" : "1",
"question" : "sss"
}
},
"Countries" : {
"-KiUR2ilBYN5LJU6uOCf" : {
"answer" : "ffffff",
"id" : "1",
"question" : "fffff"
}
},
"Film" : {
"-KiUOr7GbPhV_perbHt4" : {
"answer" : "dddd",
"id" : "1",
"question" : "dd"
}
}
}
From the above data, I want to get only child names of items.
Eg. I want to get these names
Chemistry
Countries
Film
How can I do that?
To get those names, please use this code:
DatabaseReference itemsRef = FirebaseDatabase.getInstance().getReference().child("items");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.getKey();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
itemsRef.addListenerForSingleValueEvent(eventListener);

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" : "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! :)

How to retrieve data from firebase using key?

"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

Categories

Resources