0

I am building an app and I am using FCM notifications. When user clicks on notification I want to send him to the Fragment1(that is the name of the fragment) on Main Activity. I do that with intent.putExtra but when in Main Activity I log Bundle extras=getIntent().getExtras() I have null pointer exception. Why I don't have anything in putExtra?

Here is myFireBaseMessagingService

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.d("OnMessage", "Received");
    super.onMessageReceived(remoteMessage);
    Log.d(TAG, "From " + remoteMessage.getFrom());
    Log.d(TAG, "Body " + remoteMessage.getNotification().getBody());
    sendNotification(remoteMessage);

}




private void sendNotification(RemoteMessage remoteMessage) {
    Intent intent=new Intent(this, MainActivity.class);
    intent.putExtra("action", "goToFragment1");
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent=PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
    Uri defaultSoundUri=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder=new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.logo)
            .setContentText(remoteMessage.getNotification().getBody())
            .setContentTitle("Asp")
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);
    NotificationManager notificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, notificationBuilder.build());


}

And here is MainActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn1=(Button)findViewById(R.id.dugme1);
    btn2=(Button)findViewById(R.id.dugme2);
    btn3=(Button)findViewById(R.id.dugme3);
    dugme=(Button)findViewById(R.id.subscribe);
    dugme.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            FirebaseMessaging.getInstance().subscribeToTopic("developeri");
            Log.d("Bravo", "Subscribed to developeri!");
        }
    });


    FragmentManager fm=getSupportFragmentManager();
    FragmentTransaction ft=fm.beginTransaction();
    StartFragment startFragment=new StartFragment();
    ft.add(R.id.myFragment, startFragment);
    ft.commit();
    btn1.setOnClickListener(btnOnClickListener);
    btn2.setOnClickListener(btnOnClickListener);
    btn3.setOnClickListener(btnOnClickListener);
    Intent intent=getIntent();
    Bundle extras=getIntent().getExtras();
    Log.d("Bundle", "Bundle is here");
    Log.d("Extras", extras.getString("action"));
    if (extras!=null && extras.containsKey("action") && extras.getString("action").contains("goToFragment1")){
        getSupportFragmentManager().beginTransaction().replace(R.id.myFragment, new Fragment1()).commit();
        Log.d("MainActivity", "IF IS HERE");

    }

}
 Button.OnClickListener  btnOnClickListener= new Button.OnClickListener() {
     @Override
     public void onClick(View view) {
         Fragment newFragment;
         if (view==btn1){
             newFragment =new Fragment1();

         }else if(view==btn2){
              newFragment =new Fragment2();
         }else if (view==btn3){
             newFragment =new Fragment3();
         }else{
             newFragment=new StartFragment();
         }
         FragmentTransaction transaction=getSupportFragmentManager().beginTransaction();
         transaction.replace(R.id.myFragment, newFragment);
         transaction.addToBackStack(null);
         transaction.setTransition(FragmentTransaction.TRANSIT_NONE);
         transaction.commit();


     }
 };

}

My logcat

06-07 09:22:49.598 23913-23913/com.example.dev3.fragmenti E/AndroidRuntime: FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.dev3.fragmenti/com.example.dev3.fragmenti.MainActivity}: java.lang.NullPointerException at android.app.ActivityThread.performLaunchActivity(ActivityThread.java) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java) at android.app.ActivityThread.access$700(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java) at android.os.Handler.dispatchMessage(Handler.java) at android.os.Looper.loop(Looper.java) at android.app.ActivityThread.main(ActivityThread.java) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:525) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.NullPointerException at com.example.dev3.fragmenti.MainActivity.onCreate(MainActivity.java:53) at android.app.Activity.performCreate(Activity.java) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java)  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java)  at android.app.ActivityThread.access$700(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java)  at android.os.Handler.dispatchMessage(Handler.java)  at android.os.Looper.loop(Looper.java)  at android.app.ActivityThread.main(ActivityThread.java)  at java.lang.reflect.Method.invokeNative(Native Method)  at java.lang.reflect.Method.invoke(Method.java:525)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)  at dalvik.system.NativeStart.main(Native Method)

Yazan
  • 6,074
  • 1
  • 19
  • 33
