[英]I'm reading some data from Firebase database but it returned object is null
Here is my firebase structure Fire Base Structure 这是我的火力基础结构火力基础结构
I am trying to fetch phone value from firebase but it is giving null. 我正在尝试从Firebase获取电话值,但它给出了null。
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference com.google.firebase.database.DatabaseReference.child(java.lang.String)' on a null object reference java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'com.google.firebase.database.DatabaseReference com.google.firebase.database.DatabaseReference.child(java.lang.String)'
//getting user id value
SharedPreferences settings = getSharedPreferences("myapp", MODE_PRIVATE);
// Reading from SharedPreferences
String uid = settings.getString("uid", "");
userId = uid;
mFirebaseDatabase.child("users").child(userId).child("phone").addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
phone = dataSnapshot.getValue(String.class);
Log.d(TAG, "Value is: " +phone);
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
textview.setText(phone);
Please give some suggestion i don't know why it is returning null Thanks 请给我一些建议,我不知道为什么它返回null
Your error is here : 您的错误在这里:
string uid = settings.getString("uid","")
You're pushing the values using the random key and your code is unable to locate to that key rhat is why its giving null
您正在使用随机键推送值,而您的代码无法定位到该键,这就是为什么它给出null
Solution : In the code where you're pushing the values to the database instead of push just use 解决方案:在将值推入数据库而不是推入的代码中,只需使用
FirebaseDatabase.getInstance().getReference("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(your value model class variable)
Now in your fetching code just replace uid
with 现在在获取代码中,只需将uid
替换为
FirebaseAuth.getInstance().getCurrentUser().getUid()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.