Firebase Datasnapshot values are not getting reflected in associated class object - android

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

Related

Getting W/ClassMapper: No setter/field for XXX found on class

I am getting this error for every child under the parent node (GID) for Games in my Firebase json tree.
So that error message is for AwayTeam, HomeTeam, AwayScore, HomeScore, etc...Its like it did NOT map anything properly!?
The firebase structure is like the following:
Games
--- GID
----- AwayTeam
----- HomeTeam
----- AwayScore
----- HomeScore
etc...
My Adapter file is like the following:
public class PoolAdapter extends RecyclerView.Adapter<PoolAdapter.PoolViewHolder> {
public PoolAdapter(Dashboard dashboardFragment, String userID) {
this.mDashboardFragment = dashboardFragment;
mPoolRef = FirebaseDatabase.getInstance().getReference();
playerInPoolRef = mPoolRef.child("PlayerInPool").child(userID).orderByValue().equalTo(true);
playerInPoolRef.addValueEventListener(new PlayersInPoolChildEventListener());
}
private class PlayersInPoolChildEventListener implements ValueEventListener {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
getPoolData(dataSnapshot);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
}
private void getPoolData(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot: dataSnapshot.getChildren()) {
String poolID = snapshot.getKey();
poolRef = mPoolRef.child("Pools").child(poolID);
poolRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
getGameData(dataSnapshot);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
});
}
}
private void getGameData(DataSnapshot dataSnapshot) {
String gameID = dataSnapshot.child("GameId").getValue().toString();
gameRef = mPoolRef.child("Games").child(gameID);
gameRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
loadPlayerDashboard(dataSnapshot);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
});
}
private void loadPlayerDashboard(DataSnapshot dataSnapshot) {
Log.d(TAG, "*** Database snapshot: " + dataSnapshot); <-- Displays the correct Firebase information
Pools pool = dataSnapshot.getValue(Pools.class);
mPools.add(pool);
Collections.sort(mPools);
}
}
My Model class object is as follows:
public class Pools implements Comparable<Pools> {
private String _poolID;
//
private String _poolName;
private String _poolPassword;
private String _gameID;
private String _awayTeam;
private String _homeTeam;
private String _gameTime;
private String _gameDate;
public Pools() { }
public Pools(String poolID, String poolName, String gameID, String awayTeamName, String homeTeamName, String gameDate, String gameTime) {
this._poolID = poolID;
this._poolName = poolName;
//
this._gameID = gameID;
this._awayTeam = awayTeamName;
this._homeTeam = homeTeamName;
this._gameDate = gameDate;
this._gameTime = gameTime;
}
public String get_poolID() {
return _poolID;
}
public void set_poolID(String _poolID) {
this._poolID = _poolID;
}
public String get_poolName() {
return _poolName;
}
public void set_poolName(String _poolName) {
this._poolName = _poolName;
}
public String get_poolPassword() {
return _poolPassword;
}
public void set_poolPassword(String _poolPassword) {
this._poolPassword = _poolPassword;
}
public String get_gameID() {
return _gameID;
}
public void set_gameID(String _gameID) {
this._gameID = _gameID;
}
public String get_awayTeam() {
return _awayTeam;
}
public void set_awayTeam(String _awayTeam) {
this._awayTeam = _awayTeam;
}
public String get_homeTeam() {
return _homeTeam;
}
public void set_homeTeam(String _homeTeam) {
this._homeTeam = _homeTeam;
}
public String get_gameTime() {
return _gameTime;
}
public void set_gameTime(String _gameTime) {
this._gameTime = _gameTime;
}
public String get_gameDate() {
return _gameDate;
}
public void set_gameDate(String _gameDate) {
this._gameDate = _gameDate;
}
}
which has all the getters and setters so I am not sure why I am getting the error!?
I know the data is there as log log statement that you see above in my Adapter displays the following:
*** Database snapshot: DataSnapshot { key = 2019020300, value = {HomeTeam=Los Angeles Rams, GSIS=57833, GameYear=2019, isPlayed=true, hBackground=hTeam/rams.png, HomeId=29, hScore=0, GameTime=6:30, AwayId=31, aBackground=aTeam/patriots.png, SportID=1, aScore=0, Qtr=Pregame, WeekId=22, GameDate=20190203, AwayTeam=New England Patriots, SeasonType=SB} }
Does anyone know how I can resolve this!?
You need to iterate over dataSnapshot.getChildren(
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
Pools pool = childSnapshot.getValue(Pools.class);
}

Can't convert object of type java.lang.String to type