Goran_1992
  • 103
  • 1
  • 2
  • 9

2 Answers2

0

On create is only called when activity is launched. It main remain "alive" while receiving your notification. You should therefore have your code handling the extra in:

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        if (intent.hasExtra("action")) {
            String action =  intent.getExtras().getString("action");
            // Do what ever is needed
            if (action.equalsIgnoreCase("gotToFragment1")) { 
                getSupportFragmentManager().beginTransaction().replace(R.id.myFragment, new Fragment1()).commit();
            }
        }
    }

Add the onNewIntent() method to your MainActivity (the activity receiving the new Intent). This will be called if your activity is already started.

Tristan Richard
  • 3,385
  • 1
  • 15
  • 17
  • Okay, but where I am going to use "goToFragment1"? In this yours method I just using "action"? – Goran_1992 Jun 07 '16 at 07:33
  • intent.putExtra("action", "goToFragment1"); is set to late. Set it after intent creation – Tristan Richard Jun 07 '16 at 07:39
  • I set intent.putExtra like you said after intent creation but nothing. I again receive null pointer, and the most weird thing is that Logcat throws me an error on commented code! – Goran_1992 Jun 07 '16 at 07:45
  • I done this with onNewIntent but again I am receiving null pointer, and throws me to the line 53 like just before. But, what is the most interesting is that part of code now is commented, but error is still there! – Goran_1992 Jun 07 '16 at 07:52
  • Try cleaning your project. Seems that you are using Instant run and it has not detected the changes – Tristan Richard Jun 07 '16 at 07:52
  • Hoh, now I finally can run my app. But how to check whether I have extras or no? – Goran_1992 Jun 07 '16 at 07:55
  • Check for has extras and get extras – Tristan Richard Jun 07 '16 at 07:56
  • I dont have option intent.putString..just intent.putExtra – Goran_1992 Jun 07 '16 at 07:57
  • putString does not exist on intent my bad. Check my update – Tristan Richard Jun 07 '16 at 07:57
  • So, to summarise: In method sendNotification I must write intent.putExtra("action", "goToFragment1") or something else? – Goran_1992 Jun 07 '16 at 08:04
  • Just one more question mate: Why I dont use second part of Intent.putExtra("goToFragment1"),? – Goran_1992 Jun 07 '16 at 08:09
  • You can! that is the "yourString" variable you can make check before pushing to fragment – Tristan Richard Jun 07 '16 at 08:10
  • So, I have to write String yourString = intent.getExtras().getString("goToFragment"); or String goToFragment1= intent.getExtras().getString("action"); ? – Goran_1992 Jun 07 '16 at 08:13
  • Thanks mate, I will check now, maybe later, and i will write yo you if it works or not, if you are agree of course. – Goran_1992 Jun 07 '16 at 08:28
  • Again it backs me to the first page, not to the Fragment1..I don't know why that happens again.... – Goran_1992 Jun 07 '16 at 11:42
  • what do you mean? Is it a different issue? – Tristan Richard Jun 07 '16 at 12:13
  • Hey, now is all okay! But I have one more problem. Notification brings me to the wanted fragment(Fragment1) butt only when app is in the foreground. But when is in background notification takes me to the first page on MainActivity...I hope that you understand me... – Goran_1992 Jun 07 '16 at 12:23
  • Well, I have changed your code a litle bit, because that method onNewIntent() wasn't working so I have wrote in OnCreate this: String msg=getIntent().getStringExtra("action"); FragmentManager fragmentManager=getSupportFragmentManager(); FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction(); if (msg!=null){ if (msg.equals("goToFragment1")){ Fragment1 fragment1=new Fragment1(); fragmentTransaction.replace(R.id.myFragment, fragment1); fragmentTransaction.commit(); } – Goran_1992 Jun 07 '16 at 12:33
  • I think you should call add() instead of replace() at that point – Tristan Richard Jun 07 '16 at 12:41
  • I have created another question with a code. http://stackoverflow.com/questions/37680025/from-notification-to-fragment-when-app-is-in-the-background – Goran_1992 Jun 07 '16 at 13:19
0

try to move your

    intent.putExtra("action", "goToFragment1");

above

PendingIntent pendingIntent=PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Wooby
  • 216
  • 2
  • 10