Query Firebase list with object value - android

Hi i am using DatabaseReference#push method to add object to reference.
This object has property id.
Next time i have id and i wish to get that user object from that list, how can i get that. I there any simple way to directly Query, or we need to pull all objects and compare each id with the one i require,
here is my object code
#IgnoreExtraProperties
public final class User {
private Integer id;
private String name;
private String secret;
public User() {
}
public User(Integer id, String name, String secret) {
this.id = id;
this.name = name;
this.secret = secret;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public String getSecret() {
return secret;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setSecret(String secret) {
this.secret = secret;
}
}
This is how i am adding it to firebase console mReference.push().setValue(user); , also i want to know that can we omit thos random generated id for node, becuase i will not be having that kp*** id instead i will be havind id of user object
Her is how i am try to query more code :)
public final class UserReference implements ChildEventListener {
private static final String TAG = UserReference.class.getSimpleName();
private static final List<User> userList = new ArrayList<>();
static {
userList.add(new User(1, "user1", "secret1"));
userList.add(new User(2, "user2", "secret2"));
}
private static final String USER = "users";
private final DatabaseReference mReference;
private Query mSingleUserQuery;
UserReference(FirebaseDatabase database) {
mReference = database.getReference(USER);
// mReference.addChildEventListener(this);
}
//One time use method
public void saveUser() {
for (User user : userList) {
mReference.push().setValue(user);
}
}
public void findUserById(final String id, final OnDbCompleteListener<User> userListener) {
mSingleUserQuery = mReference.orderByChild("id").equalTo(id);
mSingleUserQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Logger.info(TAG, "Key: " + dataSnapshot.getValue());
sendDataAndUnregister(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Logger.info(TAG, dataSnapshot.getKey());
sendDataAndUnregister(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Logger.info(TAG, dataSnapshot.getKey());
sendDataAndUnregister(dataSnapshot);
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
Logger.info(TAG, dataSnapshot.getKey());
sendDataAndUnregister(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
databaseError.toException().printStackTrace();
}
private void sendDataAndUnregister(DataSnapshot dataSnapshot) {
mSingleUserQuery.removeEventListener(this);
userListener.onComplete(dataSnapshot.getValue(User.class));
}
});
}
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Logger.info(TAG, "added: " + dataSnapshot.getKey());
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Logger.info(TAG, "changed: " + dataSnapshot.getKey());
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Logger.info(TAG, "removed: " + dataSnapshot.getKey());
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
Logger.info(TAG, "moved: " + dataSnapshot.getKey());
}
#Override
public void onCancelled(DatabaseError databaseError) {
Logger.info(TAG, "Error: " + databaseError.getMessage());
}
}
Database Class
public final class MySuperCoolDatabase {
private FirebaseDatabase mDatabase;
private UserReference mUserReference;
public MySuperCoolDatabase() {
mDatabase = FirebaseDatabase.getInstance();
mUserReference = new UserReference(mDatabase);
}
public UserReference getUserReference() {
return this.mUserReference;
}
}
Its call:
MySuperCoolDatabase database = new MySuperCoolDatabase();
UserReference userReference = database.getUserReference();
userReference.findUserById("1", new OnDbCompleteListener<User>() {
#Override
public void onComplete(User user) {
Logger.info(TAG, "YAYA");
}
});
DbUpdateListener:
public interface OnDbCompleteListener<T> {
void onComplete(T t);
}

Thanks to #FrankvanPuffelen i had to do following changes, because i was storing id as Integer so i should request for Integer only.
public void findUserById(final Integer id, final OnDbCompleteListener<User> userListener) {
mSingleUserQuery = mReference.orderByChild("id").equalTo(id);
...
}
From
public void findUserById(final String id, final OnDbCompleteListener<User> userListener) {
mSingleUserQuery = mReference.orderByChild("id").equalTo(id);
...
}
Also along with this changes i had to add index as suggested in console by firebase war logger here is the rules files
{
"rules": {
".read": true,
".write": false,
"users": {
".indexOn": "id"
}
}
}

