Android - getValue from Firebase returns null - android

I am setting the value of a child in Firebase, but when I get the value from Firebase the value is null. I don't understand why.
database.child("User").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int depositInteger = 0;
try {
depositInteger = Integer.parseInt(depositText.getText().toString().trim());
} catch (NumberFormatException e) {
if (depositText.equals("")) {
Toast.makeText(getActivity(), "Failed", Toast.LENGTH_SHORT).show();
}
}
database.child(user.getDisplayName()).child("deposit").setValue(depositInteger);
Long previousDeposit = dataSnapshot.child("User").child(user.getDisplayName()).child("deposit").getValue(Long.class);
System.out.println("VAAAALUE: " + previousDeposit);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

To set a value, you can use setValue() method directly on the reference like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("Users").child(user.getDisplayName());
userRef.child("deposit").setValue(9); //Sets the value to 9
To get the value, please use the following code:
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int deposit = dataSnapshot.child("deposit").getValue(Integer.class);
Log.d("TAG", deposit);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userRef.addListenerForSingleValueEvent(eventListener);
Please see the correct DatabaseReference which contains Users and not only User as shown in your screen-shot.

According your database structure the child you should reference is Users and in your code you are calling User. Fix that mistake...
//Replace child tag by Users to fix the error
database.child("Users").addValueEventListener(new ValueEventListener() { ...

Related

Firebase Database Read Data

I am trying to read some values from Firebase Real time database.
My structure looks like this:
and my code to retrieve the value("Wine and Dine"):
databaseReference.child("test").child("event_name").child("drinks")
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Object dataSnapshotObject = dataSnapshot.getValue(String.class);
if(dataSnapshotObject != null){
Toast.makeText(content, "Event Name: " + dataSnapshotObject.toString(), Toast.LENGTH_LONG).show();
}else
Toast.makeText(context,"null",Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
});
However, I only get a null response as the value. What could I be doing wrong?
You may remove .child("drinks") from the chain (and put it in later, as in code below)and if you want to make the dataSnapshotObject to String anyway, then you should retrieve it in a String.
Something like this:
String value = dataSnapshot.child("drinks").getValue(String.class);
Also check if your databaseReference looks something like this or not.
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
You can use addListenerForSingleValueEvent to get the value
Code sample:
FirebaseDatabase.getInstance().getReference().child("test").child("event_name").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
HashMap hashUser = (HashMap) dataSnapshot.getValue();
if (hashUser != null) {
String Drinks = hashUser.get("drinks").toString();
//Toast.makeText(this, Drinks , Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Not able to get the data from Firebase database - it returns a null value

I am trying to retrieve the data from Firebase:
DatabaseReference customerRef = FirebaseDatabase.getInstance().getReference("Drivers").child(driverId).child("customerRideId");
Log.d("TAG_SiX",customerRef.toString());
customerRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// retriveCustomerID(dataSnapshot);
Log.d("TAG_eight",dataSnapshot.toString());
Map<String,String> map =
(Map<String,String>)dataSnapshot.getValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here is the logcat value
D/TAg_five: DataSnapshot { key = customerRideId, value = null }
05
Here is the Firebase data structure, I want the value of customerRideId which in logcat shows null and the customerRideId is in the DriverID.
Drivers
PyltxOLXcWfZf6itgJEMWC4ylDu2
driverEmail: "nishant#gmail.com"
driverName: "Nishant"
customerRideId: "Sqpb6RFNhMOSiXeCrYj83aeeG7r2"
I want to retrieve the value of customerRideId but in logcat it shows null value please help me out in this.
here is the database screenshot
DataBase Screen shot here
make sure you have added appropriate dependencies in gradle and there is some data in firebase DB
If all those things are good, try:
private FirebaseDatabase database;
In your method:
database=FirebaseDatabase.getInstance();
DatabaseReference customerRef = database.getReference("Drivers/"+driverId+"/customerRideId");
Try this code ..
DatabaseReference customerRef = FirebaseDatabase.getInstance().getReference();
Query query1=customerRef.child("Drivers").child(customerRef.getKey()).child("customerRideId");
Log.d("TAG_SiX", customerRef.toString());
query1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// retriveCustomerID(dataSnapshot);
Log.d("TAG_eight", dataSnapshot.toString());
Map<String, String> map =
(Map<String, String>) dataSnapshot.getValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To get the value of your customerRideId property, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference driverIdRef = rootRef.child("Drivers");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String customerRideId = dataSnapshot.child("customerRideId").getValue(String.class);
Log.d("TAG", customerRideId);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
driverIdRef.addListenerForSingleValueEvent(valueEventListener);
The output will be: Sqpb6RFNhMOSiXeCrYj83aeeG7r2.

Android + Firebase: retrieve multiple values and get the sum

Hello, I am new to Android development, so I'm hoping for your understanding. I would like to ask how I can retrieve all data under 'values' and get the sum. As you can see, the 'keys' are random-generated keys, which were sent from an Arduino device to Firebase, but the values being sent to Firebase are correct. I want to get the sum and display it on an Android app in a single TextView. I am using Android Studio as IDE for my Android app.
I've tried other snippets from Stack Overflow as well, but it's too confusing for my level of knowledge in Android and I can't make it work. Thank you.
Try like this, may be this will help to achieve your task.
DatabaseReference ref=FirebaseDatabase.getInstance().getReference();
ref.child("data/values").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int toalSum=0;
if (dataSnapshot.getValue() != null) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
//depending upon what datatype youre using caste to it.
totalSum = totalSum+(int)snapshot.getValue();
}
Log.d("LOG","Toatal sum-"+totalSum)
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Try this dataSnapshot.getChildrenCount() will return size
DatabaseReference dbref=FirebaseDatabase.getInstance().getReference();
dbref.child("url/values")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int size = dataSnapshot.getChildrenCount(); //Here u can see the count
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To count those values, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference valuesRef = rootRef.child("data").child("values");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int sum = o;
for(DataSnapshot ds : dataSnapshot.getChildren()) {
int value = ds.getValue(Integer.class);
sum = sum + value;
}
Log.d("TAG", sum);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
valuesRef.addListenerForSingleValueEvent(eventListener);
Your outout will be:
1780
try this basic split string.
database.geteDatabase().getReference().child("data").child("values")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//dataSnapshot.getValue().toString() = {a=1,b=2,c=3}
String[] value = dataSnapshot.getValue().toString().split("[{,}]");
String[] getA= value[1].split("="); //value[1]='a=1'
String[] getB= value[2].split("="); //value[2]='b=2'
String[] getC= value[3].split("="); //value[3]='c=3'
//what you want to do here.
}
#Override
public void onCancelled(DatabaseError databaseError) { }
});
this can use for other get basic multi value from firebase database.

