I am using firebase in android to save the user information and retrieving it.
I am getting the value from firebase database but its not casting to my POJO class
UserInformation.java
public class UserInformation {
private String phoneNo;
private String address;
public UserInformation() {
}
public UserInformation(String address, String phoneNo) {
this.phoneNo = phoneNo;
this.address = address;
}
public String getPhoneNo() {
return phoneNo;
}
public String getAddress() {
return address;
}
}
ValueEventListener
public ValueEventListener displayUserData() {
return new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
UserInformation userInformation =
dataSnapshot.getValue(UserInformation.class);
mEtAddress.setText(userInformation.getAddress());
mEtPhoneNo.setText(userInformation.getPhoneNo());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
}
The data snapshot is not casting to UserInformation.class. I am getting all null values in it.
You seem to be attaching your listener one level above the UserInformation node in the JSON tree. In that case the result contains a snapshot with a list of snapshots. Even if there is only one snapshot, your code needs to handle the fact that it's a list.
public ValueEventListener displayUserData() {
return new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
UserInformation userInformation =
userSnapshot.getValue(UserInformation.class);
mEtAddress.setText(userInformation.getAddress());
mEtPhoneNo.setText(userInformation.getPhoneNo());
}
}
Related
i am retrieving data from child from firebase database, the first child after the reference is "cars" which i reach with mRoot
then i use iterative to reach every child in "cars"
then i get the data into car class
at first i created the class with string values then it said you can't convert long values to string
then i turned it to long and it said you cannot convert string values to long
com.google.firebase.database.DatabaseException: Failed to convert value of type java.lang.Long to String
at com.google.android.gms.internal.firebase_database.zzkt.zzb(Unknown Source)
at com.google.android.gms.internal.firebase_database.zzkt.zza(Unknown Source)
at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
at com.example.ahmed.pointoflife.LogIn$1$1.onDataChange(LogIn.java:55)
when changing
com.google.firebase.database.DatabaseException: Failed to convert a value of type java.lang.String to long
at com.google.android.gms.internal.firebase_database.zzkt.zzb(Unknown Source)
at com.google.android.gms.internal.firebase_database.zzkt.zza(Unknown Source)
at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
at com.example.ahmed.pointoflife.LogIn$1$1.onDataChange(LogIn.java:55)
mRoot.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
Car car = new Car();
car.setHospital(childSnapshot.child("hospital").getValue(Long.class));
car.setId(childSnapshot.child("id").getValue(Long.class));
car.setPassword(childSnapshot.child("password").getValue(Long.class));
h.put(car.getId().toString(),car);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
package com.example.ahmed.pointoflife;
import com.google.firebase.database.PropertyName;
public class Car {
private Long hospital,id,password;
public Car(Long hospital,Long id,Long passowrd)
{
this.hospital = hospital;
this.id = id;
this.password = passowrd;
}
Car(){
}
#PropertyName("hospital")
public Long getHospital() {
return hospital;
}
public void setHospital(Long hospital) {
this.hospital = hospital;
}
#PropertyName("id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#PropertyName("password")
public Long getPassword() {
return password;
}
public void setPassword(Long password) {
this.password = password;
}
}
firebase tree
https://drive.google.com/file/d/17xYkrFwZqscCdrzvfkStr6cC-VYaQHI1/view?usp=sharing
how can i take these values correctly from firebase without troubles
Assuming that the mRoot points to the Firebase root, to solve this, please change the following line of code:
mRoot.addValueEventListener(*/ ... */);
to
mRoot.child("cars").addValueEventListener(*/ ... */);
And to get the Car object you can simply use:
Car car = childSnapshot.getValue(Car.class);
Edit: Seeing your entire database structure is more clear now. So to solve this, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference carsRef = rootRef.child("cars");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Car car = ds.getValue(Car.class);
Log.d(TAG, car.getHospital());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
carsRef.addListenerForSingleValueEvent(valueEventListener);
The output in your logcat will be: 11.
Or in a more simpler way using the Long class:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference carsRef = rootRef.child("cars");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Long hospital = ds.child("hospital").getValue(Long.class);
Log.d(TAG, hospital);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
carsRef.addListenerForSingleValueEvent(valueEventListener);
The output will be the same.
There's also no need to use #PropertyName because all your fields in the class match the fileds in your database.
I have been struggling with this issue for about three days. Or may be I am not understanding the who concept of addValueEventListener(). I have a POJO class.
public class InstantMessage {
private String UID;
private String email;
private String password;
private String type;
public InstantMessage() {
}
public InstantMessage(String newUID, String newEmail, String newPassword, String newType) {
UID = newUID;
email = newEmail;
password = newPassword;
type = newType;
}
public void setUID(String newUID) {
UID = UID;
}
public void setEmail(String newEmail) {
email = newEmail;
}
public void setPassword(String newPassword) {
password = newPassword;
}
public void setType(String newType) {
type = newType;
}
public String getUID() {
return UID;
}
public String getEmail()
{
return email;
}
public String getPassword()
{
return password;
}
public String getType()
{
return type;
}
}
What I am actually trying to achieve is to fetch "type" node from Firebase database. My database reference is:
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
I have tried to loop through the Datasnapshot object still no luck.
Here's what I am trying to do.
private void showData(){
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
InstantMessage iM1 = dataSnapshot.getValue(InstantMessage.class);
//System.out.println("The type is:" + iM1.getType());
sampleUser.add(iM1);
studentAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
As you can see in the logs that Datasnapshot is getting an object I am looking for but values are null.
I am so sorry if it's just a novice question but I am trying hard to learn it. Any help would be greatly appreciated.
You're getting a list of all users (from /Users), and then try to map the entire result to a single InstantMessage. That won't work, since the properties in InstantMessage don't exist straight in /Users, they are one level deeper in your JSON.
To solve this problem, you'll need to loop over the child nodes of your snapshot to get at the individual messages:
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot messageSnapshot: dataSnapshot.getChildren()) {
InstantMessage iM1 = messageSnapshot.getValue(InstantMessage.class);
sampleUser.add(iM1);
}
studentAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
so i want to create a refferal code system,using firebase realtime database,but i found a difficult,how i can get all the value in key refferal?
i already have the code,but its just give me the value from my uid,
Show below:-
Query query = mDatabase.child(uid).orderByChild("refferal_status");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot movieSnapshot : dataSnapshot.getChildren()) {
UserModel movie = dataSnapshot.getValue(UserModel.class);
if (movie.getRefferal_status().equals("akmKA")) {
Toast.makeText(SpinActivity.this, movie.getRefferal_status(), Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Class Model
String email;
String point;
String checkin;
String limitation;
String refferal_status;
public UserModel(){
}
public UserModel(String email,String point,String checkin,String limitation,String refferal_status){
this.email = email;
this.point = point;
this.checkin = checkin;
this.limitation = limitation;
this.refferal_status = refferal_status;
}
//setter getter here
}
so this is my database
Image
Try this !
Note:- equals expect String object .
if ("akmKA".equals(movie.getRefferal_status())) {
Toast.makeText(SpinActivity.this, movie.getRefferal_status(), Toast.LENGTH_SHORT).show();
}
Final code
Query query = mDatabase.child(uid).orderByChild("refferal_status");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot movieSnapshot : dataSnapshot.getChildren()) {
UserModel movie = dataSnapshot.getValue(UserModel.class);
if ("akmKA".equals(movie.getRefferal_status())) {
Toast.makeText(SpinActivity.this, movie.getRefferal_status(), Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I am newbie in Firebase. I am trying to fetch data from firebase to object of the related class. The datasnapshot gets the value from Firebase, but the same values are not getting assigned to the object.
Below is my Firebase Structure:
Here is what getting me the problem:
myRef =database.getReference();
myRef.child("Tables").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded( DataSnapshot dataSnapshot, String s) {
Log.v("DS",dataSnapshot.getValue().toString());
Tables values=dataSnapshot.getValue(Tables.class);
Log.v("isAl", values.toString());
int Capacity=values.getCapacity();
String Customer=values.getCustomer();
boolean IsAllocated= values.isAllocated();
Log.v("isAl", String.valueOf(values.isAllocated())+"\t"+Customer+"\t"+Capacity);
String key = dataSnapshot.getKey();
oldKey=key;
mKeys.add(key);
Tables table=new Tables(Capacity,Customer,IsAllocated);
});
}
My Tables Class is as follows:
public class Tables {
private int Capacity;
private String Customer;
private boolean IsAllocated;
public Tables(int capacity, String customer, boolean isAllocated) {
Capacity = capacity;
Customer = customer;
IsAllocated = isAllocated;
}
public Tables() {
}
public int getCapacity() {
return Capacity;
}
public void setCapacity(int capacity) {
Capacity = capacity;
}
public String getCustomer() {
return Customer;
}
public void setCustomer(String customer) {
Customer = customer;
}
public boolean isAllocated() {
return IsAllocated;
}
public void setAllocated(boolean allocated) {
IsAllocated = allocated;
}
}
Here is my BindViewHolder of Adapter Class:
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
list=Tlist.get(position);
Log.v("vlist", String.valueOf(Tlist.get(position)));
holder.tabletext.setText("Table");
holder.status.setText(String.valueOf(list.isAllocated()));
}
In values object, I am getting null values. Any help will be appreciated. Thank you in advance.
Change your class variable it uses a case-sensitive you are using small char and your Firebase DB contains capital
change your class to:
public class Tables {
int Capacity;
String Customer;
Boolean IsAllocated;
And use ValueEventListener to get all the records in single bunch
myRef.child("Tables").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Tables values=dataSnapshot.getValue(Tables.class);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Edit 1: you can get value using map try below code
myRef.child("Tables").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Map<String,String> map=(Map<String,String>)postSnapshot.getValue();
String Customer=map.get("Customer");
String IsAllocated= map.get("IsAllocated");
String Capacity= map.get("Capacity");
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here is how I intend my code to work. I first make sure that a unique placeID VALUE exists in my database (as seen in the picture), and set it to the query object. If the dataSnapshot of that VALUE exists, I want to retrieve the corresponding businessID using
businessID = resInfo_P.getBusinessID();
However it returns a null object reference.
Question: How do I retrieve the businessID VALUE without returning a null?
Code:
ref2 = FirebaseDatabase.getInstance().getReference();
mDatabase = FirebaseDatabase.getInstance().getReference();
Query query = ref2.child("place_id").orderByChild("placeID").equalTo(resID);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
RestaurantInformation resInfo_P = dataSnapshot
.child("place_id")
.child(resID).getValue(RestaurantInformation.class);
businessID = resInfo_P.getBusinessID(); // null object exception
} else {
...
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Model
public class RestaurantInformation {
private String resName;
private String status;
private String businessID;
private String placeID;
public RestaurantInformation() {
}
public RestaurantInformation(String businessID, String placeID) {
this.businessID = businessID;
this.placeID = placeID;
}
public RestaurantInformation(String resName) {
this.resName = resName;
}
public String getResName() {
return resName;
}
public void setResName(String resName) {
this.resName = resName;
}
public String getBusinessID() {
return businessID;
}
public void setBusinessID(String placeID) {
this.businessID = placeID;
}
public String getPlaceID() {
return placeID;
}
public void setPlaceID(String placeID) {
this.placeID = placeID;
}
}
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
You will need to handle this list in your code by iterating over the children of the snapshot:
Query query = ref2.child("place_id").orderByChild("placeID").equalTo(resID);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
RestaurantInformation resInfo_P = childSnapshot.getValue(RestaurantInformation.class);
businessID = resInfo_P.getBusinessID();
}
} else {
...
}