I am trying to get data using model class but in vain. There are so many questions have already been asked, but I think I am according to them, If I am missing something, Please let me know..
I am trying to get data something like this..
FirebaseHelper.firebaseDatabase().getReference().child("rooms").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot roomSnap : dataSnapshot.getChildren()) {
Room room = roomSnap.getValue(Room.class);
//no response
Log.d("createdAt", room.createdAt);
// returns all data in roomSnap
Log.d("roomSnap", roomSnap.toString());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
But its not fetching data from database.
Database:
Room Model
public class Room implements Parcelable {
private static final String TAG = "Room";
public Room() {
}
public String objectID = "";
public String createdAt = "";
public String updatedAt = "";
public String ACL = "";
public String roomNumber = "";
public String roomStatus = "";
public String roomGuestFirstName = "";
public String roomGuestLastName = "";
public String guestArrival = "";
public String guestDepature = "";
protected Room(Parcel in) {
objectID = in.readString();
createdAt = in.readString();
updatedAt = in.readString();
ACL = in.readString();
roomNumber = in.readString();
roomStatus = in.readString();
roomGuestFirstName = in.readString();
roomGuestLastName = in.readString();
guestArrival = in.readString();
guestDepature = in.readString();
}
public static final Creator<Room> CREATOR = new Creator<Room>() {
#Override
public Room createFromParcel(Parcel in) {
return new Room(in);
}
#Override
public Room[] newArray(int size) {
return new Room[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(objectID);
dest.writeString(createdAt);
dest.writeString(updatedAt);
dest.writeString(ACL);
dest.writeString(roomNumber);
dest.writeString(roomStatus);
dest.writeString(roomGuestFirstName);
dest.writeString(roomGuestLastName);
dest.writeString(guestArrival);
dest.writeString(guestDepature);
}
}
I am using same class to creating room and that's working fine, just I am getting issue in data retrieving. Even there is no error and nothing in logcat,
It was my stupidity I was trying to get data from empty String. I was expecting at least Log-cat tag name, however I have solved this, just adding data to value like this...
I think the problem with your code is that you are not setting the retrieved data to a list or recycler view(anything that you are using to show data) and if this doesn't help try setting your addvalue event listener like mine in the below code.
i hope this will help you.
DatabaseReference ref = database.getReference().child("buddy_plans");
ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Buddy buddy = dataSnapshot.getValue(Buddy.class);
listBuddy.add(buddy);
buddyAdapter.notifyDataSetChanged();
}
#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(DatabaseError databaseError) {
}
});
Related
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) {
}
});
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
}
});
In my NotificationListener of my application I am listening (and syncronizing with my SQLite) to new or changed data from Firebase.
In the first case I would like to check if the status of a loaned book has changed. Therefor I use the following code in onStartCommand:
databaseLoanedBooks.orderByChild("contactId").equalTo(firebase_uid).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
String book_id = dataSnapshot.child("bookId").getValue(String.class);
String book_status = dataSnapshot.child("bookStatus").getValue(String.class);
DatabaseHelper db = new DatabaseHelper(getApplicationContext());
List<String> all_book_ids = db.getAllBookIds();
if (all_book_ids.contains(book_id)){
// some action... check for status, if status=x output of notification
}
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Moreover I would like to check if there is a new message about the loaned book at the server. Therefor I use the following code in onStartCommand of my NotifiactionListener:
final List<String> all_book_ids = db.getAllBookIds();
// iterate through all book-ids the user has loaned at the moment (and saved in SQL)
for (int i = 0; i < all_book_ids .size(); i++) {
final String check_book_id = all_book_ids.get(i);
databaseMessage.child(check_book_id).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
ChatMessage chatMessage = dataSnapshot.getValue(ChatMessage.class);
String message_id = dataSnapshot.child("messageId").getValue(String.class);
String message_book_id = dataSnapshot.child("messageBookId").getValue(String.class);
String message_uid = dataSnapshot.child("messageUid").getValue(String.class);
String message_text = dataSnapshot.child("messageText").getValue(String.class);
String message_time = String.valueOf(chatMessage.getMessageTime());
DatabaseHelper db = new DatabaseHelper(getApplicationContext());
final List<String> all_message_ids = db.getAllMessagesIds();
final List<String> all_book_ids = db.getAllBookIds();
String new_message = getString(R.string.text_new_message);
if (all_book_ids.contains(message_book_id)) {
if (all_message_ids.contains(message_id_changed)) {
// already exists
} else {
ContentValues values_new = new ContentValues();
values_new.put(DatabaseHelper.COLUMN_CHAT_FCM_ID, message_id); values_new.put(DatabaseHelper.COLUMN_CHAT_BOOK_ID, message_book_id);
values_new.put(DatabaseHelper.COLUMN_CHAT_TEXT, message_text_changed); values_new.put(DatabaseHelper.COLUMN_CHAT_BOOK_ID, message_uid);
values_new.put(DatabaseHelper.COLUMN_CHAT_TIME, message_time);
todoUri = getContentResolver().insert(DataContentProvider.CONTENT_URI_CHATS, values_new);
HashMap<String, String> user_session = session.getUserDetails();
// UID from sharedpreferences
String noti_status = user_session.get(SessionManager.KEY_NOTIFICATION);
String user_name_chat_sql = String.valueOf(db.getContactName(message_uid));
String book_name = String.valueOf(db.getBookNameForWA(message_book_id));
user_name_chat_sql = user_name_chat_sql.replaceAll("\\p{P}", "");
book_name = book_name.replaceAll("\\p{P}", "");
showNotificationNewMessage(new_message, user_name_chat_sql, message_text, book_name);
}
}
}
#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(DatabaseError databaseError) {
}
});
}
With this code I have a data usage of approximately 2 MB per day per user. So my question is: How can I minimize my downloads and following from this my data usage? In the code to check for new messages I tried to use a for-loop to restrict the gathered data only for the books of the respective user, but this is unfortunately not the solution. How can I solve this problem?
I am implementing Firebase and DataSnapshot return null to custom java object. I have try to solved this issue by following some answer using this site also but I don't know where is exact issue in my code.
Here I am attaching my screenshot of firebase database so kindly help me resolve this issue
Below is my model.
public class ChatModel {
private String messege;
private String user;
private int intType;
public ChatModel(){}
public ChatModel(String messege, String user, int intType) {
this.messege = messege;
this.user = user;
this.intType = intType;
}
public String getMessege() {
return messege;
}
public void setMessege(String messege) {
this.messege = messege;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public int getIntType() {
return intType;
}
public void setIntType(int intType) {
this.intType = intType;
}
}
and here is my activitycode.
DatabaseReference messagesReference = reference1.child("messages/"+ UserDetails.username + "_" + UserDetails.chatWith);
Log.e("messages URL "," ==>"+messagesReference);
messagesReference .addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.e("messages Referencev "," ==>"+dataSnapshot.toString());
ChatModel map = dataSnapshot.getValue(ChatModel.class);
String message = map.getMessege();
String userName = map.getUser();
Log.e("message "," ==>"+message); // Here I am getting null value
}
#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(DatabaseError databaseError) {
}
});
and logcat show message like this.
==>DataSnapshot { key = -KslrqBPRMNKkWQO15h_, value = {message=Hi This is sakib, user=sakib} }
Your keys are mismatch that's why it's returning null value check your screenshot and your ChatModel class, remove str from your ChatModel class variables, and generate getter setter again
This might help you.
public class ChatModel {
private String messege;
private String user;
private int intType;
// TODO generate getter setter again
}
either you can get values via map as well
Map<String,String> map=(Map<String,String>)dataSnapshot.getValue();
String message = map.get("message");
String userName = map.get("user");
Log.e("message "," ==>"+message);
Try to rename your model
private String message;
public String getMessage(){ return message;}
i had the same issue and it worked after i named the properties exactly like they are named in the firebase Database.
You can try to use dataSnapshot.getChildren() in the for loop, like this:
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
ChatModel map = snapshot.getValue(ChatModel.class);
String message = map.getMessege();
String userName = map.getUser();
}
}
I use firebase to store data , but I could not get the list of data
from firabse ,Specifically I want to get arraylist of person object.
here is the class person
public class Person {
private String name;
private String username;
public Person() {
}
public Person(String name, String username) {
this.name = name;
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
and here is data structure
You can fetch the data with any of the event listeners. Here is with child event listener.
List<Person> persons = new ArrayList<>();
ChildEventListener listener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Person person = dataSnapshot.getValue(Person.class);
persons.add(person);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Person person = dataSnapshot.getValue(Person.class);
persons.remove(person);
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
FirebaseDatabase.getInstance().getReference().child("persons").addChildEventListener(listener);
Ugur B answers also correct one. Here,You can also fetch firebase data by using the ValueEventListener too...
ArrayList<String> arrayListVal = new ArrayList<String>();
fbref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
Person person = postSnapshot.getValue(Person.class);
//Adding it to a ArrayList
arrayListVal.add(person);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("Failed to fetch data: " + firebaseError.getMessage());
}
});