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());
}
});
Related
I am trying to show messages in a recycler view. I can successfully send messages to firebase server but no messages are shown in the app including my messages. I have created two models one for users and one for messages. I don't know if the problem is with retrieving data or with my recycler view.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group_chat);
init();
}
private void init() {
auth= FirebaseAuth.getInstance();
database= FirebaseDatabase.getInstance();
u= new User();
rvmessage= findViewById(R.id.rvMessage);
etMessage= findViewById(R.id.etMesage);
imgButton= findViewById(R.id.btnSend);
imgButton.setOnClickListener(this);
messages= new ArrayList<>();
}
#Override
public void onClick(View v) {
if(!TextUtils.isEmpty(etMessage.getText().toString())){
Message message= new Message(etMessage.getText().toString(), u.getName());
etMessage.setText("");
messagedb= database.getReference("messages");
messagedb.push().setValue(message);
}
else{
Toast.makeText(this, "You cannnot send blank message", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onStart() {
super.onStart();
final FirebaseUser currentUser= auth.getCurrentUser();
u.setUid(currentUser.getUid());
u.setEmail(currentUser.getEmail());
database.getReference("User").child(currentUser.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
u= new User();
u= dataSnapshot.getValue(User.class);
u.setUid(currentUser.getUid());
AllMethods.name= u.getName();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
messagedb= database.getReference("messages");
messagedb.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Message message= dataSnapshot.getValue(Message.class);
message.setKey(dataSnapshot.getKey());
messages.add(message);
displayMessages(messages);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Message message= dataSnapshot.getValue(Message.class);
message.setKey(dataSnapshot.getKey());
List<Message> newMessages= new ArrayList<Message>();
for(Message m: messages){
if (m.getKey().equals(message.getKey())){
newMessages.add(message);
}
else
{
newMessages.add(m);
}
}
messages= newMessages;
displayMessages(messages);
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
Message message= dataSnapshot.getValue(Message.class);
message.setKey(dataSnapshot.getKey());
List<Message> newMessages= new ArrayList<Message>();
for(Message m: messages){
if(!m.getKey().equals(message.getKey())){
newMessages.add(m);
}
}
messages= newMessages;
displayMessages(messages);
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
}
private void displayMessages(List<Message> messages) {
rvmessage.setLayoutManager(new
LinearLayoutManager(GroupChatActivity.this));
messageAdapter= new messageAdapter(GroupChatActivity.this, messages,
messagedb);
rvmessage.setAdapter(messageAdapter);
}
//pojo for messages
public class Message {
String name;
String message;
String key;
public Message() {
}
public Message(String name, String message) {
this.name = name;
this.message = message;
this.key = key;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
#NonNull
#Override
public String toString() {
return "Message{"+ "Message='" +message + '\''+", name='" + name+
'\''+", key='" +key+'\''+'}';
}
}
//pojo for user
public class User {
String uid;
String email, name;
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = 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;
}
#NonNull
#Override
public String toString() {
return "User{"+ "uid='" +uid + '\''+", name='" + name+ '\''+", email='" +email+'\''+'}';
}
public User() {
}
}
//adapter code(onBindviewHolder)
public void onBindViewHolder(#NonNull messageAdapterViewholder holder, int position) {
Message message = messages.get(position);
if(message.getName().equals(AllMethods.name)){
holder.tvTitle.setText("You : " + message.getMessage());
holder.tvTitle.setGravity(Gravity.START);
holder.l1.setBackgroundColor(Color.parseColor("EF9E73"));
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) {
}
});
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);
}
}
My code is as show below:
mFirebaseDatabase = mFirebaseInstance.getReference();
mFirebaseDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
allText.setText(dataSnapshot.child("58ca237b2e2c211dc0c7ed9").child("order_status").getValue(String.class));
Log.d(TAG, "onDataChange: " + dataSnapshot.hasChild("58ca237b2e2c211dc0c7ed9"));
Log.d(TAG, "onDataChange: next " + dataSnapshot.getValue().equals("58ca237b2e2c211dc0c7ed9"));
for (DataSnapshot child : dataSnapshot.getChildren()) {
Log.d(TAG, "onDataChange for: " + child.toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "onCancelled: ");
}
});
The response that I am getting in log is as shown below:
onDataChange for: DataSnapshot { key = 58ca237b2e2c211dc0c7ed9, value = {order_status=2} }
Here, I want to read order_status=2, but I am unable to do it. How can I do that?
My firebase schema is as show below:
You can Send/Receive Data from FireBase following way:
Send data to FireBase
EmpInfo empInfo = new EmpInfo();
empInfo.setName(mEditTextName.getText().toString());
empInfo.setAge(mEditTextAge.getText().toString());
empInfo.setMobile(mEditTextMobileNo.getText().toString());
empInfo.setCity(autoCompleteTextView.getText().toString());
databaseReference.child("Emp_Info").setValue(empInfo);
Get Data from FireBase
databaseReference.child("Emp_Info").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG,"onDataChages invoked ="+dataSnapshot.toString());
//Getting the data from snapshot
EmpInfo empInfo = (EmpInfo)dataSnapshot.getValue(EmpInfo.class);
mTextName.setText(mTextName.getText()+" : "+empInfo.getName());
mTextAge.setText(mTextAge.getText()+" : "+empInfo.getAge());
mTextMobileNo.setText(mTextMobileNo.getText()+" : "+empInfo.getMobile());
mTextCity.setText(mTextCity.getText()+" : "+empInfo.getCity());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Model class
public class EmpInfo {
public String name;
public String age;
public String mobile;
public String city;
public EmpInfo(){
}
public EmpInfo(String name, String age, String mobile,String city) {
this.name = name;
this.age = age;
this.mobile = mobile;
this.city = city;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Hope It will help you !
Create Model of result that you are expecting and then simply do like this, you can manipulate the code that works for you
public static class Post {
public String author;
public String title;
public Post(String author, String title) {
this.author = author;
this.title = title;
}
//Default Constructor
public Post {
}
//Setter and Getter below
-----
// Get a reference to our posts
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("server/saving-
data/fireblog/posts");
// Attach a listener to read the data at our posts reference
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Post post = dataSnapshot.getValue(Post.class);
System.out.println(post.get(------));
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
Here is my DB structure:
Code which I used for data reading:
user="hrcj7";
mDatabase = FirebaseDatabase.getInstance().getReference().child("User");
Query phoneQuery = mDatabase.orderByChild(user);
phoneQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {
User dinosaur = dataSnapshot.getValue(User.class);
System.out.println(dataSnapshot.getKey() + " was " + dinosaur.getEmail() + " meters tall.");
}
#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) {
Log.e("App", "onCancelled", databaseError.toException());
}
});
This is the dataSnapsshot value after retrieving:
DataSnapshot {
key = hrcj7,
value = {
-Kh2-jOeGXCOr-VE3uD5={
username=hrcj7,
email=rperera723#gmail.com,
imageurl=https://firebasestorage.googleapis.com/v0/b/freelancer-33195.appspot.com/o/Blog_Images%2Fcropped933315999.jpg?alt=media&token=7890f05f-87db-4a9d-9534-02da00225470
}
}
}
This is the model class:
public class User {
public String email;
public String imageurl;
public String username;
public User(String email,String imageurl,String username) {
this.email = email;
this.imageurl=imageurl;
this.username=username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getImageurl() {
return imageurl;
}
public void setImageurl(String imageurl) {
this.imageurl = imageurl;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public User() {
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
}
My problem is that dinosaur.getEmail() get null after retrieving the value. What can be the issue? Thanks in advance.
Here I found the solution .
In line:
User dinosaur = dataSnapshot.getValue(User.class);
should be replaced as following:
String key = mDatabase.child("User").child(user).push().getKey();
User dinosaur = dataSnapshot.child(key).getValue(User.class);