{
"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);
Related
i have the following json structure:
"Question_Score" : {
"anna_01" : {
"categoryID" : "01",
"categoryName" : "Intelligence",
"question_Score" : "anna_01",
"score" : "20",
"user" : "anna"
},
"anna_03" : {
"categoryID" : "03",
"categoryName" : "Constitution",
"question_Score" : "anna_03",
"score" : "170",
"user" : "anna"
},
"stelios_01" : {
"categoryID" : "01",
"categoryName" : "Intelligence",
"question_Score" : "stelios_01",
"score" : "230",
"user" : "stelios"
},
"stelios_02" : {
"categoryID" : "02",
"categoryName" : "Widsom",
"question_Score" : "stelios_02",
"score" : "220",
"user" : "stelios"
},
I want for currentuser get the categoryID and score. So probably i need to check equality currentuser == user and then get the categoryID and score for this user. As i m new in firebase i find it a little difficult.
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("Question_Score");
// Attach a listener to read the data at your profile reference
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Profile profile = dataSnapshot.getValue(Question_Score.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.v("The read failed: " + databaseError.getCode());
}
});
I dont know from here how to take the values of CategoryId and score to check equality. I ll apriciate any help!
If I understand you correctly you're trying to read the Question_Score child nodes that have a specific value for categoryID. You can do that with a Firebase Database query on the categoryID property:
database = FirebaseDatabase.getInstance();
questionScoreRef = database.getReference("Question_Score");
Query query = questionScoreRef.orderByChild("categoryID").equalTo("01");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
Log.i(TAG, childSnapshot.getKey()+": "+childSnapshot.child("user").getValue(String.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
};
questionScore.addValueEventListener(postListener);
This prints the key and user value of each child node that has categoryID of "01".
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"
} // ...
}
}
I have Database like this:
"Users" : {
"user_ykdF5b234afdgd" : {
"Scoring" : [ {
"Name" : "Name1",
"punkte" : "0"
}, {
"Name" : "Name2",
"punkte" : "0"
} ],
"image" : "",
"membertype" : "bike",
"startnummer" : "1",
"teamname" : "Paul Musterman"
}
},
"user_ykdF5b234afdgd2" : {
"Scoring" : [ {
"Name" : "Name1",
"punkte" : "0"
}, {
"Name" : "Name2",
"punkte" : "0"
} ],
"image" : "",
"membertype" : "bike",
"startnummer" : "1",
"teamname" : "Franz Musterman"
}
},
user_ykdF5b234afdgd is in my Table:
Users : {
user_ykdF5b234afdgd : {
....
I want to display and sum the "punkte" in the Scoring child in every Userchild.
"Scoring" : [ {
"Name" : "Name1",
"punkte" : "100"
}, {
"Name" : "Name2",
"punkte" : "150"
} ],
I want add 100 + 150 and will display the 250 in my Android Layout.
mDatabase.child("Users").child("user_ykdF5b234afdgd/Scoringboard").orderByChild("Name").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot snapshot :
dataSnapshot.getChildren()) {
try {
Log.d("debuug", String.valueOf(snapshot.child("Name").getValue()) + " "+ String.valueOf(snapshot.child("punkte").getValue()));
} catch (NumberFormatException e) {
Log.d("debuug", "Eingabe nicht valide");
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
I tested this and get the scores, but this has two "fails"
1) How can i use this with all my child entries?
mDatabase.child("Users").child("user_ykdF5b234afdgd/Scoringboard").orderByChild("Name").addValueEventListener(new ValueEventListener() {
works only in these child.... TEILNEHMERDATA contains all my users
2) How can I sum the score?
Thanks =)
If anything is unclear, I will explain!
First of all i suggest you adding the values of punkte as Integers and not as Strings. Then, i suggest you change your database structure a little bit. Your database structure should look like this:
Scoring
|
--- scoreId
| |
| --- Name: "Name1"
| |
| --- punkte: 100
|
--- scoreId
|
--- Name: "Name2"
|
--- punkte: 150
To achieve this, i suggest you using the push() method for creating the score ids. Assuming that Users is a direct child of your Firebase root, to sum those values please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int totalPunkte = 0;
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
for(DataSnapshot ds: dSnapshot.child("Scoring").getChildren()) {
int punkte = ds.child("punkte").getValue(Integer.class);
totalPunkte = totalPunkte + punkte;
}
}
Log.d("TAG", totalPunkte);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(eventListener);
Thanks for your reply.
Changed it a little and it works:
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
int sum = 0;
for (DataSnapshot snapScore : snapshot.child("Scoringboard").getChildren()) {
sum += Integer.parseInt(String.valueOf(snapScore.child("punkte").getValue()));
}
try {
this.u = new User(snapshot.getKey(), ((String) snapshot.child("teamname").getValue()), sum);
teilnehmerList.add(this.u);
} catch (NumberFormatException e) {
Log.d("debug", "Punkte nicht valide");
}
}
}
The Solution is:
int sum = 0;
for (DataSnapshot snapScore : snapshot.child("Scoringboard").getChildren()) {
sum += Integer.parseInt(String.valueOf(snapScore.child("punkte").getValue()));
}
"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
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