Value of snapshot returns null firebase - java

I am getting some image ids from firebase but it always returns null even though i am 100% sure data is there and the key names are correct here is my code and firebase database:
String storeidd = getIntent().getStringExtra("storeid");
Query query = FirebaseDatabase.getInstance().getReference().child("Member").child(storeidd).child(childDataSnapshot.getKey()).child("proImages").orderByChild("ImageID").equalTo("1597332319044_0.null");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.exists()){
System.out.println(snapshot.child("ImageID").getValue().toString()); // <- returns null
itemArrayList.add(new ClassListItems(childDataSnapshot.child("proname").getValue().toString(),snapshot.child("ImageID").getValue().toString(),childDataSnapshot.child("proprice").getValue().toString(),childDataSnapshot.child("prodesc").getValue().toString()));
myAppAdapter = new MyAppAdapter(itemArrayList, showProducts.this);
listView21.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView21.setAdapter(myAppAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Also when I print it as System.out.println(snapshot.getValue().toString());
It gives me {-MEcQEJFZCO5Cr0aJSbg={ImageID=1597332319044_0.null}}
Any ideas?

You need to iterate inside the snapshot to be able to get the data:
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.exists()){
for(DataSnapshot ds : snapshot.getChildren()){
String imageID = ds.child("ImageID").getValue(String.class);
}
}
}

Related

How can I change the value of child in Firebase database?

I want to change the value of child "toggleStatus" under Reference "BetSlip" as shown below. The already set value is "on" so I want such that when I click the button the value of "toggleStatus" is changed to "off"
BetSlipActivity.toggleCollapse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String timeStamp = betSlip.get(position).getTimeStamp();
String toggleStatus = betSlip.get(position).getToggleStatus();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("BetSlip");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds: snapshot.getChildren()) {
String timestamp = ""+ ds.child("timeStamp").getValue();
String toggleStatus = ""+ ds.child("toggleStatus").getValue();
if (timeStamp.equals(timestamp) && toggleStatus.equals("on")) {
//set value to off
}
if (timeStamp.equals(timestamp) && toggleStatus.equals("off")) {
//set value to on
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
If you've got the DataSnapshot for a path in the database, it's easy to get the DatabaseReference that you need to update it:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("BetSlip");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds: snapshot.getChildren()) {
String timestamp = ""+ ds.child("timeStamp").getValue();
String toggleStatus = ""+ ds.child("toggleStatus").getValue();
if (timeStamp.equals(timestamp) && toggleStatus.equals("on")) {
ds.child("toggleStatus").getRef().setValue("off");
}
if (timeStamp.equals(timestamp) && toggleStatus.equals("off")) {
ds.child("toggleStatus").getRef().setValue("on");
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});
Since you're updating the node based on its existing value, strictly speaking you might need to use a transaction for it.

how to get string array from firebase realtime database

databaseReference = FirebaseDatabase.getInstance().getReference("/sample");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Log.d(TAG, "onDataChange: dataSnapshot "+dataSnapshot.getValue());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I'm new to android app development and firebase as well. i m fetching data from sample node and getting DataSnapshot value like below.
{size=[Small, Large, Ex-Large], type=[Type 1, Type 2], color=[Red, Green, Blue], category=[T-Shirt, Jeans, Sweater]}
need some expect help, any suggestion will greatly appreciated.
Thanks
To retrieve values separately, you can use a code like this:
databaseReference.child("category").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (int i=0;i<3;i++) {
// category is an ArrayList you can declare above
category.add(dataSnapshot.child(String.valueOf(i)).getValue(String.class));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) { // Do something for this
}
});
Similarly you can add values of other nodes in your other ArrayLists, just by changing the value of Childs in this code.
Firebase has no native support for arrays. If you store an array, it really gets stored as an "object" with integers as the key names.
// we send this
['hello', 'world']
// Firebase stores this
{0: 'hello', 1: 'world'}
Best Practices: Arrays in Firebase
// TRY THIS
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
youNameArray = new ArrayList<>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
String data = snapshot.getValue(String.class);
youNameArray.add(data);
}
Log.v("asdf", "First data : " + youNameArray.get(0));
}
Something like this:
databaseReference = FirebaseDatabase.getInstance().getReference("/sample");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot sampleSnapshot: dataSnapshot.getChildren()) {
Log.d(TAG, "onDataChange: sampleSnapshot "+sampleSnapshot.getKey()+" = "+sampleSnapshot.getValue());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
The difference is that in my answer I loop over dataSnapshot.getChildren() to get each individual sample snapshot. The sampleSnapshot.getValue() call should return a List.
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference refence = database.getReference();
refence.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot snapshot) {
// TODO Auto-generated method stub
ArrayList array= new ArrayList<>();
for (DataSnapshot ds : snapshot.getChildren()){
String data = ds.getValue().toString();
array.add(data);
}
System.out.println(array);
}
#Override
public void onCancelled(DatabaseError error) {
// TODO Auto-generated method stub
}
});
In my case String.class does not work instead .toString method works
String data = ds.getValue().toString();