For pushing value directly into node, you could use -
User user = "detail of your user";
// On firebase reference push value on id directly.
ref.child("1").setValue("user);
Here "1" is an id which is going to be primary key for your user detail.
Update -
public void saveUser() {
for (User user : userList) {
mReference.child(user.id).setValue(user);
}
}

Related

I Want to store firebase child's data to Arraylist

I have an Android application connected to firebase, I add the data in firebase manually but I want to fetch it and store it in an ArrayList with type Object, here is my firebase :
My Array :
ArrayList<Character> CharacterList = new ArrayList<>();
My Character Class :
public class Character {
private String name , Description , imageurl ;
public Character() {
}
public Character(String name, String desc , String imgurl) {
this.name = name;
this.Description = desc;
this.imageurl = imgurl;
}
public String getname(){
return this.name;
}
public String getDescription(){
return this.Description;
}
public String getImageurl(){
return this.imageurl;
}
}
You need to create DatabaseReference like this:
DatabaseReference database=FirebaseDatabase.getInstance().getReference().child("yourChild");
and then use addChildEventListener:
database.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Character character = dataSnapshot.getValue(Character.class);
CharacterList.add(character);
}
#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) {
}
});

Android Firebase DataSnapshot class returning null to custom java object

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

Firebase DataSnapshot Null values

My app allows you to add a Player to a node, once they have been added I am using the below method to search by phoneNum to see if that player exists in the 'users' node.
Where I am having trouble is that I need to be able to access the values from the datasnapshot for the user within the found matching node. e.g.return the value of the user id. When I attempt this it keeps showing as a null value and when I try to log to the console it complains that it is a null value which doesn't make sense as the if statement should take care of this.
The method is able to find if a player exists in the the users node and displays a Toast message to indicate this.
Code:
public void checkPlayerNum(final String phoneNum) {
DatabaseReference mDatabaseReference =
FirebaseDatabase.getInstance().getReference().child("users");
if (!TextUtils.isEmpty(phoneNum)) {
final Query phoneNumReference = mDatabaseReference.orderByChild("phoneNum").equalTo(phoneNum);
ValueEventListener phoneNumValueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
// String key = String.valueOf(dataSnapshot.getValue());
User mUser = dataSnapshot.getValue(User.class);
String uId = mUser.getUid();
// Log.d("TAG",uId);
Toast.makeText(getApplicationContext(), "* found **"+ uId , Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "****NOT FOUND****", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
phoneNumReference.addListenerForSingleValueEvent(phoneNumValueEventListener);
} else {
Log.e("Error","phoneNum is null");
}
}
final Query query = mFirebaseDatabase.orderByChild("phoneNum").equalTo("userPhoneNumber");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
//here means the value exist
//do whatever you want to do
} else {
//here means the value not exist
//do whatever you want to do
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
Use this to check whether the data exist or not.
you need to do this at two steps , first check if the user exists. then you get user info by your userId.
DatabaseReference mDatabaseReference;
public void checkPlayerNum(final String phoneNum,final String userId) {
mDatabaseReference =
FirebaseDatabase.getInstance().getReference().child("users");
if (!TextUtils.isEmpty(phoneNum)) {
final Query phoneNumReference = mDatabaseReference.orderByChild("phoneNum").equalTo(phoneNum);
ValueEventListener phoneNumValueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
// user exists
getUserInf(userId);
} else {
Toast.makeText(getApplicationContext(), "****NOT FOUND****", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
phoneNumReference.addListenerForSingleValueEvent(phoneNumValueEventListener);
} else {
Log.e("Error","phoneNum is null");
}
}
get user info by userId. mDatabaseReference is the same as before . define it as member field .
void getUserInf(String userId) {
userValueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// get user data
User mUser = dataSnapshot.getValue(User.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mDatabaseReference.child(userId).addListenerForSingleValueEvent(userValueEventListener);
}
your user Pojo should be like below.
public class User {
String email,name,phoneNum,uid;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
}
Thanks everybody I managed to achieve it by using childEventListener
public void checkingNumber(final String phoneNum){
DatabaseReference mDatabaseReference =
FirebaseDatabase.getInstance().getReference().child("users");
final Query query = mDatabaseReference;
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot.getValue() != null) {
// String key = String.valueOf(dataSnapshot.getValue());
User mUser = dataSnapshot.getValue(User.class);
// String uId = mUser.getUid();
// usersDatabase.child(mUser.getUid());
// Log.d("TAG",uId);
if(mUser.getPhoneNum().equals(phoneNum)) {
String uId= mUser.getUid();
String email = mUser.getEmail();
String name = mUser.getName();
Toast.makeText(getApplicationContext(), "* found **" + " " + uId + " " + " " + email + " " + name, Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(), "****NOT FOUND****", Toast.LENGTH_LONG).show();
}
}
#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) {
}
});
}

