Reputation: 13
My app is saving users in my firebase database, but when I try to read the value of the object it always returns null. The rules of my firebase are all set true and the app is saving the users properly. I don't know why I can't read the data and why it always returns null. This is my MainActivity class:
package com.example.leo_o.testfirebase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
private Button saveButton;
private EditText nameEditText;
private DatabaseReference mDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabase = FirebaseDatabase.getInstance().getReference("users");
saveButton = (Button) findViewById(R.id.saveButton);
nameEditText = (EditText) findViewById(R.id.nameEditText);
}
private void saveUser(String name) {
User user = new User(name);
String userId = mDatabase.push().getKey();
mDatabase.child(userId).setValue(user);
}
public void getData() {
ValueEventListener userListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
String name = user.getName();
if (name == null) {
Toast.makeText(MainActivity.this, "Null value", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
mDatabase.addValueEventListener(userListener);
}
@Override
public void onClick(View view) {
if (view == saveButton) {
String name = nameEditText.getText().toString();
saveUser(name);
getData();
}
}
}
An this is my User class:
package com.example.leo_o.testfirebase;
public class User {
public String name;
public User() {
}
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Does anyone know what is wrong with my code and why it always returns null?
Upvotes: 1
Views: 646
Reputation: 259
Your mDatabase points to the "users" node in firebase so the value that you are getting in "onDataChange" is a list of users and not a single user.
See how you are setting the value: mDatabase.child(userId).setValue()
You need to do the same if you just want to get the details of a single user. Attach the value event to a userId node.
Alternatively, you can also use a child event listener on mDatabase.
Upvotes: 1