Firebase realtime database - how to get parent name based on a value of one of its keys

The structure looks like this:
users
|----username1
|----uid:value
username2
|----uid:value
I'm trying to find the best way to get the username value based of the value of it's uid,
This need to be in Java code (Android), So far I found the following code:
Query uid = reference.child("users").orderByChild("uid").equalTo(uid);
uid.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String keys=datas.getKey();
if (keys.equals(uid)) {
// uid found
} else {
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Try this code and create a model class to fetch value of Uid
DatabaseReference users= FirebaseDatabase.getInstance().getReference().child("users");
users.orderByChild("uid").equalTo(uid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot post:dataSnapshot.getChildren()){
//Use a model class to fetch user id like below
UIDDetails u=post.getValue(UIDDetails.class);
String user_id=u.getUid();
//Here all values will be equal to youy required uid if exists more than one
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Please add below code into your file:
DatabaseReference users= FirebaseDatabase.getInstance().getReference().child("users");
final Query userQuery = users.orderByChild("uid");
userQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
map.clear();
if(child.getkey().toString().equalsIgnoreCase(uid)){
//Get the node from the datasnapshot
String myParentNode = dataSnapshot.getKey();
for (DataSnapshot child: dataSnapshot.getChildren())
{
String key = child.getKey().toString();
String value = child.getValue().toString();
map.put(key,value);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
databaseError.toException();
}
});

Bypass a push id node in firebase

I am getting a null when I try to get data of the child node of a push id. My structure look like this
And this is my code for getting the message data
DatabaseReference mMessageDatabase = FirebaseDatabase.getInstance().getReference().child("private_messages");
mMessageDatabase.child(User1).child(User2).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot != null) {
// getting null in message
String message = dataSnapshot.child("message").getValue(String.class);
Log.e(TAG, "CHAT_LOG: " + message);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Is there something wrong in my code or Am I missing a code there?
EDIT:
I try using a query to test if it gives me data. heres my code
messageDatabase.orderByChild("seen").equalTo("false")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
String key = datas.getKey();
String seen = dataSnapshot.child(key).child("seen").getValue(String.class);
Log.e(TAG, "CHAT_LOG: Seen= " + seen);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Fortunately it gives me a data. THe only problem is getting the message. I used a query here and I need to give a specific value to it.
Try the following:
mMessageDatabase.child(User1).child(User2).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot != null) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String message = datas.child("message").getValue(String.class);
Log.e(TAG, "CHAT_LOG: " + message);
}
}
}
Since the snapshot is at User2 then you can loop inside the direct child which is the push id and retrieve the value of child message

I want to delete the Firebase database child, but I can't

I want to delete the Firebase database child with this follow code when I click the first item in a list in an app, but I can't. What's wrong?
Query removeCalendar = mCalendarDatabaseReference.limitToFirst(1);
removeCalendar.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String remCal = dataSnapshot.toString();
mCalendarioDatabaseReference.child(remCal).removeValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Firebase Queries return a list of possible locations where the query might be satisfied, you'd need to iterate through your dataSnapshot to access those locations. Moreover, this :
String remCal = dataSnapshot.toString();
is not going to print the String value of this snapshot. If you want to get the string value of a dataSnapshot it should be:
String remCal = dataSnapshot.getValue(String.class);
If you want to get the reference of a datasnapshot just use getRef(), you don't have to access the original reference.
Query removeCalendar = mCalendarDatabaseReference.limitToFirst(1);
removeCalendar.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
child.getRef().setValue(null); //deleting the value at this location. You can also use removeValue()
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I solve the problem with this code:
Query removerCalendario = mCalendarioDatabaseReference.limitToFirst(1);
removerCalendario.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
ds.getRef().removeValue();
}
}
You can do mCalendarioDatabaseReference.child(remCal).setValue(null);

Categories