Android Firebase retrieve data from child node

I'm trying to get the data from Firebase child node. But it throws Can't convert object of type java.lang.String to type uk.co.stableweb.geethika.model.DailyVerse exception.
This is the structure of my Firebase database.
Here is the code. I'm using Android Firebase new documentation.
mRef = FirebaseDatabase.getInstance().getReference().child("daily_verse");
mRef.keepSynced(true);
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
Log.d("Child Event,Verse", dataSnapshot.getKey());
dailyVerse = dataSnapshot.getValue(DailyVerse.class);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
Log.d("Child Event,Verse", "onChildChanged:" + dataSnapshot.getKey());
dailyVerse = dataSnapshot.getValue(DailyVerse.class);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w("Firebase", "onCancelled", databaseError.toException());
Toast.makeText(context, "Failed to load verse",
Toast.LENGTH_SHORT).show();
}
};
mRef.addChildEventListener(childEventListener);
And Model class.
public class DailyVerse {
private String verse_title;
private String verse_content;
public String getVerseTitle() {
return verse_title;
}
public void setVerseTitle(String verse_title) {
this.verse_title = verse_title;
}
public String getVerseContent() {
return verse_content;
}
public void setVerseContent(String verse_content) {
this.verse_content = verse_content;
}
}
And the LogCat.
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type uk.co.stableweb.geethika.model.DailyVerse
at com.google.android.gms.internal.zzalq.zzd(Unknown Source)
at com.google.android.gms.internal.zzalq.zzb(Unknown Source)
at com.google.android.gms.internal.zzalq.zza(Unknown Source)
at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
at uk.co.stableweb.geethika.VerseActivityFragment$1.onChildAdded(VerseActivityFragment.java:63)
at com.google.android.gms.internal.zzahh.zza(Unknown Source)
at com.google.android.gms.internal.zzajh.zzctc(Unknown Source)
at com.google.android.gms.internal.zzajk$1.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
But if I change the database reference as follows. And get the dataSnapshot value, it grabs the data.
mRef = FirebaseDatabase.getInstance().getReference("daily_verse");
testVal = (String) dataSnapshot.getValue();
Log.d("TEST", testVal);
V/FA: Activity resumed, time: 278033062
D/Child Event,Verse added: verse_content
D/TEST: විශ්වාසකමේ මාර්ගය තෝරා ගතිමි. ඔබගේ විනිශ්චයන් මා ඉදිරියෙහි තබා ගතිමි.
D/Child Event,Verse added: verse_title
D/TEST: ගීතාවලිය 119:30
I think it is possible to get those values using HashMap. But there was a comment saying it is no longer recommended.
Pay careful attention to the names of your properties in the JSON and your fields/getters in the Java code. If they don't match, the Firebase client won't be able to match the values between them.
Your JSON has verse_title and verse_content, so your Java class must be either:
public class DailyVerse {
public String verse_title;
public String verse_content;
}
or:
public class DailyVerse {
private String verse_title;
private String verse_content;
public String getVerse_title() {
return verse_title;
}
public void setVerse_title(String verse_title) {
this.verse_title = verse_title;
}
public String getVerse_content() {
return verse_content;
}
public void setVerse_content(String verse_content) {
this.verse_content = verse_content;
}
}
Since Firebase Android SDK 9.2, you can also annotate your Java code to map to the correct JSON properties. So a third way to get the correct mapping is:
public class DailyVerse {
private String verse_title;
private String verse_content;
#PropertyName("verse_title")
public String getVerseTitle() {
return verse_title;
}
public void setVerseTitle(String verse_title) {
this.verse_title = verse_title;
}
#PropertyName("verse_content")
public String getVerseContent() {
return verse_content;
}
public void setVerseContent(String verse_content) {
this.verse_content = verse_content;
}
}
I haven't tried that latest variant though, so let me know if there are typos on the answer.
By this method
mRef.addChildEventListener(childEventListener);
you subscribe for
.child("daily_verse");
children. daily_verse has two children: verse_content and verse_title. The type of these children is String. So, you get two String datasnapshot in the onChildAdd listener.
Update:
Try something like this:
mRef = FirebaseDatabase.getInstance().getReference();
mRef.keepSynced(true);
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
Log.d("Child Event,Verse", dataSnapshot.getKey());
if ("daily_verse".equal(dataSnapshot().getKey){
dailyVerse = dataSnapshot.getValue(DailyVerse.class);
Log.d("TEST","Object: "+dailyVerse);
if (dailyVerse!=null){
Log.d("TEST","values: "+dailyVerse.verse_title+", "+dailyVerse.verse_content);
}
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
Log.d("Child Event,Verse", "onChildChanged:" + dataSnapshot.getKey());
if ("daily_verse".equal(dataSnapshot().getKey){
dailyVerse = dataSnapshot.getValue(DailyVerse.class);
Log.d("TEST","Changed object: "+dailyVerse);
if (dailyVerse!=null){
Log.d("TEST","Changed values: "+dailyVerse.verse_title+", "+dailyVerse.verse_content);
}
}
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w("Firebase", "onCancelled", databaseError.toException());
Toast.makeText(context, "Failed to load verse",
Toast.LENGTH_SHORT).show();
}
};
mRef.addChildEventListener(childEventListener);
You should subscribe to events from parent object and check the key at events listener.
DataRef = FirebaseDatabase.getInstance().getReference().child("Users");
DataRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String acctname = (String)dataSnapshot.child("Name").getValue();
String acctmail = (String)dataSnapshot.child("Email").getValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
When using a firebase model class, You have to include an empty constructor for firebase to work with.
Try adding it as
public class DailyVerse {
public DailyVerse(){
}
}
ArrayList<EventsResponse> usersEventsList = new ArrayList<>();
dummyIdsArrayList = new ArrayList<>();
Iterator<DataSnapshot> eventsIterator = dataSnapshot.getChildren().iterator();
while (eventsIterator.hasNext()) {
DataSnapshot eventsSnapShot = eventsIterator.next();
EventsResponse eventsResponse = new EventsResponse();
eventsResponse.setEventName(eventsSnapShot.getKey());
Iterator<DataSnapshot> eventChildIterator = eventsSnapShot.getChildren().iterator();
while (eventChildIterator.hasNext()) {
DataSnapshot eventchildSnapshot = eventChildIterator.next();
if (eventchildSnapshot.getKey().equals("is_recursive")) {
eventsResponse.setRecursive((Boolean) eventchildSnapshot.getValue());
} else if (eventchildSnapshot.getKey().equals("is_notif")) {
eventsResponse.setNotif((Boolean) eventchildSnapshot.getValue());
} else if (eventchildSnapshot.getKey().equals("is_editable")) {
eventsResponse.setEditable((Boolean) eventchildSnapshot.getValue());
} else if (eventchildSnapshot.getKey().equals("is_visible")) {
eventsResponse.setVisible((Boolean) eventchildSnapshot.getValue());
} else if (eventchildSnapshot.getKey().equals("name")) {
eventsResponse.setName(eventchildSnapshot.getValue().toString());
} else if (eventchildSnapshot.getKey().equals("date")) {
Iterator<DataSnapshot> eventChildDateIterator = eventchildSnapshot.getChildren().iterator();
while (eventChildDateIterator.hasNext()) {
DataSnapshot eventchildDateSnapshot = eventChildDateIterator.next();
if (eventchildDateSnapshot.getKey().equals("day")) {
eventsResponse.setDay(eventchildDateSnapshot.getValue().toString());
} else if (eventchildDateSnapshot.getKey().equals("month")) {
eventsResponse.setMonth(eventchildDateSnapshot.getValue().toString());
} else if (eventchildDateSnapshot.getKey().equals("year")) {
eventsResponse.setYear(eventchildDateSnapshot.getValue().toString());
}
}
} else {
eventsResponse.setNotif(true);
eventsResponse.setVisible(false);
}
}
if you are not able to fetch data,then you can fetch the data in that format.

fetch data from google firebase (android)

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

Categories

Resources