How to get all children firebase realtime database? - android

My insert() function:
public void insert(RSSModel rssModel, String TABLE_NAME) {
database.getReference()
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(TABLE_NAME)
.child(rssModel.getTitle())
.setValue(rssModel);
Log.d("alo " + rssModel.getTitle(), "alo");
}
I want to get all RSSModel from TABLE_NAME but it's always return null
public List<RSSModel> getAll(String TABLE_NAME) {
List<RSSModel> rssModelList = new ArrayList<>();
DatabaseReference databaseReference = database.getReference(TABLE_NAME);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot: snapshot.getChildren()) {
Log.d("alo " + dataSnapshot.getValue(), "alo");
rssModelList.add(dataSnapshot.getValue(RSSModel.class));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
return rssModelList;
}
Hope that you can help me with this. Thank in advance!

You're writing to a structure:
/$uid/TABLE_NAME/rssTitle
And then you're reading from: database.getReference(TABLE_NAME)
There is no node /TABLE_NAME, so this read will indeed lead to a non-existing snapshot.
If you want to read the data for a specific user, you will need to specify their UID similar to how you do when writing.
If you want to read the data for all users, you'll need to read from the root (database.getReference()) and then loop over snapshot.getChildren() for the user, and then read the TABLE_NAME (dataSnapshot.child(TABLE_NAME)).

Related

Firebase getting data outside of onDataChange addListenerForSingleValueEvent

Hello everyone i am new on android programming. i have a problem about passind data out of ondatachange method.
as you can see below i have 2 queries get data from firebase query1 gets incomes and query gets data outcomes.
so my problem is total incomes (toplamgelir) and total outcomes (toplamgider) transfer to outside of these queries.
when i want to make result from (totalincomes -minus- totaloutcomes = result)
it doesnt show anything. how can i do that ? i will be appreciate if you show me the way
thank you in advance for your helps.
double toplamgelir, toplamgider;
Query query1 = myRef.orderByChild("gelirZaman")
.startAt(getStartOfDay(today).getTime())
.endAt(getEndOfDay(today).getTime());
query1.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot d : snapshot.getChildren()) {
Gelirler gelirler = d.getValue(Gelirler.class);
gelirler.setGelirid(d.getKey());
toplamgelir = +gelirler.getGelirTutar();
}
TVbugungeliristoc.setText(String.valueOf(toplamgelir) + " TL");
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Query query2 = myRef2.orderByChild("giderZaman").startAt(getStartOfDay(today).getTime()).endAt(getEndOfDay(today).getTime());
query2.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot d : snapshot.getChildren()) {
Giderler giderler = d.getValue(Giderler.class);
giderler.setGiderid(d.getKey());
toplamgider = +giderler.getGiderTutar();
}
TVbugungideristoc.setText(String.valueOf(toplamgider) + " TL");
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
double result = (toplamgelir-toplamgider);
//textview below shows income-outcome = acquired surplus
TVbugunKarZararistoc.setText(String.valueOf(result));
The problem is not so much where you access the data, but when you access it. By the time your double result = (toplamgelir-toplamgider) runs, the onDataChange methods haven't run yet. If you add some logging, or run in a debugger, you can most easily see that.
Instead of reexplaining why this is, I recommend reading getContactsFromFirebase() method return an empty list and Setting Singleton property value in Firebase Listener.
The tl;dr is: any code that needs data from the database, needs to be inside onDataChange or be called from there.
The simplest way for you to do that with your code, is to move the second listener into the onDataChange for the first one, and then do the final sum in the inner onDataChange:
query1.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot d : snapshot.getChildren()) {
Gelirler gelirler = d.getValue(Gelirler.class);
gelirler.setGelirid(d.getKey());
toplamgelir = +gelirler.getGelirTutar();
}
TVbugungeliristoc.setText(String.valueOf(toplamgelir) + " TL");
Query query2 = myRef2.orderByChild("giderZaman").startAt(getStartOfDay(today).getTime()).endAt(getEndOfDay(today).getTime());
query2.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot d : snapshot.getChildren()) {
Giderler giderler = d.getValue(Giderler.class);
giderler.setGiderid(d.getKey());
toplamgider = +giderler.getGiderTutar();
}
TVbugungideristoc.setText(String.valueOf(toplamgider) + " TL");
double result = (toplamgelir-toplamgider);
TVbugunKarZararistoc.setText(String.valueOf(result));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});
A new alternative is to use the new get() method, instead of addListenerForSingleValueEvent. That returns a Task object, so you can then use Tasks.whenAll(...) to wait for all of them to be done.

