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

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

Related

Populating Recycler View From Nested Queries in Firebase

I am trying to populate a recycler view using nested queries. The first query goes to groups_list node and takes data in the node and the unique key. Then it goes to groups node with the key and gets data under that key. The result of both the queries needs to be updated in recycler view.
In short, the first query gets some data and a key, the key is used to make the second query. The result from both these queries need to be updated in the recycler view. I am using a model class and recycler view adapter for this.
But I am getting an error below.
My Fragment is as follows:
// Firebase
fbDatabaseRootNode = FirebaseDatabase.getInstance().getReference();
fbDatabaseRefGroupList = fbDatabaseRootNode.child("groups_list").child(current_user_id);
fbDatabaseRefGroups = fbDatabaseRootNode.child("groups");
fbDatabaseRefGroupList.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// Array to Get Group List
lGroupsList = new ArrayList<>();
if (dataSnapshot.exists()) {
// Clear Array to Get Group List
lGroupsList.clear();
for (DataSnapshot glSnapshot : dataSnapshot.getChildren()) {
// Use The Model To Format Array List and Pass It Into It
GroupsListModel g = glSnapshot.getValue(GroupsListModel.class);
// Array to Get Group List
lGroupsList.add(g);
String groupID = String.valueOf(glSnapshot.getKey());
fbDatabaseRefGroups.child(groupID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot gSnapshot : dataSnapshot.getChildren()) {
// Use The Model To Format Array List and Pass It Into It
GroupsListModel g = gSnapshot.getValue(GroupsListModel.class);
// Array to Get Group List
lGroupsList.add(g);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
aGroupList = new GroupsListAdapter(getContext(), lGroupsList);
rvGroupList.setAdapter(aGroupList);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
And My Firebase Database Structure Looks Like
"groups" : {
"-LaPfENd0G4pHlejrcd6" : {
"group_creation_date" : 1553078221782,
"group_logo" : "0",
"group_member_count" : "0",
"group_name" : "dog lovers",
"group_tagline" : "we love dogs..."
},
"-LaPhG0YHnF3FG0Czxom" : {
"group_creation_date" : 1553078751686,
"group_logo" : "0",
"group_member_count" : "0",
"group_name" : "hi",
"group_tagline" : "hello"
}
},
"groups_list" : {
"F81wvGx9a7fXRrfVPQMhQtkM0wv2" : {
"-LaPfENd0G4pHlejrcd6" : {
"block_status" : "0",
"hide_status" : "0",
"notification_status" : "0",
"pin_sequence" : "0",
"report_status" : "0"
},
"-LaPhG0YHnF3FG0Czxom" : {
"block_status" : "0",
"hide_status" : "0",
"notification_status" : "0",
"pin_sequence" : "0",
"report_status" : "0"
}
}
},
The Model Class Is
public class GroupsListModel {
private String block_status;
private String hide_status;
private String notification_status;
private String pin_sequence;
private String report_status;
private String group_name;
private Long group_creation_date;
private String group_logo;
private String group_member_count;
private String group_tagline;
public GroupsListModel() {
}
public GroupsListModel(String block_status, String hide_status, String notification_status, String pin_sequence, String report_status, String group_name, Long group_creation_date, String group_logo, String group_member_count, String group_tagline) {
this.block_status = block_status;
this.hide_status = hide_status;
this.notification_status = notification_status;
this.pin_sequence = pin_sequence;
this.report_status = report_status;
this.group_name = group_name;
this.group_creation_date = group_creation_date;
this.group_logo = group_logo;
this.group_member_count = group_member_count;
this.group_tagline = group_tagline;
}
public String getBlock_status() {
return block_status;
}
public void setBlock_status(String block_status) {
this.block_status = block_status;
}
public String getHide_status() {
return hide_status;
}
public void setHide_status(String hide_status) {
this.hide_status = hide_status;
}
public String getNotification_status() {
return notification_status;
}
public void setNotification_status(String notification_status) {
this.notification_status = notification_status;
}
public String getPin_sequence() {
return pin_sequence;
}
public void setPin_sequence(String pin_sequence) {
this.pin_sequence = pin_sequence;
}
public String getReport_status() {
return report_status;
}
public void setReport_status(String report_status) {
this.report_status = report_status;
}
public String getGroup_name() {
return group_name;
}
public void setGroup_name(String group_name) {
this.group_name = group_name;
}
public Long getGroup_creation_date() {
return group_creation_date;
}
public void setGroup_creation_date(Long group_creation_date) {
this.group_creation_date = group_creation_date;
}
public String getGroup_logo() {
return group_logo;
}
public void setGroup_logo(String group_logo) {
this.group_logo = group_logo;
}
public String getGroup_member_count() {
return group_member_count;
}
public void setGroup_member_count(String group_member_count) {
this.group_member_count = group_member_count;
}
public String getGroup_tagline() {
return group_tagline;
}
public void setGroup_tagline(String group_tagline) {
this.group_tagline = group_tagline;
}
}
And The Error is
Can't convert object of type java.lang.Long to type com.example.myproject
The logs from datasnapshots are coming as follows... first one...
The log from second one...
Possible Solution 1 (Passing To Recycler View An Issue Otherwise Working)
This seems to be getting the data in proper sequence now just have to pass it into the Model Array List and Set The Adapter
// Get The Data
fbDatabaseRefGroupList.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if (dataSnapshot.exists()) {
final String groupID = dataSnapshot.getKey();
final String blockStatus = (String) dataSnapshot.child("block_status").getValue();
final String hideStatus = (String) dataSnapshot.child("hide_status").getValue();
final String notificationStatus = (String) dataSnapshot.child("notification_status").getValue();
final String pinSequence = (String) dataSnapshot.child("pin_sequence").getValue();
final String reportStatus = (String) dataSnapshot.child("report_status").getValue();
fbDatabaseRefGroups.child(groupID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String groupName = (String) dataSnapshot.child("group_name").getValue();
String groupTagLine = (String) dataSnapshot.child("group_name").getValue();
String groupMemberCount = (String) dataSnapshot.child("group_name").getValue();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Possible Solution 2 (List Merging Is An Issue - Otherwise Working)
// Firebase
fbDatabaseRootNode = FirebaseDatabase.getInstance().getReference();
fbDatabaseRefGroupList = fbDatabaseRootNode.child("groups_list").child(current_user_id);
fbDatabaseRefGroups = fbDatabaseRootNode.child("groups");
// Array to Get Group List
lGroupsListList = new ArrayList<>();
lGroupsList = new ArrayList<>();
lCombinedList = new ArrayList<>();
// Clear Array to Get Group List
lGroupsList.clear();
// Clear Array to Get Group List
lGroupsListList.clear();
// Clear Array to Get Group List
lCombinedList.clear();
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
// Use The Model To Format Array List and Pass It Into It
GroupsListModel g = ds.getValue(GroupsListModel.class);
// Array to Get Group List
lGroupsListList.add(g);
final String key = ds.getKey();
final String blockStatus = (String) ds.child("block_status").getValue();
DatabaseReference keyRef = fbDatabaseRootNode.child("groups").child(key);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Use The Model To Format Array List and Pass It Into It
GroupsListModel g = dataSnapshot.getValue(GroupsListModel.class);
// Array to Get Group List
lGroupsList.add(g);
String groupName = (String) dataSnapshot.child("group_name").getValue();
Log.d(TAG, "groupdetails: " + key + "--" + groupName + "--" + blockStatus);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
keyRef.addListenerForSingleValueEvent(eventListener);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
aGroupList = new GroupsListAdapter(getContext(), lGroupsList);
rvGroupList.setAdapter(aGroupList);
fbDatabaseRefGroupList.addListenerForSingleValueEvent(valueEventListener);
#Prateek Jain Your answer is giving error please see screenshot below:
Working Solution Based on Prateek Jains Inputs
public class GroupsListFragment extends Fragment {
private static final String TAG = "GroupsListFragment";
// Recycler View
private RecyclerView rvGroupList;
private GroupsListAdapter aGroupList;
private List<GroupsListModel> lGroupsListList;
private List<GroupsListModel> lGroupsList;
private List<GroupsListModel> lCombinedList;
// Firebase
private FirebaseAuth mAuth;
private DatabaseReference fbDatabaseRootNode;
private DatabaseReference fbDatabaseRefGroupList;
private DatabaseReference fbDatabaseRefGroups;
private String current_user_id;
private String groupID;
private List<String> lgroupIDs;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_groups_list, container, false);
mAuth = FirebaseAuth.getInstance();
current_user_id = mAuth.getCurrentUser().getUid();
// Init Recycler View
rvGroupList = view.findViewById(R.id.f_groups_list_groups_list);
rvGroupList.setHasFixedSize(true);
rvGroupList.setLayoutManager(new LinearLayoutManager(getActivity()));
// Firebase
fbDatabaseRootNode = FirebaseDatabase.getInstance().getReference();
fbDatabaseRefGroupList = fbDatabaseRootNode.child("groups_list").child(current_user_id);
fbDatabaseRefGroups = fbDatabaseRootNode.child("groups");
// Get The Data
fbDatabaseRefGroupList.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
// Array to Get Group List
lGroupsList = new ArrayList<>();
if (dataSnapshot.exists()) {
// Clear Array to Get Group List
lGroupsList.clear();
final String groupID = dataSnapshot.getKey();
final String blockStatus = (String) dataSnapshot.child("block_status").getValue();
final String hideStatus = (String) dataSnapshot.child("hide_status").getValue();
final String notificationStatus = (String) dataSnapshot.child("notification_status").getValue();
final String pinSequence = (String) dataSnapshot.child("pin_sequence").getValue();
final String reportStatus = (String) dataSnapshot.child("report_status").getValue();
fbDatabaseRefGroups.child(groupID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Long groupCreationDate = (Long) dataSnapshot.child("group_creation_date").getValue();
String groupLogo = (String) dataSnapshot.child("group_logo").getValue();
String groupMemberCount = (String) dataSnapshot.child("group_member_count").getValue();
String groupName = (String) dataSnapshot.child("group_name").getValue();
String groupTagLine = (String) dataSnapshot.child("group_tagline").getValue();
lGroupsList.add(new GroupsListModel(blockStatus, hideStatus, notificationStatus, pinSequence,
reportStatus, groupName, groupCreationDate, groupLogo, groupMemberCount, groupTagLine));
aGroupList.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
aGroupList = new GroupsListAdapter(getContext(), lGroupsList);
rvGroupList.setAdapter(aGroupList);
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return view;
}
}
You have to add the required data to the list which is being used by your adapter to render the views. Once that is done you must call notifyDataSetChanged, so that adapter can reload its data from the updated list.
fbDatabaseRefGroups.child(groupID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String groupName = (String) dataSnapshot.child("group_name").getValue();
String groupTagLine = (String) dataSnapshot.child("group_name").getValue();
String groupMemberCount = (String) dataSnapshot.child("group_name").getValue();
lGroupsList.add(new GroupsListModel(groupName, groupMemberCount, groupTagLine));
aGroupList.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

Firebase Datasnapshot values are not getting reflected in associated class object

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

How to get total number of child from firebase database

I have created an android app which stores the value of User class in the following manner.
{
"users" : {
"Om8VuPSCcvg7d5jsYtZvPTWpm5o1" : {
"email" : "tavinder12singh#gmail.com",
"name" : "Ajay",
"uId" : "Om8VuPSCcvg7d5jsYtZvPTWpm5o1"
},
"v1dHuFXkfJYt6fYppICQS6rjxiw2" : {
"email" : "tavinder123singh#gmail.com",
"name" : "Tavinder Singh",
"uId" : "v1dHuFXkfJYt6fYppICQS6rjxiw2"
}
}
}
My User class:
#IgnoreExtraProperties
public class User implements Parcelable {
public String uId;
public String email;
public String name;
public User() {
}
public User(String uId, String email, String name) {
this.uId = uId;
this.email = email;
this.name = name;
}
protected User(Parcel in) {
uId = in.readString();
email = in.readString();
name = in.readString();
}
public static final Creator<User> CREATOR = new Creator<User>() {
#Override
public User createFromParcel(Parcel in) {
return new User(in);
}
#Override
public User[] newArray(int size) {
return new User[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(uId);
parcel.writeString(email);
parcel.writeString(name);
}
}
I am using the following code to save the data
FirebaseUser user = mAuth.getCurrentUser();
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
database.child("users").child(user.uId).setValue(user);
But when I am trying to count the total number of child the "users" have, all I am getting is 0.
I am using the following code to get the total number of child:
userReference = FirebaseDatabase.getInstance().getReference().child("users");
userReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
num = dataSnapshot.getChildrenCount();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I want to know that how I can get the the total number of child.
Try this:
userReference = FirebaseDatabase.getInstance().getReference("users");
userReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
num = dataSnapshot.getChildrenCount();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Attempt to invoke virtual method on a null object reference .child() Firebase database

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 {
...
}

How to get the value of child node in firebase

My Firebase heirarchy
I want to get the value of all "user", but calling datasnapshot.getValue is returning null.
FirebaseDatabase.getInstance().getReference("data").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
if (dataSnapshot.getKey().equals("user"))
username = data.getValue().toString();
Toast.makeText(getApplicationContext(), "sender is " + username, Toast.LENGTH_SHORT).show();
}
}
Create a class with the database structure.
public class Data {
private String msgbody;
private String mtime;
private String uname;
private String user;
public Data() {
}
public String getMsgbody() {
return msgbody;
}
public void setMsgbody(String msgbody) {
this.msgbody = msgbody;
}
public String getMtime() {
return mtime;
}
public void setMtime(String mtime) {
this.mtime = mtime;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
}
then
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Data obj = snapshot.getValue(snapshot.getValue(Data.class);
}

Categories

Resources