cBankRef=myRef.child("user_id").child("ASSETS");
cBankRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String value = dataSnapshot.child("1").child("description").getValue(String.class);
Log.d(TAG, "onChildAdded: the value is"+value);
if(dataSnapshot.child("2").exists()) {
String valuess = dataSnapshot.child("3").child("description").getValue(String.class);
Log.d(TAG, "onChildAdded: the value is: " + valuess);
}
if (dataSnapshot.child("3").exists()) {
String values = dataSnapshot.child("1").child("description").getValue(String.class);
Log.d(TAG, "onChildAdded: the cash at bank is: "+values);
}
}
#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) {
}
});
first i accessed the user_id child and the ASSETS then through the nodes ("1"),("2") i had to add other nodes in order to get the value, the("1") and ("2") were ("Cash at Bank") ("stock") in the beginning but i decided to change them to numbers but it's giving null #makrand pawar
You have multiple issues in your example:
Your cBankRef is pointing to \user_id\ASSETS\Cash at bank\stock\Cash in Hand, which does not exist (Cash at bank node does not exist under ASSETS).
You are then attaching a ChildEventListener to this reference, which won't return any values, because there aren't any children under it (as it doesn't exist).
Inside onChildAdded(), you are trying to access the houses node which also doesn't exist in your example (house does though).
To access the children under the Stock node, you'll need something like:
ref = FirebaseDatabase.getInstance().getReference().child("user_id").child("ASSETS").child("Stock");
ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String value = dataSnapshot.child("house").child("values").getValue(String.class);
Log.d(TAG, "onChildAdded: the value is: "+value);
}
// ...
});
The DatabaseReference#child() method is not a SELECT statement. To access everything underneath a node, you only need to create a reference to the highest node required, then attach a listener to that.
For example, if you need access to everything underneath the ASSETS node, you could attach a listener there instead:
ref = FirebaseDatabase.getInstance().getReference().child("user_id").child("ASSETS");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = dataSnapshot.child("Stock").child("house").child("values").getValue(String.class);
Log.d(TAG, "onChildAdded: the value is: "+value);
if (dataSnapshot.child("Cash at bank").exists()) {
String value = dataSnapshot.child("Cash at bank").getValue(String.class);
Log.d(TAG, "onChildAdded: the cash at bank is: "+value);
}
}
// ...
});
Then when the listener returns you can use DataSnapshot#child() instead to access the individual values retrieved from that location. Also, using DataSnapshot#exists() is a simple way to check that a node exists before using it.
If you plan to have additional values or nodes under ASSETS that don't currently exist, they will be returned by the above listener as soon as they are created.
To achieve this, i suggest you using ValueEventListener like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference stockRef = rootRef.child("user_id").child("ASSETS").child("Stock");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String values = ds.child("house").child("values").getValue(String.class);
Log.d("TAG", values);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
stockRef.addListenerForSingleValueEvent(eventListener);
Related
I want to pass data from one activity to another, first I download it from Firebase Realtime Database and then pass it to another activity and how to use it in it.
my data like this.(image from the internet)
cam_firebase.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NotNull DataSnapshot dataSnapshot, String s) {
// long count = dataSnapshot.getChildrenCount();
double longt = dataSnapshot.child("longt").getValue(Double.class);
double lat = dataSnapshot.child("lat").getValue(Double.class);
String type = dataSnapshot.child("type").getValue(String.class);
List<Model> list = new ArrayList<>();
list.add(new Model());
list.get(0).setLat(lat);
list.get(0).setLongt(longt);
cameras_info.onCallback();
}
#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(#NonNull #NotNull DatabaseError error) {
}
});
Assuming that pXGb...lGE2 is the UID of the logged-in user, to be able to read the data that corresponds to your schema, then please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = db.child("ProgressReportss").child(uid);
uidRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
DataSnapshot snapshot = task.getResult();
for (DataSnapshot ds : snapshot.getChildren()) {
String content = ds.child("content").getValue(String.class);
String timestamp = ds.child("timestamp").getValue(String.class);
String title = ds.child("title").getValue(String.class);
Log.d("TAG", content + "/" + timestamp + "/" + title);
}
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
The result in the logcat will be:
Test 2/30-11-2018/Test 2
Test 3/30-11-2018/Test 3
Test 4/30-11-2018/Test 4
That's how you read it. If you need to send the data to another activity, inside the onComplete() use the logic in the following answer:
How to pass an object from one activity to another on Android
I am building an app that needs to retrieve all child from a certain parent node and would like to perform a method call on each child retrieved.
Here is my current database:
Click Me
I would like to call all child of conradjr and on retrieval of a child for example "ranniecardino15", it should store it to a variable then perform a method call. How can I do this?
I have made a code like this but the method call "getCurrentLocation" is only performed on the last child retrieved.
public void getCurrentChildUser() {
DatabaseReference getuser = FirebaseDatabase.getInstance().getReference().child("Children");
getuser.child(user).orderByChild("CurrentLocation").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
childuser = childSnapshot.getKey();
if (childuser != null){
getCurrentLocation();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void getCurrentLocation(){
DatabaseReference getuser = FirebaseDatabase.getInstance().getReference().child("Children");
getuser.child(user).child(childuser).child("CurrentLocation").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot != null){
currentloc = dataSnapshot.getValue(String.class);
System.out.println("Current Location: "+currentloc);
String split[] = currentloc.split(",");
lat1 = Double.parseDouble(split[0]);
lng1 = Double.parseDouble(split[1]);
System.out.println("Current Latitude: "+lat1+" and Current Longitude: "+lng1);
getSavedLocation();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
}
Please help me :) Thanks in advance :)
To solve this, you need to change the declaration of your getCurrentLocation() method from:
public void getCurrentLocation(){}
to
public void getCurrentLocation(String childuser){}
Now you need to call this method from inside the onDataChange() method like this:
getCurrentLocation(childuser);
See, I have passed the childuser as an argument to the getCurrentLocation() so it can be used in a proper way.
I have this structure in my Firebase Real-time database :
How can I count the data and show it in my app, which listener shall I use to get all childrens?
There are a few ways in which you could achieve this.
I use the following way:
FirebaseDatabase.getInstance()
.getReference()
.child("demografi")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnap : dataSnapshot.getChildren()) {
YourObject object = dataSnap.getValue(YourObject.class);
// Use your object as needed
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
dataSnapshot returns the child referenced. Once you have it, all you have to do is iterate through them and you have access to "all children" as you wanted.
FirebaseDatabase.getInstance()
.getReference()
.child("demografi")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
/** Qty of data in demografi, this is what you want. */
long Count = dataSnapshot.getChildrenCount();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
if you want to monitor the count of data in realtime way,
you have to replace [addListenerForSingleValueEvent] with [addValueEventListener].
I will prefer this way -
String email, gender, nama;
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("demografi");
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
// To get children count
dataSnapshot.getChildrenCount();
email = dataSnapshot.child("email").getValue().toString();
gender = dataSnapshot.child("gender").getValue().toString();
nama = dataSnapshot.child("nama").getValue().toString();
// and so on..
}
#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) {
}
});
If you don't have a model class, you can simply use the String class. So to get all child's data, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference demografiRef = rootRef.child("demografi");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String nama = ds.child("nama").getValue(String.class);
Log.d("TAG", nama);
}
Log.d("TAG", String.valueOf(dataSnapshot.getChildrenCount()));
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
demografiRef.addListenerForSingleValueEvent(valueEventListener);
The output in your logcat will be all the names of all your users. As you can see, there is a second log statement which will print the total number of your children.
I am using Google Firebase to store database of user heartbeat from Android Wear.
Now I'm trying to retrieve the heartbeat value on child "tmpHR" but the value keeps on showing null.
Here is the structure of my database :
I want to retrieve int tmpHR child value under the random key
Here's my lines of code :
Integer hrValue;
ArrayList<Integer> array1;
array1 = new ArrayList<>();
DatabaseReference userdatabase = FirebaseDatabase.getInstance().getReference().child("Users");
DatabaseReference ref = userdatabase.child(user.getUid()).child("hrvalue").child("nilaihr");`
`ref.addChildEventListener(new ChildEventListener() {`
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for (DataSnapshot uniqueKeySnapshot : dataSnapshot.getChildren()) {
//Loop 1 to go through all the child nodes of nilaihr
//store random key in uniqueKeySnapshot
Integer hrValue = uniqueKeySnapshot.child("tmpHR").getValue(Integer.class);
// random key -> child tmpHR -> store in Integer hrValue
Log.i("heart rate value", "hrvalue " + hrValue);
showData(dataSnapshot);
}
}
#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) {
}
});
}
private void showData(DataSnapshot dataSnapshot) {array1.add(hrValue);}
And here's the logcat :
05-15 19:01:55.824 27624-27624/com.example.amiramaulina.retrievedataheartbeat I/database array: array database [null, null, null,....., null]
05-15 19:01:55.824 27624-27624/com.example.amiramaulina.retrievedataheartbeat I/heart rate value: hrvalue null
Before, there was only one child (which is Integer "tmpHR") under the random key, and I have succeeded to retrieve the value. Since I added another child (String Date), the value of tmpHR keeps on returning null.
Any solutions would be appreciated.
Thank you!
Try the following:
ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Integer hrValue = dataSnapshot.child("tmpHR").getValue(Integer.class);
showData(dataSnapshot);
}
#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) {
}
});
Remove the for loop, since you do not need to loop to be able to retrieve tmpHR in this case.
mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseRef = mFirebaseInstance.getReferenceFromUrl("https://c7d86.firebaseio.com");
mFirebaseRef.child("bloodgroup").equalTo("B+").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
getUpdate(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
getUpdate(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
So please help me because I am a new learner for firebase and have to know how to write a query in this.
Firebase Database queries evaluate the children under the node where you execute the query. So in your case when you use mFirebaseRef.child("bloodgroup") it will look for a /bloodgroup and then query the children under that. Since there is no /bloodgroup, there are no results.
The correct code:
mFirebaseRef = mFirebaseInstance.getReference();
DatabaseReference queryLocation = mFirebaseRef.child("the key under bloodfinder-c7d86 in the screenshot");
Query query = queryLocation.orderByChild("bloodgroup").equalTo("B+");
query.addChildEventListener(new ChildEventListener() {
#Override
Note that I had to do some guesses, because you shared a picture of the JSON. For future questions, share the JSON as text. You can get this by clicking the "Export JSON" link in your Firebase Database console.