I have a problem after I add another table to my firebase database. it gives me following error:
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type ...
here is my code, which works fine if I have database like this:
and code:
Main activity code:
rvOrder = (RecyclerView) findViewById(R.id.rvOrders);
rvOrder.setLayoutManager(new LinearLayoutManager(this));
databaseReference= FirebaseDatabase.getInstance().getReference();
firebaseHelper=new FirebaseHelper(databaseReference);
myAdapter=new MyAdapter(this,firebaseHelper.retrieve());
rvOrder.setAdapter(myAdapter);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
rvOrder.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Firebase helper code:
public class FirebaseHelper {
DatabaseReference databaseReference ;
Boolean saved = null;
ArrayList<Order> orders = new ArrayList<>();
public FirebaseHelper(DatabaseReference databaseReference) {
this.databaseReference = databaseReference;
}
public Boolean save(Order order) {
if (order == null) {
saved = false;
} else {
try {
databaseReference.child("Orders").push().setValue(order);
saved = true;
} catch (DatabaseException e) {
e.printStackTrace();
saved = false;
}
}
return saved;
}
private void fetchData(DataSnapshot dataSnapshot) {
orders.clear();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
System.out.println(ds.getValue(Order.class));
Order order = ds.getValue(Order.class);
orders.add(order);
}
}
public ArrayList<Order> retrieve() {
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return orders;
}
If I change my code to this (which I saw in this question link to the question ):
in Main activity:
databaseReference= FirebaseDatabase.getInstance().getReference();
to
databaseReference= FirebaseDatabase.getInstance().getReference().child("Orders");
and in firebasehelper:
for(DataSnapshot ds : dataSnapshot.getChildren()) {
System.out.println(ds.getValue(Order.class));
Order order = ds.getValue(Order.class);
orders.add(order);
}
to
System.out.println(dataSnapshot.getValue(Order.class));
Order order = dataSnapshot.getValue(Order.class);
orders.add(order);
then I am able to add another tables to database but I just get only the last item from the Orders table.
I want to add many tables with multiple items into the database and also I want to get all items from the "Orders" table.
Can anybody suggest me anything?
In your first code snippet you read from the root of the database. Since you're trying to read orders, you should read from /Orders instead:
databaseReference= FirebaseDatabase.getInstance().getReference();
firebaseHelper=new FirebaseHelper(databaseReference);
//myAdapter=new MyAdapter(this,firebaseHelper.retrieve());
//rvOrder.setAdapter(myAdapter);
databaseReference.child("Orders").addValueEventListener(new ValueEventListener() {
Now in your onDataChange you can read the orders by looping over them. Since you already do precisely that in FirebaseHelper.fetchData, you can call that method:
public void onDataChange(DataSnapshot dataSnapshot) {
firebaseHelper.fetchData(dataSnapshot);
}
Now all that is left is to wire up the data from firebaseHelper.orders to an adapter and the view:
public void onDataChange(DataSnapshot dataSnapshot) {
firebaseHelper.fetchData(dataSnapshot);
myAdapter=new MyAdapter(this,firebaseHelper.orders);
rvOrder.setAdapter(myAdapter);
}
This last step will require that you make FirebaseHelper.orders public, and probably some of the variables must be final.
I think you need to update this method accordingly:
public Boolean save(Order order) {
if (order == null) {
saved = false;
} else {
try {
databaseReference.child("Orders").push().setValue(order);
saved = true;
} catch (DatabaseException e) {
e.printStackTrace();
saved = false;
}
}
return saved;
}
Try to change:
databaseReference.child("Orders").push().setValue(order);
To:
databaseReference.child("Orders").child(order.getId).setValue(order);
Also, to retreive all Orders keep using the enhanced loop:
for(DataSnapshot ds : dataSnapshot.getChildren()) {
System.out.println(ds.getValue(Order.class));
Order order = ds.getValue(Order.class);
orders.add(order);
}

get a value with different key Firebase Realtime DB

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

Not able to retrieve value in firebase database

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

Access Firebase database specifics child item

I have two children in a Firebase database like 1) Semester I Notes and 2) Semester II Notes.
I have successfully uploaded data into these children, but when I retrieve these items, it just returns the first child's data. Code for Firebase helper here - name is the variable of our Semester I Notes or Semester II Notes
public class FireBaseHelper {
DatabaseReference db;
boolean saved;
String name;
Query myref;
ArrayList<Semester> semesters = new ArrayList<>();
public FireBaseHelper(DatabaseReference db, String n) {
this.db = db;
myref=db.orderByChild("model").equalTo(n);
name = n;
}
public boolean save(Semester s) {
if (s == null) {
saved = false;
} else {
try {
db.child(name).push().setValue(s);
myref=db.orderByChild("model").equalTo(name);
} catch (DatabaseException e) {
e.printStackTrace();
saved = false;
}
saved = true;
}
return saved;
}
public void fetchData(DataSnapshot dataSnapshot) {
Log.i("Getchildcount", String.valueOf(dataSnapshot.getChildrenCount()));
semesters.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Semester semester = ds.getValue(Semester.class);
semesters.add(semester);
}
}
public ArrayList<Semester> retrieve() {
myref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return semesters;
}
}
I call the retrieve method like this
Firebase helper = new FireBaseHelper(db, NameOfDb);
NotesAdapter adapter = new NotesAdapter(this, helper.retrieve());
//this is the list variable noteItem and I set adapter on it
notesItem.setAdapter(adapter);
Model Image of Firebase
You need to use DatabaseReference childItem = mDatabase.child("child_item_name");
Firebase Realtime database Doc

Categories

Resources