I want to get user's name from my firebase database but I'm getting this error
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
here is my firebase database structure:
below is my code which is proffering the same error:
public class MyAccount extends AppCompatActivity {
private Button mSetupButton;
private EditText mSetupName;
private EditText mSetupBio;
private ImageButton mSetupImageButton;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private String mPostKey=null;
private DatabaseReference mDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_account);
mAuth=FirebaseAuth.getInstance();
String user_id=mAuth.getCurrentUser().getUid();
mDatabase= FirebaseDatabase.getInstance().getReference().child("Profiles");
mPostKey=getIntent().getExtras().getString(user_id);
mSetupName = (EditText) findViewById(R.id.accountName);
mSetupBio = (EditText) findViewById(R.id.accountBio);
mSetupButton = (Button) findViewById(R.id.accountButton);
mSetupImageButton = (ImageButton) findViewById(R.id.accountImageButton);
mDatabase.child(mPostKey).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String post_name = (String) dataSnapshot.child("Name").getValue();
mSetupName.setText(post_name);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
Apparently the error is in getting user id.
答案 0 :(得分:0)
just update or add as per your naming convention and your requirements in FirstScreen(i have almost done the required changes you need to make).
Intent i = new Intent(FirstScreen.this, MyAccount.class);
String user_id;
i.putExtra("user_id", user_id);
答案 1 :(得分:0)
假设之前的活动是MainActivity
,那么这是将额外的活动加到意图
String mPostKey = // the post key value here
Intent intent = new Intent(MainActivity.this, MyAccount.class);
intent.putExtra("post_key", mPostKey);
startActivity(intent);
要在MyAccount
活动中获得额外费用,请致电
mPostKey = getIntent().getExtras().getString("post_key");
顺便说一句,我建议您通过将uid
作为“post key”来更改数据库结构,这样您就可以更轻松地读取用户的信息而无需检索“post key”< / p>
{
"profiles": {
"0059HUGgfNcEyX73ZpTi6HQUscu1": {
"email": "aaa@gmail.com",
"image": "...",
"name": "...",
"phone": "..."
},
"other user's uid": {
...
}
}
}
使用这种数据库结构,您不再需要mPostKey
(不需要放置并获得额外的意图)。要获取用户的信息,您可以执行此操作
mDatabase.child(mAuth.getCurrentUser().getUid()). addValueEventListener(eventListener);
希望我的回答有所帮助:)
答案 2 :(得分:0)
要从firebase获取当前登录用户的名称,只需使用以下代码:
String user_name=mAuth.getCurrentUser().getDisplayName();