I have read many answers to this question, none solved my problem.
ValueEventListener dataListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
DataSnapshot ls = ds.child("/leafBox001");
DataSnapshot cs = ls.child("/currentState");
Log.i(TAG, "msg " + cs + ls + ds);
}
Log returns the following:
DataSnapshot { key = leafBox001, value = {lightSensor=6793, currentState=false} }
DataSnapshot { key = currentState, value = null }
DataSnapshot { key = leafBox001, value = null }
As you can see, when I try to access a child the values become null.
I also always get null when using getValue. Example of that code:
ValueEventListener dataListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
currentState = ds.child("/leafBox001").child("/currentState").getValue(Boolean.class);
Log.i(TAG, "msg " + cs + ls + ds);
}
I have tried every variation of the above code, always null.
RTD Structure
Your database structure is like this:
leafBox001
lightSensor:6793
currentState: false
then do the following:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("leafBox001");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String sensor = dataSnapshot.child("lightSensor").getValue().toString();
String currentState = dataSnapshot.child("currentState").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The snapshot is at the key leafBox001 then you will be able to access the child of that key.
Related
How to fetch this Data
I only want number and their respective bidding amount.
This id my code:
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Map<String, Object> map = (HashMap<String, Object>) dataSnapshot.child(statusScreenLoaders.get(position).getItemName()).getValue();
for ( String key : map.keySet() ) {
Log.d(TAG, "onDataChange: "+key);
}
for (Object value:map.values()){
Log.d(TAG, "onDataChange: " +value);
}
You can do the following to get the number:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("KitKat");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
String key = ds.getKey();
}
}
String key = ds.getKey(); will return then number that you want. You can then create another reference inside the for loop to get the data of the binding amount:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("KitKat");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
String key = ds.getKey();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("KitKat").child(key);
reference.child("BiddingAmount").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String num = dataSnapshot.child("0").getValue(String.class);
}
}
}
I want to compare text with data from firebase. Below is my code and it reads name only from ing01. but actually i want it to read from all ingredient data, not only ing01. Please help me, thank you.
final String dataCompare=sb.toString();//.replaceAll("\\s+","");
databaseReference = firebaseDatabase.getInstance().getReference().child("ingredients");//.child("ing01").child("iName");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()){
String iName = ds.child("iName").getValue(String.class);
if(dataCompare.equals(iName)){
mResultEt.setText(dataCompare);
mStatusEt.setText("OK");
mStatusEt.setTextColor(Color.GREEN);
}
else{
mResultEt.setText(dataCompare);
mStatusEt.setText("Not OK");
mStatusEt.setTextColor(Color.RED);
}
}
Check this:
FirebaseDatabase.getInstance().getReference().child("ingredients").addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
String iName = childSnapshot.child("iName").getValue(String.class);
//Implement your logic here
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
}
);
Here you will get all the ingredients and through iteration you get the iName.
But According your implementation logic. It's useless to get all the ingredients, rather you can get the specific ingredient matching your compare query. Try like below:
FirebaseDatabase.getInstance().getReference().child("ingredients").orderByChild("iName").equalTo(dataCompare).addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChildren()) {
mResultEt.setText(dataCompare);
mStatusEt.setText("OK");
mStatusEt.setTextColor(Color.GREEN);
} else {
mResultEt.setText(dataCompare);
mStatusEt.setText("Not OK");
mStatusEt.setTextColor(Color.RED);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
}
);
Instead of firebaseDatabase.getInstance().getReference().child("ingredients").child("ing01").child("iName");, use firebaseDatabase.getInstance().getReference().child("ingredients"); for getting all ingredients
you can used a third party library like: Angularfire here is there official link: https://github.com/angular/angularfire
final String dataCompare=sb.toString();
databaseReference = firebaseDatabase.getInstance().getReference().child("ingredients");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String iName1 = dataSnapshot.child("ing01").child("iName");
String iName2 = dataSnapshot.child("ing02").child("iName");
//now here you can compare both the iName values with the dataCompare object.
}
}
**** EDIT ****
final String dataCompare=sb.toString();
Log.d("DataCompare: ", dataCompare);
databaseReference = firebaseDatabase.getInstance().getReference().child("ingredients");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getChildren() == null) {
Log.d(TAG, "onDataChange: snapshot has no children");
} else {
int i = 1;
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String iName = ds.child("ing0" + i++).child("iName").getValue();
// if this doesn't work try this --
// String iName = ds.child("iName").getValue();
Log.d(TAG, "name value: " + iName);
if (iName.equals(dataCompare)) {
Log.d(TAG, "onDataChange: string equals");
} else {
Log.d(TAG, "onDataChange: strings are not equal");
}
}
}
}
}
Inside the onDataChange() method I wrote :-
String iName = ds.child("ing0" + i++).child("iName").getValue();
here we are reading the child "ing01" (in the first iteration of the loop) of the datasnapshot which is currently at "ingredients", and then we read "iName" and its value into iName string object.
for each loop will do this for all the children of the dataSnapshot which means for all the data you have in your firebase database.
I am trying to get a parent value of a field in Firebase database along with its children.
for clarification:
I want to loop through the Snapshot to find the user who want to login by his or her ID, after that I want to get the parent of that id (i.e. is the user female or male) after that I want to get the canton and name.
so what I am doing is:
database=FirebaseDatabase.getInstance();
rootRef = database.getReference();
users = rootRef.child("Users");
and then
users.orderByChild("name").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
if (child.getValue().equals(curUser.getUid())) {
String gender = child.getKey().toString();
currentPolUser.setuGender(gender);
currentPolUser.setuName(child.child("Name").getValue().toString());
Log.d("FirebaseUsers", "SUCCESSSSSS: "+currentPolUser.getuName() + " " + currentPolUser.getuGender());
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The problem is child.getValue() returns an object that can't be compared to the User id string.
Try this:
ref.child("Users").orderByChild("name").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
String gender = child.getKey();
for(DataSnapshot finalChild : child.getChildren()){
if (finalChild.getKey().equals(curUser.getUid())) {
HashMap<String, Object> map = (HashMap<String, Object>) finalChild.getValue();
String name = (String) map.get("name");
currentPolUser.setuGender(gender);
currentPolUser.setuName(name);
Log.d("FirebaseUsers", "SUCCESSSSSS: "+currentPolUser.getuName() + " " + currentPolUser.getuGender());
Log.e("TTT", name);
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I am new to Firebase. I have following data in firebase:
Inside EventPlayer I have array of data for key eventID. I want to get all objects for a eventID in an Array.
My code:
final String eventId=intent.getStringExtra("EventID");
mref.child("EventPlayer").child(eventId).orderByChild("eventID").equalTo(eventId);
// Attach a listener to read the data at our posts reference
mref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
EventRequest post = child.getValue(EventRequest.class);
if(post != null){
System.out.println(post);
arrPlayers.add(post);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
The post has no value and it is an empty class.
Edit
Code for creating arrraylist:
arrPlayers = new ArrayList<EventRequest>();
Try this code. The only change is in the first few lines, with the postQuery variable.
final String eventId=intent.getStringExtra("EventID");
Query postQuery = mref.child("EventPlayer").child(eventId).orderByChild("eventID").equalTo(eventId);
// Attach a listener to read the data at our posts reference
postQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
EventRequest post = child.getValue(EventRequest.class);
if(post != null){
System.out.println(post);
arrPlayers.add(post);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
Your second line of code creates a Query object, but you never assign it to anything. Assigning it to a new variable and then adding the ValueEventListener to that new variable should get you to your data.
To get all those event ids, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference eventIdRef = rootRef.child("EventPlayer").child(eventId);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String eventID = ds.child("eventID").getValue(String.class);
list.add(eventID);
Log.d("TAG", eventID);
}
Log.d("TAG", list);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
eventIdRef.addListenerForSingleValueEvent(eventListener);
I have this data structure:
The red arrows points at animal IDs, and the blue arrow points at user IDs. Every user have one or many animals.
I have tried different methods for showing only the animals that have id that is stored in the current user node.
Example: If I have UID = 48onHXIxgDP465j5WW16oo7psNm2 (the first one in "users") I want to show the data from: "dog2" and "dog3".
Now iIhave the following code that gets snapshot from the "animals" node in the database, and then gets data from every child.
myAnimalRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
list = new ArrayList<AnimalCard>();
for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){
AnimalCard value = dataSnapshot1.getValue(AnimalCard.class);
AnimalCard animal = new AnimalCard();
String name = value.getName();
int age = value.getAge();
String url = value.getUrl();
animal.setName(name);
animal.setAge(age);
animal.setUrl(url);
list.add(animal);
}
recyclerViewSetAdapter();
progressDialog.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG1, "failed to read value: " + databaseError.toException());
}
});
How can get my code to filter out every animal that does not have their ID in the user node?
The reason I want to make the user get access with an UID stored in the database is because later on I want to make it so that multiple users can get access to the same animal.
To achieve this, you need to query your database twice. Please use the following code:
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
String uid = firebaseUser.getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = usersRef.child("users").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String aid = ds.getKey();
DatabaseReference animalRef = rootRef.child("animals").child(aid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dSnapshot) {
int age = dSnapshot.child("age").getValue(Integer.class);
String name = dSnapshot.child("name").getValue(String.class);
String url = dSnapshot.child("url").getValue(String.class);
Log.d("TAG", age + " / " + name + " / " + url);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
animalRef.addListenerForSingleValueEvent(valueEventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(eventListener);
In which uid is the id of the logged-in user and aid is the id of the animal. Your output will be:
11 / dog1 / http...
12 / dog2 / http...
Hope you find this helpfull.!
Get Object in Your Model Class and Store that Object in List for Further user.!
You can get specific object as well simple using
mdatabaseRef.child("animals").orderByChild().equalTo("value")
and also you can add check on key by orderByKey()
private FirebaseAuth mAuth;
private FirebaseDatabase mdatabase;
private DatabaseReference mdatabaseRef;
mAuth = FirebaseAuth.getInstance();
mdatabase = FirebaseDatabase.getInstance();
mdatabaseRef = mdatabase.getReference();
ArrayList<User> allUserList = new ArrayList<>();
Array<Animal> allAnimalList=new ArrayList<>();
mdatabaseRef.child("animals").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
String key = childSnapshot.getKey();
Animal animal = childSnapshot.getValue(Animal.class);
allAnimalList.add(animal );
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mdatabaseRef.child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
String key = childSnapshot.getKey();
User user = childSnapshot.getValue(User .class);
allUserList.add(user);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I ended up taking Alex Mamo's answer and tweak with a litte bit.
This is the code i'am using:
uid = currentUser.getUid();
mRootRef = FirebaseDatabase.getInstance().getReference();
final DatabaseReference myUserRef = mRootRef.child("users").child(uid);
Log.d(TAG1, uid);
myUserRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
list = new ArrayList<AnimalCard>();
for(DataSnapshot ds : dataSnapshot.getChildren()){
String aid = ds.getKey();
DatabaseReference myAnimalRef = mRootRef.child("animals");
Query query = myAnimalRef.orderByKey().equalTo(aid);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds2 : dataSnapshot.getChildren()){
AnimalCard value = ds2.getValue(AnimalCard.class);
AnimalCard animal = new AnimalCard();
String name = value.getName();
int age = value.getAge();
String url = value.getUrl();
animal.setName(name);
animal.setAge(age);
animal.setUrl(url);
list.add(animal);
}
recyclerViewSetAdapter();
progressDialog.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The main difference is that i'am using a query to filter out every Animal that does not have the aID that the currentUser have.