DataSnapshot Firebase: Getvalue return null - android

I try to read the user's data from Firebase Realtime Database but it always returns null. Here is my code:
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference();
ref.child("shop").child("Users").child(mAuth.getCurrentUser().getUid()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Users user = dataSnapshot.getValue(Users.class);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("1abc", "Failed to read value.", error.toException());
}
});
Here is the Users class:
public class Users {
private String full_name;
private String UID;
private String email;
public Users(String newemail, String newUID, String newfull_name) {
// ...
this.email=newemail;
this.full_name=newfull_name;
this.UID=newUID;
}
public Users() {
// ...
}
}
And here is my database tree:
Can someone tell me where am i wrong? Thanks in advance.

make Users model members public !
public class Users {
public String full_name;
public String UID;
public String email;
public Users(String newemail, String newUID, String newfull_name) {
// ...
this.email=newemail;
this.full_name=newfull_name;
this.UID=newUID;
}
public Users() {
// ...
}
}

You need to add getters and setters in your POJO class:
public class Users {
private String full_name;
private String UID;
private String email;
public Users(String newemail, String newUID, String newfull_name) {
// ...
this.email=newemail;
this.full_name=newfull_name;
this.UID=newUID;
}
public Users() {
// ...
}
public String getFull_name() {
return full_name;
}
public void setFull_name(String full_name) {
this.full_name = full_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;
}
}

Related

Datasnapshot's getValue() method is empty

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

Code does not excecute Firebase Database child event listener error

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);
//...
}

How to read specific value against particular key in Firebase?

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

Firebase database data retrieving -Java

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

How to get the value of child node in firebase

My Firebase heirarchy
I want to get the value of all "user", but calling datasnapshot.getValue is returning null.
FirebaseDatabase.getInstance().getReference("data").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
if (dataSnapshot.getKey().equals("user"))
username = data.getValue().toString();
Toast.makeText(getApplicationContext(), "sender is " + username, Toast.LENGTH_SHORT).show();
}
}
Create a class with the database structure.
public class Data {
private String msgbody;
private String mtime;
private String uname;
private String user;
public Data() {
}
public String getMsgbody() {
return msgbody;
}
public void setMsgbody(String msgbody) {
this.msgbody = msgbody;
}
public String getMtime() {
return mtime;
}
public void setMtime(String mtime) {
this.mtime = mtime;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
}
then
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Data obj = snapshot.getValue(snapshot.getValue(Data.class);
}

Categories

Resources