Android Studio Firebase "No Such instance field" error

I am using Firebase for my Android app. In the code below,
DatabaseReference rootReference = FirebaseDatabase.getInstance().getReference();
matchReference = rootReference.child("tournaments");
userReference = rootReference.child("Users").child(deviceID);
userReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
if(snapshot.child(matchList.get(position).getId()).exists()) {
//If the user has Starred this game
isStarred = true;
} else { isStarred = false; }
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I get a "No Such instance field" error in the userReference field. When I debug it, it gives me the correct database path, but it does not enters the addValueEventListener function.
My database looks like
and another child called "starredGames" will be added in my code.
Why is it giving me the error?
The correct way of getting the value of your deviceID is:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference deviceIDRef = rootRef.child("Users").child("6610609cfc2c7945");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String deviceID = dataSnapshot.child("deviceID").getValue(String.class);
Log.d("TAG", deviceID);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
deviceIDRef.addListenerForSingleValueEvent(eventListener);

firebase get least time taken returning null value

Hey I am trying to find the least time taken by a user by the following code but for some reason it says that the value of timeTaken is null.
When I logged in it shows the incorrect user's time taken so what could be the probable solution.
private void leastTimeTaken() {
final DatabaseReference databaseReference1 = firebaseUrl.child("users");
final Query query = databaseReference1.orderByChild("timeTaken").limitToFirst(1);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userAnswerSnapshot : dataSnapshot.getChildren()) {
if (userAnswerSnapshot.child("questions").child(imagename).hasChild("timeTaken")) {
long a = userAnswerSnapshot.child("questions").child(imagename).child("timeTaken").getValue(Long.class);
DatabaseReference userPuzzleDetails = FirebaseDatabase.getInstance().getReference().child("users").child(uid).child("questions").child(imagename);
userPuzzleDetails.child("leastTime").setValue(a);
}
query.removeEventListener(this);
databaseReference1.removeEventListener(this);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Categories

Resources