Retrieve data from Firebase database in values form - android

mDatabase6 = FirebaseDatabase.getInstance().getReference().child("Region 1").child("Parameter Reading");
mCO2View = (TextView) findViewById(R.id.CO2value);
mDatabase6.addValueEventListener(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
for (com.google.firebase.database.DataSnapshot datasnap: dataSnapshot.getChildren()){
String CO2level = datasnap.child("CO2").getValue(String.class);
mCO2View.setText("CO2: " + CO2level + "ppm");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
mCO2View.setText("CO2: Error");
}
});
I try to retrieve data that will be updated every interval of time, this code is for retrieve data that store in database in string form, I would like to retrieve the CO2 in values form. Pls get a help. Thanks

Related

how to fix dataSnapshot.getValue() retrieves null?

Okay so I am trying to pull from my database the email of a single user under the userID, and it retrieves null.
The userUID is authUID.
My Database structure
When I change the line to :
String value = dataSnapshot.child("email").getKey();
it retrieves the right key so I am standing on the right position of the database as far as I understand.
myDatabaseRef.child(userUID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try{
String value = dataSnapshot.child("email").getValue(String.class);
//String value = dataSnapshot.child("email").getKey(); gets email
Log.d("TAG", "onDataChange: " + value);
}
catch (Exception ex){
Log.d("PROBLEM",ex.toString());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
The error that I get:
2019-07-30 10:42:29.566 14673-14673/com.example.h210.housecommitteemanage D/TAG: onDataChange: null
Try this, below code will fetch emails of all the users :
FirebaseDatabase.getInstance().getReference("DataUsers").child("Users").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try{
Iterable<DataSnapshot> snapshotIterable = dataSnapshot.getChildren();
for (DataSnapshot aSnapshotIterable : snapshotIterable) {
String value = aSnapshotIterable.child("email").getValue(String.class);
Log.e(Constants.TAG, "Users email : " + value);
}
}catch (Exception ex){
Log.e("PROBLEM",ex.toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

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);

Retrieving data realtime from firebase that have 2 childs for 2 apps in 1 firebase [Android]

I create 2 android apps, for the user and for admin. The user app can crud the "pelanggaran", the admin app can see all the pelanggaran realtime.
Here, I am stuck in retrieving the data in real time for the admin app. Here's the database hierarchy.
this is the references: pelanggaran and user
each user has pelanggaran. so, the first child of pelanggaran is userID, then the pelanggaranID, then the values
I tried googling, I got it, but it is not real-time. Here's my code
private void refreshList(){
databaseUser = FirebaseDatabase.getInstance().getReference("User");
pelanggaranList = new ArrayList<>();
databaseUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
pelanggaranList.clear();
long numberUsers = dataSnapshot.getChildrenCount();
Log.w("total user", "" + numberUsers);
for (DataSnapshot dsUser : dataSnapshot.getChildren()){
User user = dsUser.getValue(User.class);
final String userId = user.getUserId();
Log.w("id user", userId);
databasePelanggaran = FirebaseDatabase.getInstance().getReference("Pelanggaran").child(userId);
databasePelanggaran.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot1) {
for (DataSnapshot dsPelanggaran : dataSnapshot1.getChildren()){
Pelanggaran pelanggaran = dsPelanggaran.getValue(Pelanggaran.class);
Log.w("id pelanggaran", userId + " : " + pelanggaran.getIdPelanggaran());
pelanggaranList.add(pelanggaran);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
PelanggaranAdapter pelanggaranAdapter = new PelanggaranAdapter(MainActivity.this, pelanggaranList);
recyclerView.setAdapter(pelanggaranAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
It can take all the values from each user but it is not real time. And sometimes the data doesn't appears. What should I do to make it realtime?

firebase - get single object from list as snapshot

So I have a list of objects stored in firebase and want to query for just one object using child equal to method but I am getting a map with single key value instead.
Code below showing what I want to achieve instead of dealing with hashmaps.
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference coutryRef = database.getReference(FireContract.PATH_COUNTRY);
Query countryQuery = coutryRef.orderByChild(FireContract.CHILD_NAME)
.equalTo(TestUtilities.TEST_COUNTRY_ALGERIA).limitToFirst(1);
countryQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Country country = dataSnapshot.getValue(Country.class);
assertEquals(TestUtilities.TEST_COUNTRY_ALGERIA, country.getName());
//get country key
String coutryKey = dataSnapshot.getKey();
}
#Override
public void onCancelled(DatabaseError databaseError) {
fail("Failed to get country: " + databaseError.getMessage());
}
});
When you fire a query, you will always get a list of results. Even when there is only a single item matching the query, the result will be a list of one item.
To handle the list, you can either use a ChildEvenListener or you can loop over the children in your ValueEventListener:
countryQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot countrySnapshot: dataSnapshot.getChildren()) {
Country country = countrySnapshot.getValue(Country.class);
assertEquals(TestUtilities.TEST_COUNTRY_ALGERIA, country.getName());
//get country key
String countryKey = countrySnapshot.getKey();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
fail("Failed to get country: " + databaseError.getMessage());
}
});

How to fetch all data after adding new data in firebase database

This is my code for adding person object in firebase.
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Person");
buttonSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String name = editTextName.getText().toString().trim();
String address = editTextAddress.getText().toString().trim();
//Creating Person object
Person person = new Person();
person.setName(name);
person.setAddress(address);
new Firebase(Config.FIREBASE_URL).child("Person").push().setValue(person);
}
});
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
//Getting the data from snapshot
Person person = postSnapshot.getValue(Person.class);
//Adding it to a string
String string = "Name: " + person.getName() + "\nAddress: " + person.getAddress() + "\n\n";
//Displaying it on textview
textViewPersons.setText(string);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getMessage());
}
});
Adding data is working fine and every add creating a new key for person.
But addValueEventListener is showing me only last added entry. I want all the entries data.
Can anyone help me on this?
Every time anything changes in the Person node, you get notified through onDataChange(). In there you loop over the people and then for each call:
textViewPersons.setText(string);
So you're constantly replacing the contents of the text view with the information from each person. After each loop it will end up showing just the information for the last user. You can easily see that the code loops through all people by adding:
System.out.println(string);
With this you'll see each person in logcat, but only the last person in the text view.
One solution is to either use a ListView or RecyclerView, both of which handle lists of items. Another (quicker to implement) way to show all users it to append the strings in the text view:
textViewPersons.setText(textViewPersons.getText()+string+"\n");
Try this if it helps:
String dataviewer=new String();
Firebase firebase=new Firebase(Config.FIREBASE_URL);
buttonSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String name = editTextName.getText().toString().trim();
String address = editTextAddress.getText().toString().trim();
//Creating Person object
Person person = new Person();
person.setName(name);
person.setAddress(address);
new Firebase(Config.FIREBASE_URL).child("Person").push().setValue(person);
}
});
firebase.child("Person").addChildEventListener(new ChildEventListener() {
// Retrieve values as they are added to Firebase
#Override
public void onChildAdded(DataSnapshot snapshot, String previousChildKey) {
Map<String,Object> vals=(Map<String,Object>)snapshot.getValue();
String name_person=String.valueOf(vals.get("name"));
String address_person=String.valueOf(vals.get("address"));
dataviewer+="Name: " + name_person + "\nAddress: " + address_person + "\n\n";
}
#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(FirebaseError firebaseError) {
}
});

Categories

Resources