Problem in retrieving firebase database to an android app.
Here is the image of firebase realtime database updating from from raspberry pi
error: Failed to convert value of type java.util.HashMap to String
Below is my MainActivity.java
public class MainActivity extends AppCompatActivity {
private TextView tempvalue;
private TextView humidvalue;
private FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
private DatabaseReference mRootReference = firebaseDatabase.getReference();
private DatabaseReference mChildReference = mRootReference.child("user").child("");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tempvalue = (TextView)findViewById(R.id.tempvalue);
humidvalue = (TextView)findViewById(R.id.humidvalue);
}
#Override
protected void onStart() {
super.onStart();
mChildReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String Temperature = dataSnapshot.getValue(String.class);
String Humidity = dataSnapshot.getValue(String.class);
tempvalue.setText(Temperature);
humidvalue.setText(Humidity);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}}
output error while i'm running it into my phone(usb-debugging)
*
Its because you listen to null.
your database reference is like this:
mChildReference= mRootReference.child("user").child("");
this part
.child("");
is listening to a null node. Hence your error
You must add the exact path that you are trying to read.
EDIT
okay use this as the ref:
mChildReference= mRootReference.child("user");
and listen to the values like this:
mChildReference.addValueEvent(new Value......{
onDataChange(DataSnapshot datasnapshot){
String temprature= datasnapshot.child("Temprature").getValue().toString();
String humidity= datasnapshot.child("Humidity").getValue().toString();
}
})
To solve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("user");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String humidity = ds.child("Humidity").getValue(String.class);
String temperature = ds.child("Temperature").getValue(String.class);
Log.d("TAG", humidity + " / " + temperature);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userRef.addListenerForSingleValueEvent(valueEventListener);
It will print the humidity and temperature of all objects.
If you want to display the value of a single object, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("user").child("-L6wEaOp58bSnCGUTSMs");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String humidity = dataSnapshot.child("Humidity").getValue(String.class);
String temperature = dataSnapshot.child("Temperature").getValue(String.class);
Log.d("TAG", humidity + " / " + temperature);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userRef.addListenerForSingleValueEvent(valueEventListener);
Related
how can filter the value in firebase?
if I want to filter the value in firebase
Because the country values is variable, how can I do?
Below is my code
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
Could I filter the values?
Should I
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts").child("country"); //???
=====================Update===================
now, I used this code, but I don't know why I can't get the country value in readPost function. Do I miss something?
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference country_ref = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser.getUid());
country_ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
country = snapshot.child("country").getValue().toString();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
private void readPosts(){
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading...");
progressDialog.show();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
Query query = reference.orderByChild("country").equalTo(country);
query.addListenerForSingleValueEvent(new ValueEventListener() {
I can get the country value in country = snapshot.child("country").getValue().toString();
but can't get in readPost function
Queries in Firebase are done like this:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts")
Query query = reference.orderByChild("country").equalTo("Australia");
You can then read the values matching this query with:
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
Log.d("Firebase", userSnapshot.getKey();
Log.d("Firebase", userSnapshot.child("country").getValue(String.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
})
Also see the Firebase documentation on ordering and filtering data and listening to value events for lists. If you're new to Firebase, I also strongly recommend taking the codelab for Android developers.
To get all countries of "Posts"-
private ArrayList<String> countryNameList;
private String countryName;
private TextView countryNameView;
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Posts");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
countryName = ds.child("country").getValue().toString();
countryNameList.add(countryName);
StringBuilder stringBuilder = new StringBuilder();
for (String s : countryNameList) {
stringBuilder.append(s + "\n");
}
countryNameView.setText(stringBuilder.toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w("TAG", "onCancelled", databaseError.toException());
}
});
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);
I am trying to get values from Firebase Database and set them to text view. My database has multiple child like in image. I want to get the Phone and Address values from it. How can I get them? I am new to Android and I have tried multiple answers here, but failed. Can anyone help me with this?
To get that data, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String address = ds.child("Address").getValue(String.class);
String phone = ds.child("Phone").getValue(String.class);
Log.d("TAG", address + " / " + phone);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(eventListener);
And this is the code to get the address from a single user:
String uid = firebaseAuth.getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("Users").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String address = dataSnapshot.child("Address").getValue(String.class);
Log.d("TAG", address);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userRef.addListenerForSingleValueEvent(eventListener);
I have this data structure:
The red arrows points at animal IDs, and the blue arrow points at user IDs. Every user have one or many animals.
I have tried different methods for showing only the animals that have id that is stored in the current user node.
Example: If I have UID = 48onHXIxgDP465j5WW16oo7psNm2 (the first one in "users") I want to show the data from: "dog2" and "dog3".
Now iIhave the following code that gets snapshot from the "animals" node in the database, and then gets data from every child.
myAnimalRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
list = new ArrayList<AnimalCard>();
for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){
AnimalCard value = dataSnapshot1.getValue(AnimalCard.class);
AnimalCard animal = new AnimalCard();
String name = value.getName();
int age = value.getAge();
String url = value.getUrl();
animal.setName(name);
animal.setAge(age);
animal.setUrl(url);
list.add(animal);
}
recyclerViewSetAdapter();
progressDialog.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG1, "failed to read value: " + databaseError.toException());
}
});
How can get my code to filter out every animal that does not have their ID in the user node?
The reason I want to make the user get access with an UID stored in the database is because later on I want to make it so that multiple users can get access to the same animal.
To achieve this, you need to query your database twice. Please use the following code:
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
String uid = firebaseUser.getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = usersRef.child("users").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String aid = ds.getKey();
DatabaseReference animalRef = rootRef.child("animals").child(aid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dSnapshot) {
int age = dSnapshot.child("age").getValue(Integer.class);
String name = dSnapshot.child("name").getValue(String.class);
String url = dSnapshot.child("url").getValue(String.class);
Log.d("TAG", age + " / " + name + " / " + url);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
animalRef.addListenerForSingleValueEvent(valueEventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(eventListener);
In which uid is the id of the logged-in user and aid is the id of the animal. Your output will be:
11 / dog1 / http...
12 / dog2 / http...
Hope you find this helpfull.!
Get Object in Your Model Class and Store that Object in List for Further user.!
You can get specific object as well simple using
mdatabaseRef.child("animals").orderByChild().equalTo("value")
and also you can add check on key by orderByKey()
private FirebaseAuth mAuth;
private FirebaseDatabase mdatabase;
private DatabaseReference mdatabaseRef;
mAuth = FirebaseAuth.getInstance();
mdatabase = FirebaseDatabase.getInstance();
mdatabaseRef = mdatabase.getReference();
ArrayList<User> allUserList = new ArrayList<>();
Array<Animal> allAnimalList=new ArrayList<>();
mdatabaseRef.child("animals").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
String key = childSnapshot.getKey();
Animal animal = childSnapshot.getValue(Animal.class);
allAnimalList.add(animal );
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mdatabaseRef.child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
String key = childSnapshot.getKey();
User user = childSnapshot.getValue(User .class);
allUserList.add(user);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I ended up taking Alex Mamo's answer and tweak with a litte bit.
This is the code i'am using:
uid = currentUser.getUid();
mRootRef = FirebaseDatabase.getInstance().getReference();
final DatabaseReference myUserRef = mRootRef.child("users").child(uid);
Log.d(TAG1, uid);
myUserRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
list = new ArrayList<AnimalCard>();
for(DataSnapshot ds : dataSnapshot.getChildren()){
String aid = ds.getKey();
DatabaseReference myAnimalRef = mRootRef.child("animals");
Query query = myAnimalRef.orderByKey().equalTo(aid);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds2 : dataSnapshot.getChildren()){
AnimalCard value = ds2.getValue(AnimalCard.class);
AnimalCard animal = new AnimalCard();
String name = value.getName();
int age = value.getAge();
String url = value.getUrl();
animal.setName(name);
animal.setAge(age);
animal.setUrl(url);
list.add(animal);
}
recyclerViewSetAdapter();
progressDialog.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The main difference is that i'am using a query to filter out every Animal that does not have the aID that the currentUser have.
This is my datbase tree
the below is my code to check if my database has a child with a specified number stored in num variable.
i am unable to access num variable in addListenerForSingleValueEvent
here is my code.
Thanks in advance.
mDatabase = FirebaseDatabase.getInstance().getReference();
public String nam,num;
for( contacts e : mylist)
{
num = e.getPhoneNumber();
nam = e.getName();
check(nam,num);
}
public void check(final String nam, final String num)
{
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild(num)) //this line is giving error
Toast.makeText(getActivity(),num,Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getActivity(),"some error",Toast.LENGTH_SHORT).show();
}
});
}
To solve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference numberRef = rootRef.child(num);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
Log.d("TAG", "Number exists!");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
numberRef.addListenerForSingleValueEvent(eventListener);