Firebase How To Retrieve The Data Under A Push Key - java

I can't figure out how to retrieve my data without variable under the push key, so please help.
reference = FirebaseDatabase.getInstance().getReference("FireAlarm");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot keySnapshot : dataSnapshot.getChildren()){
dataBaru = keySnapshot.getKey();
data.setText(dataBaru);
}
}

When you are using the following line of code:
dataBaru = keySnapshot.getKey();
You are getting only those pushed keys. If you want to get the values corresponding to the keys, please use the following line of code:
dataBaru = keySnapshot.getValue(String.class);
One more thing, when looping through a DataSnapshot object using getChildren() method, you're most likely getting more than one result so you can simply set it to a TextView. So probably you should use a ListView for that or even better a RecyclerView.

Related

Read value for random generated child in firebase android

I'm trying to read all the values from my firebase database. My child values are randomly generated using
.push.getkey()
My database structure looks as below:
database structure
Example: child -MFo2XLRF34Pez_xeVAT contains a Jobs object.
How can I get all the values of randomly generated child nodes ? Since i can't pass the values to datasource.child()since I don't know the name of the child.
I just want to save all the Jobs objects into an ArrayList but I can't access them.
Make a Job class with getter and setter for the information you have at that node then to get the data you do this:
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Jobs");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot dataSnapshot:snapshot.getChildren())
{
Jobs jobs = dataSnapshot.getValue(Jobs.class);
jobsList.add(jobs);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
the problem was in my databasereference. Instead of assigning databasereference = FirebaseDatabase.getInstance().getReference("Jobs") i was using FirebaseDatabase.getInstance().getReference() which was pointing to the root node. After that dataSnapshot.getValue() worked like a charm.

How to get the random key paired with a specific value in firebase database and delete the value?

I have a simple database structure like so:
I need to remove the value earphone by using its key which is -M-4XBDqv-ve396r5EHm.
I have a button for deleting that value,
and I want to use this line of code to remove it:
mReferenceForListA.child("List A").child("Items").child(key).removeValue().
But how do I get the key for earphone?
I know I can just write
mReferenceForListA.child("List A").child("Items").child(-M-4XBDqv-ve396r5EHm).removeValue()
to delete earphone straight away,
but what if I need to delete other items in the list?
I'll need to pass a specific key into a variable called "key" to delete a specific value.
So, again, how could I get a specific key for the value that I want to delete in my current JSON structure?
This is what I tried:
Reading through related posts for days in stackoverflow and I came down to writing the following codes, but I don't think I got the hang of this thing yet and seriously need help. The following codes always delete the whole "List A" node, but in this case I just need to delete one specified value and keep the others intact in the node.
public static DatabaseReference mRootReference = FirebaseDatabase.getInstance().getReference();
public static DatabaseReference mReferenceForListA = mRootReference.child("List A");
deleteButton= findViewById(R.id.delete_button)
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mReferenceForListA.child("Items").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postsnapshot :dataSnapshot.getChildren()) {
String key = postsnapshot.getKey();
mReferenceForListA.child("Items").child(key).removeValue();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
To delete a node you need to know its complete path. If you only know a value of (a property of) the node, you can run a query to find all nodes that match that value.
Something like:
public static DatabaseReference mRootReference = FirebaseDatabase.getInstance().getReference();
public static DatabaseReference mReferenceForListA = mRootReference.child("List A");
Query query = mReferenceForListA.child("Items").orderByValue().equalTo("earphone");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
snapshot.getRef().removeValue();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
The main changes:
The above uses a query on orderByValue() on the Items child. This means Firebase searches all child nodes directly under List A/Items and returns the ones whose value matches earphones.
It also uses addListenerForSingleValueEvent, so that the delete only runs once, instead of continuously.
It uses snapshot.getRef().removeValue() for a much shorter way to remove the node.
It implements onCancelled, since you should never ignore errors.
You should iterate through the DataSnapshot as you have done, but you also need to supply it with a condition to delete the entry with a specific value.
for (DataSnapshot postsnapshot : dataSnapshot.getChildren()) {
if(postsnapshot.child(postsnapshot.getKey()).getValue(String.class)).equals("earphone"){
mReferenceForListA.child("List A").child("Items").child(postsnapshot.getkey()).removeValue();
}
}
Let me know if this works as I am trying to write this from memory.

Firebase DataSnapshot.getValue() is null

I've been looking at the other errors here in SO, in regards to mine and still can't seem to get anywhere, since I keep getting the DataSnapshot.getValue() returning null...
First I get the db-ref:
private DatabaseReference f_database = FirebaseDatabase.getInstance().getReference().child("maps_data");
Then in my OnCreate method inside my activity I've added a listener:
f_database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){ <<<< Problem is here, value is null
for(DataSnapshot snapshot:dataSnapshot.getChildren()){
double lati = 0;
// Get UsersLocationFavorites object and use the values to update the UI
UsersLocationFavorites userLocFav = snapshot.getValue(UsersLocationFavorites.class);
LatLng location = new LatLng(userLocFav.getFavoriteSpot().getLatitude(), userLocFav.getFavoriteSpot().getLongitude());
gmap.addMarker(new MarkerOptions().position(location).title("Old Marker"));
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
And looking inside my firebase database, I have the following:
I've double checked spellings ("maps_data"), I've looked an many SO-problems here, where I can't find one that fits my problem.
Can anyone see, what I've done wrong?
You're mixing up the databases provided by Firebase.
All the code you're showing is accessing Firebase Realtime Database. But the screenshot is showing data in Firestore. These are completely diffrent database products. If you want to read data out of Firestore, you should be using the Firestore SDK instead.

how to use one of the attribute value to get another attribute value in the same table in Firebase

After the user has made an appointment, the attribute(user id, date, time) is stored in the appointment table with the therapist push id as the parent node(to facilitate the retrieval of certain doctor's appointment).
Now, in the user interface, I need to get all the attribute by using the user id. Does anyone know how to do it?
Here is my database structure
Here is my own code
a=new ArrayList<AppointmentObject>();
databaseReference= FirebaseDatabase.getInstance().getReference();
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//to get current log in user id
String userid1 = FirebaseAuth.getInstance().getCurrentUser().getUid();
for(DataSnapshot dataSnapshot1: dataSnapshot.child("appointment").getChildren()) {
//if the userid stored is same as user id, it will be added to arraylist
if(dataSnapshot1.getValue(AppointmentObject.class).getUserid().equals(userid1)){
AppointmentObject thera= dataSnapshot1.getValue(AppointmentObject.class);
a.add(thera);
}
}
adapter=new MyRecyclerviewPAppointment(MainActivityPAppointment.this, a);
rv.setAdapter(adapter);
}
However, it appears this error
Your NullPointerException comes from this line
if(dataSnapshot1.getValue(AppointmentObject.class).getUserid().equals(userid1)) {}
One of these fields is null dataSnapshot1, dataSnapshot1.getValue(), dataSnapshot1.getValue().getUserid()
To ensure your code will compile reverse order of comparison:
if(userid1.equals(dataSnapshot1.getValue(AppointmentObject.class).getUserid())) {}

Perform key Specific Query in Firebase

I have structure for database in this manner
-... location
-... messages
-... id1_id2
-... id3_id4
-... id5_id6
.
.
.
How can I access a object in messages where I just know id1 which is the key.
TIA.
Change your database to this:
Messages
userid1
userid2
message: hello
then to retrieve message, do this:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Messages").child(userid1);
ref.addListenerForSingleValueEvent(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot){
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String messages=ds.child("message").getValue().toString();
}
}
});
Try this one
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("location/messages");
ref.addListenerForSingleValueEvent(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot){
for (DataSnapshot ds : dataSnapshot.getChildren()) {
if(ds.getKey().contains("bob")){
//Do something with the date
break;
}
}
}
});
Suppose your structure is like this:
You can do something like this, this will grab all nodes from messages that start with id1:
String id1 = "id1";
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("messages");
ref.orderByKey().startAt(id1).endAt(id1 + "\uf8ff").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snap : dataSnapshot.getChildren()) {
Log.d("SNAP", snap.getValue(String.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I took the idea from the javascript implementation, but it also worked in Android, I've run a test on my device/database. Note that this method will work to grab data that starts with the given id.
EDIT:
The idea of querying firebase data that contains a certain string is discussed in this official post. Also, this question as well. The bottom line is that the api doesn't support these types of queries, the approach I mentioned above is the closest you can get of implementing a "SQL LIKE" in firebase. Currently, there's no way of searching for strings that END with another string. The endAt doesn't mean the string ends with id1, but rather that the range of values I want to retrieve finishes at (id1 + "\uf8ff"), that means any string starting with id1.
Your options are either change the schema or grab all messages and search locally (the suggestions of the other two answers).

Categories