我想从我的firebase数据库here is what my database structure looks like
中检索用户名我已编写此代码并显示错误“java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference"
这是我的代码:
`public class MyAccount extends AppCompatActivity {
private Button mSetupButton;
private EditText mSetupName;
private EditText mSetupBio;
private ImageButton mSetupImageButton;
private String mPostKey=null;
private DatabaseReference mDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_account);
mDatabase= FirebaseDatabase.getInstance().getReference().child("Profiles");
mPostKey=getIntent().getExtras().getString("profile_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) {
}
});
}
}
答案 0 :(得分:0)
从崩溃日志中,问题应该在下面一行
mPostKey=getIntent().getExtras().getString("profile_id");
当从后台打开应用程序时,由于app kill(由于某种原因从后台杀死),它试图从堆栈中创建它,因此对于这种情况,getExtras()
将返回null。
解决方案:
在onSaveInstanceState()中保存了profile_id。它会在你的活动被杀之前接到电话。
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//Save your keys here.
}
在onCreate上检查savedInstanceState
,如果可用,从那里获取profile_id。
答案 1 :(得分:0)
可能是你没有传递任何意图,这就是为什么你的getExtras为null&导致nullpointer。添加此检查以避免nullpointer。
if(getIntent.getExtras!=null){
mPostKey=getIntent().getExtras().getString("profile_id");
}