How to get the value of child node in firebase - android

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

Related

Is there something wrong and i get 0 as value from Firebase? [duplicate]

This question already has answers here:
How to return a list from Firestore database as a result of a function in Kotlin?
(3 answers)
Closed 3 years ago.
I m trying to take a value from firebase, and always i get "0". I check my code and i cant find any error.
I used the same code in another activity and i had the correct value. Now for no reason as i didnt made any change, in both activities i cant read the value that i need
Json file:
"Ranking" : {
"Aditi" : {
"avatarUrl" : "https://i.imgur.com/S9dkvBA.png",
"score" : 60,
"userClass" : "Wizard",
"userName" : "Aditi"
},
And my code:
//Method to get the userScore from Ranking table in firebase
public void getScore() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String name = user.getDisplayName();
DatabaseReference rankingScore;
rankingScore = database.getReference("Ranking");
rankingScore.orderByChild("userName").equalTo(name)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
Ranking ranking = data.getValue(Ranking.class);
totalScore = ranking.getScore();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
I expect the value of "60" but i get "0"
Update: Ranking class
public class Ranking {
private String userName;
private long score;
private String avatarUrl;
private String userClass;
public Ranking(String userName, long score, String avatarUrl, String userClass) {
this.userName = userName;
this.score = score;
this.avatarUrl = avatarUrl;
this.userClass = userClass;
}
public Ranking() {
}
public Ranking(String userName, long score) {
this.userName = userName;
this.score = score;
}
public Ranking(String userName, long score, String avatarUrl) {
this.userName = userName;
this.score = score;
this.avatarUrl = avatarUrl;
}
public String getUserClass() {
return userClass;
}
public void setUserClass(String userClass) {
this.userClass = userClass;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public long getScore() {
return score;
}
public void setScore(long score) {
this.score = score;
}
public String getAvatarUrl() {
return avatarUrl;
}
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
}
just add child("Aditi") in reference :-
public void getScore() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String name = user.getDisplayName();
DatabaseReference rankingScore;
rankingScore = database.getReference("Ranking").child("Aditi");
rankingScore.orderByChild("userName").equalTo(name)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
Ranking ranking = data.getValue(Ranking.class);
totalScore = ranking.getScore();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

firebase realtime database writing data error: values in the firebase are different

I'm writing data to firebase realtime database. When some people register , error occured: values are not what i want . Only my there friends got this error. My registration codes, json format and User.class is below:
{
country: "Benin",
heart: 5,
highscore: "0000000",
mills: 0,
password: "12345678",
points: 0,
status: false,
username: "rr"
}
Values above is my json format when people register. Geneally i dont get this error. But some people register, my values are changed unexpectedly:
{
a: "Benin",
b: 5,
c: "0000000",
d: mills,
e: "12345678",
f: 0,
g: false,
h: "rr"
}
How can i fix this huge problem?
This is my registration code below(This code works when i click button):
databaseReference.child("users").orderByChild("username").equalTo(username).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
//finish();
progressBar.setVisibility(View.GONE);
et_username_layout.setError(getString(R.string.username_already_exists));
}else {
et_username_layout.setError(null);
String id=databaseReference.push().getKey();
Users users=new Users(username,password,"0000000",0, country,0,5,false,null);
databaseReference.child("users").child(id).setValue(users).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
progressBar.setVisibility(View.GONE);
Toast.makeText(RegisterActivity.this, R.string.registration_is_successful, Toast.LENGTH_SHORT).show();
Intent intent_success=new Intent(RegisterActivity.this,LoginActivity.class);
et_username_layout.setError("");
et_password_layout.setError("");
et_confirm_password_layout.setError("");
et_username_layout.getEditText().setText("");
et_password_layout.getEditText().setText("");
et_confirm_password_layout.getEditText().setText("");
country_name_tv.setText(getResources().getString(R.string.select_your_country));
username="";
password="";
confirm_password="";
country="";
//intent_success.setAction(REGISTER_SUCCESSFUL);
//startActivity(intent_success);
//finish();
final AlertDialog.Builder alert_ad=new AlertDialog.Builder(RegisterActivity.this);
alert_ad.setCancelable(false);
View view_Ad=getLayoutInflater().inflate(R.layout.alert_dialog_custum_reg_success,null);
alert_ad.setView(view_Ad);
final AlertDialog dialog=alert_ad.create();
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Button button=view_Ad.findViewById(R.id.btn_alert_dailog_custom_reg_success);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
finish();
}
});
}else {
progressBar.setVisibility(View.GONE);
Toast.makeText(RegisterActivity.this, R.string.registration_is_not_successful, Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
progressBar.setVisibility(View.GONE);
}
});
and my User.class
#IgnoreExtraProperties
public class Users {
private String username;
private String password;
private String highscore;
private String country;
private long mills;
private float heart;
private boolean status;
private Friends friends;
private int points;
public Users(String username, String password, String highscore,int points,
String country,long mills,float heart,boolean status,Friends friends) {
this.username = username;
this.password = password;
this.highscore = highscore;
this.country = country;
this.mills=mills;
this.heart=heart;
this.friends=friends;
this.status=status;
this.points=points;
}
public Users() {
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public Friends getFriends() {
return friends;
}
public void setFriends(Friends friends) {
this.friends = friends;
}
public float getHeart() {
return heart;
}
public void setHeart(float heart) {
this.heart = heart;
}
public long getMills() {
return mills;
}
public void setMills(long mills) {
this.mills = mills;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getHighscore() {
return highscore;
}
public void setHighscore(String highscore) {
this.highscore = highscore;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
}

Getting W/ClassMapper: No setter/field for XXX found on class

I am getting this error for every child under the parent node (GID) for Games in my Firebase json tree.
So that error message is for AwayTeam, HomeTeam, AwayScore, HomeScore, etc...Its like it did NOT map anything properly!?
The firebase structure is like the following:
Games
--- GID
----- AwayTeam
----- HomeTeam
----- AwayScore
----- HomeScore
etc...
My Adapter file is like the following:
public class PoolAdapter extends RecyclerView.Adapter<PoolAdapter.PoolViewHolder> {
public PoolAdapter(Dashboard dashboardFragment, String userID) {
this.mDashboardFragment = dashboardFragment;
mPoolRef = FirebaseDatabase.getInstance().getReference();
playerInPoolRef = mPoolRef.child("PlayerInPool").child(userID).orderByValue().equalTo(true);
playerInPoolRef.addValueEventListener(new PlayersInPoolChildEventListener());
}
private class PlayersInPoolChildEventListener implements ValueEventListener {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
getPoolData(dataSnapshot);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
}
private void getPoolData(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot: dataSnapshot.getChildren()) {
String poolID = snapshot.getKey();
poolRef = mPoolRef.child("Pools").child(poolID);
poolRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
getGameData(dataSnapshot);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
});
}
}
private void getGameData(DataSnapshot dataSnapshot) {
String gameID = dataSnapshot.child("GameId").getValue().toString();
gameRef = mPoolRef.child("Games").child(gameID);
gameRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
loadPlayerDashboard(dataSnapshot);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
});
}
private void loadPlayerDashboard(DataSnapshot dataSnapshot) {
Log.d(TAG, "*** Database snapshot: " + dataSnapshot); <-- Displays the correct Firebase information
Pools pool = dataSnapshot.getValue(Pools.class);
mPools.add(pool);
Collections.sort(mPools);
}
}
My Model class object is as follows:
public class Pools implements Comparable<Pools> {
private String _poolID;
//
private String _poolName;
private String _poolPassword;
private String _gameID;
private String _awayTeam;
private String _homeTeam;
private String _gameTime;
private String _gameDate;
public Pools() { }
public Pools(String poolID, String poolName, String gameID, String awayTeamName, String homeTeamName, String gameDate, String gameTime) {
this._poolID = poolID;
this._poolName = poolName;
//
this._gameID = gameID;
this._awayTeam = awayTeamName;
this._homeTeam = homeTeamName;
this._gameDate = gameDate;
this._gameTime = gameTime;
}
public String get_poolID() {
return _poolID;
}
public void set_poolID(String _poolID) {
this._poolID = _poolID;
}
public String get_poolName() {
return _poolName;
}
public void set_poolName(String _poolName) {
this._poolName = _poolName;
}
public String get_poolPassword() {
return _poolPassword;
}
public void set_poolPassword(String _poolPassword) {
this._poolPassword = _poolPassword;
}
public String get_gameID() {
return _gameID;
}
public void set_gameID(String _gameID) {
this._gameID = _gameID;
}
public String get_awayTeam() {
return _awayTeam;
}
public void set_awayTeam(String _awayTeam) {
this._awayTeam = _awayTeam;
}
public String get_homeTeam() {
return _homeTeam;
}
public void set_homeTeam(String _homeTeam) {
this._homeTeam = _homeTeam;
}
public String get_gameTime() {
return _gameTime;
}
public void set_gameTime(String _gameTime) {
this._gameTime = _gameTime;
}
public String get_gameDate() {
return _gameDate;
}
public void set_gameDate(String _gameDate) {
this._gameDate = _gameDate;
}
}
which has all the getters and setters so I am not sure why I am getting the error!?
I know the data is there as log log statement that you see above in my Adapter displays the following:
*** Database snapshot: DataSnapshot { key = 2019020300, value = {HomeTeam=Los Angeles Rams, GSIS=57833, GameYear=2019, isPlayed=true, hBackground=hTeam/rams.png, HomeId=29, hScore=0, GameTime=6:30, AwayId=31, aBackground=aTeam/patriots.png, SportID=1, aScore=0, Qtr=Pregame, WeekId=22, GameDate=20190203, AwayTeam=New England Patriots, SeasonType=SB} }
Does anyone know how I can resolve this!?
You need to iterate over dataSnapshot.getChildren(
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
Pools pool = childSnapshot.getValue(Pools.class);
}

DataSnapshot Firebase: Getvalue return null

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

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

Categories

Resources