Skip to content
Advertisement

Bundle is null when starting an activity from a listener using intent

The bundle is null when I use this code. The Logcat shows:

 onSuccess: starting activity with intent
 getTokenFromIntent: bundle IS null (true)

MyListenerService.java

 Bundle bundle = new Bundle();

 bundle.putString("Name",message.getName());

 Intent intent = new Intent(getApplicationContext(), MainActivity.class);
 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 intent.putExtras(bundle);

 Log.d(TAG, "onSuccess: starting activity with intent");
 startActivity(intent);

MainActivity.java

 TokenMessage token = null;

 Intent intent = getIntent();
 if (intent!=null) {
     Bundle bundle = intent.getExtras();

     if (bundle!=null) {

          token = new TokenMessage();
          token.setName(bundle.getString("Name"));

        } else {
            Log.d(TAG, "getTokenFromIntent: bundle IS null (" + (bundle==null) + ")");
        }

    } else {
        Log.d(TAG, "getTokenFromIntent: intent IS null (" + (intent==null) + ")");
    }

I have this working in a similar module of another project and have been comparing them. The only notable difference is that the working MainActivity extends Activity, and this one extends AppCompatActivity.

I looked at this, but code seems consistent as it does use a bundle. I also reviewed this, but mine is basic and does pass values like demonstrated. I reviewed this one but it did not have a formal answer, but I have an example where I use a bundle which works and so do many of the examples. This one didn’t have an accepted answer.

I must be missing something. Maybe it’s a stupid little mistake but it’s driving me a little crazy.

Advertisement

Answer

When we start the activity from Service or with singleTask flag the Intent should be retrieved from onNewIntent method.

use the following link for more details. https://developer.android.com/reference/android/app/Activity.html#onNewIntent(android.content.Intent)

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement