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());
}
});
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 want to calculate the sum of all rating values(float) that is in the nodes of Firebase database and wants to show in the text box.
Firebase Database
Firebase DATABASE Preview
Rating values i want to retrieve. I want sum of all the rating values and save that sum value in the text box.
Here is what i done
Database Class
public class databaseReview {
String description,name,userImage;
String rating;
public databaseReview(){
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public databaseReview(String rating, String description) {
this.rating = rating;
this.description = description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getuserImage() {
return userImage;
}
public void setuserImage(String userImage) {
this.userImage = userImage;
}
}
Java Class
DatabaseReference dataReference =
FirebaseDatabase.getInstance().
getReference().child("Feedbacks").child(name);
dataReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for( DataSnapshot ds :dataSnapshot.getChildren()) {
databaseReview data = ds.getValue(databaseReview.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
Assuming that the Feedbacks node is a direct child of your Firebase root and the name variable has its value as Abasyn University Islamabad, to count all the ratings, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference nameRef = rootRef.child("Feedbacks").child(name);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
double count = 0;
for(DataSnapshot ds : dataSnapshot.getChildren()) {
double rating = ds.child("rating").getValue(Double.class);
count = count + rating;
}
Log.d("TAG", count + "");
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
nameRef.addListenerForSingleValueEvent(eventListener);
But be aware, this will work only if the raiting property is stored in your database as a double. Your screenshot is correct but your model class shows:
String rating;
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);
//...
}
I get each profile back as objects and put them into an array list. The first println shows size as 1 then the second one shows the size as 0. How is this possible?... My Profile class has getters for each attribute and an empty Profile constructor.
// Initialize Profiles Array, global variable in my project
ArrayList<Profile> profileObjects = new ArrayList<>();
// GET FIREBASE PROFILE DATA, PUT INTO ARRAY
ref.child("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()){
Profile profiles = child.getValue(Profile.class);
profileObjects.add(profiles);
}
System.out.println("GETTTINGGGGG BACKKKKKKKKKKKKKKKKKKKKKKK 1: " + profileObjects.size());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
System.out.println("GETTTINGGGGG BACKKKKKKKKKKKKKKKKKKKKKKK 2: " + profileObjects.size());
Picture of my data in Firebase:
you can get all user's data then get "pic" from it or you can get only "pic" reference.
ref.child("Users").child(userId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// to get all user object ,then you can get pic url from it by calling user.getPic() for example
Usermodel user = dataSnapshot.getValue(Usermodel .class);
String picUrl = user.getPic();
// or you can get "pic" value only
String picUrl = dataSnapshot.child("pic").getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
your UserModel class could be like this
public class UserModel {
public UserModel() {
}
String name, age, gender, pic;
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 getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
}
you get null caue of
String picUrl = dataSnapshot.child("Uid").child("pic").toString();
where Uid is Just String not variable
you need to use
for (DataSnapshot child : dataSnapshot.getChildren())
{
// each child is user
// if you have use model do this
Usermodel um = child.getValue(Usermodel .class);
String picurl = um.getpicurl();
}
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());
}
});