Android Firebase retrieve data from child node - android

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.

Related

retrieve data from firebase using getUid() in a alertDialog box

Want to retrieve username and its contact number from the firebase database. I tried doing it but in the logcat it throws an Null Pointer
Logcat:-
Process: com.example.bhavya.epark, PID: 27351
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.bhavya.epark.userreg.getName()' on a null object reference
at com.example.bhavya.epark.MapSelect$1$1.onDataChange(MapSelect.java:51)
at com.google.firebase.database.obfuscated.zzap.zza(com.google.firebase:firebase-database##16.0.3:75)
at com.google.firebase.database.obfuscated.zzca.zza(com.google.firebase:firebase-database##16.0.3:63)
at com.google.firebase.database.obfuscated.zzcd$1.run(com.google.firebase:firebase-database##16.0.3:55)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
MapSelect.java
mAuth = FirebaseAuth.getInstance();
udetail = FirebaseDatabase.getInstance();
DatabaseReference databaseReference = udetail.getReference(mAuth.getUid());
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userreg userprofile = dataSnapshot.getValue(userreg.class);
alertDialog1.setMessage("Name is:" + userprofile.getName());
alertDialog1.setMessage("Your Contact No:" + userprofile.getPnum());
alertDialog1.setMessage("Your Vehicle No is:" + userprofile.getVeclno());
alertDialog1.show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(MapSelect.this,databaseError.getCode(),Toast.LENGTH_SHORT).show();
}
});
userreg.java
package com.example.bhavya.epark;
public class userreg {
public String name,mailid,pnum,veclno;
public userreg(){
}
public userreg(String name,String mailid,String pnum,String veclno){
this.name=name;
this.mailid=mailid;
this.pnum=pnum;
this.veclno=veclno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMailid() {
return mailid;
}
public void setMailid(String mailid) {
this.mailid = mailid;
}
public String getPnum() {
return pnum;
}
public void setPnum(String pnum) {
this.pnum = pnum;
}
public String getVeclno() {
return veclno;
}
public void setVeclno(String veclno) {
this.veclno = veclno;
}
}
Database Strucure:-
Image reference
https://i.stack.imgur.com/owWJr.jpg
You are pointing towards a wrong database reference. Your database has a node named Users but your code doesn't have this.
Instead of
DatabaseReference databaseReference = udetail.getReference(mAuth.getUid());
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userreg userprofile = dataSnapshot.getValue(userreg.class);
alertDialog1.setMessage("Name is:" + userprofile.getName());
alertDialog1.setMessage("Your Contact No:" + userprofile.getPnum());
alertDialog1.setMessage("Your Vehicle No is:" + userprofile.getVeclno());
alertDialog1.show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(MapSelect.this,databaseError.getCode(),Toast.LENGTH_SHORT).show();
}
});
Use
DatabaseReference databaseReference = udetail.getReference().child("Users");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot messageSnapshot: dataSnapshot.getChildren()) {
userreg userprofile = messageSnapshot.getValue(userreg.class);
Log.v("info",String.valueOf(userprofile));
}
//Do whatever you like to do with your data here
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(MapSelect.this,databaseError.getMessage(),Toast.LENGTH_SHORT).show();
}
});

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

Query Firebase list with object value

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

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

Firebase returning null for Data values in Android

All data.getValue() are returning null. I can get child key to return fine. I can write to firbase fine. Just data.getValue is returning null for some unknown reason. I have other classes working fine using the exact same format.
//method for retrieving info from firebase which has notifications
private void retrieveInfo(){
Firebase ref = new Firebase("https://fitnectapp.firebaseio.com/");
// Attach an listener to read the data at our posts reference
ref.addChildEventListener(new ChildEventListener() {
// Retrieve new posts as they are added to the database
#Override
public void onChildAdded(DataSnapshot snapshot, String previousChildKey) {
getUpdates(snapshot);
}
#Override
public void onChildRemoved(DataSnapshot snapshot) {
getUpdates(snapshot);
}
#Override
public void onChildChanged(DataSnapshot snapshot, String previousChildKey) {
getUpdates(snapshot);
}
#Override
public void onChildMoved(DataSnapshot snapshot, String previousChildKey) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
//All data values returning null??
private void getUpdates(DataSnapshot ds) {
if (ds.getKey().equals("notifications")) {
for (DataSnapshot data : ds.getChildren()) {
String user = sp.getString("username", null);
Notification notification = data.getValue(Notification.class);
if(notification.getNotifUser().equals(user)){
String sender = notification.getNotifSender();
String workout = notification.getNotifWorkout();
String notificationTxt = sender + " has liked your workout, " + workout;
notifications.add(notificationTxt);
}
}
}
}

Categories

Resources