0

I want to retrieve user name from my firebase data base here is what my database structure looks like

I have written this code and its showing 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's my code:

`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) {

        }
    });
}

}

Syyam Noor
  • 67
  • 10

2 Answers2

0

From your crash log, problem should be in the below line

mPostKey=getIntent().getExtras().getString("profile_id");

When opening the app from the background, because of app kill(killed from the background for some reason), it tried to create it from the stack, so for this case getExtras() will return null.

Solution:

  1. Saved profile_id in onSaveInstanceState(). It will get call before your activity get killed.

    @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); //Save your keys here. }

  2. Check the savedInstanceState when onCreate, if available, get the profile_id from there.

Mani
  • 17,549
  • 13
  • 79
  • 100
0

May be you are not passing anything in your intent, that is the reason why your getExtras is null & causing nullpointer. Add this check to avoid nullpointer.

if(getIntent.getExtras!=null){
   mPostKey=getIntent().getExtras().getString("profile_id");
}
farhan patel
  • 1,490
  • 2
  • 19
  • 30
  • i've tried 'if(getIntent.getExtras!=null){ mPostKey=getIntent().getExtras().getString("profile_id"); }' but now im facing this error Can't pass null for argument 'pathString' in child() – Syyam Noor Aug 05 '17 at 08:19