1

I have been trying to send String to my mainActivity from a fragment. I don't know if I done this right, but I start new mainActivity Intent after user presses button in fragment. What I want to do is when application is opened fragment needs to be loaded instead of mainActivity if there is no String message sent from fragment. At the start of the main Activity I tried to check if the message is not null but I get an error and application don't want to start because I'am trying to access null object

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.audriusalekna.camerapht/com.example.audriusalekna.camerapht.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object referenc

Should I take a different approach on doing that?

Here is my code

Intent intent = getIntent();
    if(intent.getExtras().getString("tagsText") == null){
        Fragment fragment = TagsFragment.newInstance(tagsText, "blah");

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment, fragment).commit();
        cameraBtn.setEnabled(false);
        cameraBtn.setVisibility(View.GONE);
        firstTime = false;
    }
    else{
        tagsText = intent.getExtras().getString("tagsText");
        Log.v("MESSAGE", tagsText);
    }

2 Answers2

1

you need to check if the intent itself is not NULL, and if the bundle inside it is not NULL too

if(intent!=null && intent.getExtras() != null &&  intent.getExtras().getString("tagsText") == null){

the else should not deal with intent or the extras as mostly one of them is null

Yazan
  • 6,074
  • 1
  • 19
  • 33
0

Here:

intent.getExtras().getString() == null

You are checking "one level too deep". You would need:

intent.getExtras() == null

to avoid this problem here!

GhostCat
  • 137,827
  • 25
  • 176
  • 248