How to get parent of parent node in firebase realtime database in android?

My firebase realtime database structure is given below.
I am having that phonenumber field value. I need to get that parent of parent node.
Tryed this query to return immediate parent. But unable to get that itself. Here roomId is "9444XXXXXX".
mFireBaseDatabaseNest = mFireBaseInstance.getReference(Constants.DATABASE_NEST);
mFireBaseDatabaseNest.orderByChild("phonenumber").equalTo(roomId).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String key = dataSnapshot.getChildren().iterator().next().getKey();
Log.v(TAG, "found: " + key);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Need help to change this query.

Retrieving data from particular nodes firebase Database

I am developing an android application and now I am stuck in retrieving data from particular nodes like I want to retrieve only one value from each nodes. The database structure shows below.
How can I retrieve the second unique id that created by Firebase database?
First create a POJO class to get the values you want, it should be writen the same way as you have them in Firebase.
public class AppointmentsPojo {
private String appointmentStuts;
public AppointmentsPojo(){
}
public String getAppointmentStuts() {
return appointmentStuts;
}
public void setAppointmentStuts(String appointmentStuts) {
this.appointmentStuts = appointmentStuts;
}
}
Then just loop inside Appointments to get each appointmentStuts
mDatabase.child("Appointments").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Looping inside Appointments to get each appointmentsStuts
for(DataSnapshot snapshot: dataSnapshot.getChildren()){
AppointmentsPojo ap = snapshot.getValue(AppointmentsPojo.class);
//Getting each appointmentStuts
String appointmentStuts = ap.getAppointmentStuts();
//To get each father of those appointments
String key = snapshot.getKey();
Log.e("Data: " , "" + appointmentStuts );
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
Where mDatabase is
DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference();
To get the value of appointmentStuts only from the first object, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("Appointments").child(PostKey).limitToFirst(1);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String appointmentStuts = ds.child("appointmentStuts").getValue(String.class);
Log.d(TAG, appointmentStuts);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
query.addListenerForSingleValueEvent(valueEventListener);

how to get the pushed key using its child in android firebase

I want to get the pushed key by the help of its child value
Say you have the agency name, then you can create a Firebase Database query to find the matching child nodes with that agency name:
DatabaseReference ref = FirebaseDatabase.getInstance();
Query query = ref.orderByChild("agencyname").equalTo("Babaji");
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey()+" "+ dataSnapshot.getChild("agencyname").getValue());
}
...
The onChildAdded method above will be called for every node with agencyname equal to Babaji.
I recommend spending some more time in the Firebase documentation, specifically the sections on dealing with lists of data and on querying.
You can use this also
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
Query query = mDatabase.child("suppliersdata");
query.orderByChild("agencyname").equalTo("Babaji").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
Log.i("db", "onDataChange: Key : " + childSnapshot.getKey());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // never ignore errors
}
});

Get last node in Firebase database Android

I want to get item in the last node added in firebase database from my Android. You can see on the image below i'm not sure how to get the specific node, because unique key is created by Firebase. How to reference to auto-created node and child inside? Thanks a lot
The last node
Try this:
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
Query lastQuery = databaseReference.child("mp").orderByKey().limitToLast(1);
lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String message = dataSnapshot.child("message").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Handle possible errors.
}
});
Hope this helps!
This might work:
DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("mp");
Query query = db.orderByKey().limitToLast(1);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
Log.d("User key", child.getKey());
Log.d("User val", child.child("message").getValue().toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// TODO: Handle errors.
}
});
I prefer to write and retrieve data through objects.
MyObject is POJO.
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
MyObject myObject = data.getValue(MyObject.class);
Log.i(TAG, data.getKey() + " = " + myObject.toString());
}
}
console.log('last messages', messages[messages.length-1]);

Categories

Resources