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);
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) {
}
});
I am developing an android based app using Firebase as backend server. I have designed the Structure of the app in the following manner:
Project Name
|_ Products
|_ groups
|_ 1BME
|_ members
|_ -K4usWDhtiw4U
|_ Custom Object
|_ -K4uscDHwYsXHs
|_ Custom Object
The Custom Object is:
package com.app.shubhamjhunjhunwala.heritagecompanion_students;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
/**
* Created by shubham on 23/01/17.
*/
public class UserDetails {
UserDetails() {}
public String name;
public String email;
public String password;
public String phone;
public String roll;
public String department;
public String year;
public String section;
public String dpDownloadUri;
public UserDetails(String name, String email, String password, String phone, String roll, String department, String year, String section, String dpDownloadUri) {
this.name = name;
this.email = email;
this.password = password;
this.phone = phone;
this.roll = roll;
this.department = department;
this.year = year;
this.section = section;
this.dpDownloadUri = dpDownloadUri;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getRoll() {
return roll;
}
public void setRoll(String roll) {
this.roll = roll;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
public String getDpDownloadUri() {
return dpDownloadUri;
}
public void setDpDownloadUri(String dpDownloadUri) {
this.dpDownloadUri = dpDownloadUri;
}
}
My intention is to get the user details under members child under 1BME under Groups child. So for this, I use the Following code in my program:
mDatabase = FirebaseDatabase.getInstance();
mGroupMembersDatabaseReference = mDatabase.getReference().child("groups").child(groupRoll).child("members");
mGroupMembersDatabaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
UserDetails users = dataSnapshot.getValue(UserDetails.class);
Toast.makeText(GroupChatActivity.this, users.getRoll(), Toast.LENGTH_SHORT).show();
if (!users.getRoll().equals(senderRoll)) {
Toast.makeText(GroupChatActivity.this, users.getName(), Toast.LENGTH_SHORT).show();
mRecieverDatabaseReference = mRecieverDatabaseReference.child(users.getRoll()).child("groups").child(groupRoll);
Query query1 = mRecieverDatabaseReference.orderByChild("roll").equalTo(groupRoll);
query1.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
dataSnapshot1.getRef().child("state").setValue("unread");
dataSnapshot1.getRef().child("timeID").setValue(timeID);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Messages message = new Messages(messageText, time, senderRoll, name, chatName, groupRoll, mState, messageType, "");
mRecieverDatabaseReference.push().setValue(message);
mRecieverDatabaseReference = mDatabase.getReference().child("chats");
}
}
#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) {
}
});
In this code String groupRoll = "1BME"
But when I run this code and debug it, I find that it never enters onChildAdded(). So please help me. The app isn't moving forward because of this.
Thank You.
First of all your DatabaseReference is wrong. To get data from a member please use this code:
mGroupMembersDatabaseReference = mDatabase.getReference().child("groups").child(groupRoll).child("members").child(memberId);
In which the memberId is unique id generated by the push() method.
Second, you don't need to use addListenerForSingleValueEvent to change a value. Is wrong to use setValue() method on a DataSnapshot. You can use setValue() directly on your reference. Hope it helps.
try this
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
UserDetails users = snapshot.getValue(UserDetails.class);
//...
}
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());
}
});
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());
}
});