I have tried these 3 days working on android notification where user tap on notification then Activity open. But each time i set toast, it says null. Tried with some solutions from SOF, but doesn't work. can you please look what is wrong with the code? Thanks in advance.
The Notification code is
private void sendPushNotification(JSONObject json) {
//optionally we can display the json into log
int notificationId = new Random().nextInt();
Log.e(TAG, "Notification JSON " + json.toString());
try {
//getting the json data
JSONObject data = json.getJSONObject("data");
//parsing json data
String title = data.getString("title");
String message = data.getString("message");
String imageUrl = data.getString("image");
// Instantiate a Builder object.
NotificationCompat.Builder builder = new NotificationCompat.Builder(this.getApplicationContext(),"Default");
Intent notifyIntent = new Intent(this, MainActivity.class);
notifyIntent.putExtra("fromNotification", true);
// Sets the Activity to start in a new, empty task
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
// Creates the PendingIntent
PendingIntent pendingIntent =
PendingIntent.getActivity(
this.getApplicationContext(), notificationId,
notifyIntent,
PendingIntent.FLAG_ONE_SHOT
);
//int id = 1;
// Puts the PendingIntent into the notification builder
builder.setContentIntent(pendingIntent);
// Notifications are issued by sending them to the
// NotificationManager system service.
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Builds an anonymous Notification object from the builder, and
// passes it to the NotificationManager
if (mNotificationManager != null) {
mNotificationManager.notify(notificationId, builder.build());
}
} catch (JSONException e) {
Log.e(TAG, "Json Exception: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
And mainActivity.class is
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setElevation(0);
}
// Open Tab
if(getIntent().getExtras() != null){
Bundle b = getIntent().getExtras();
boolean cameFromNotification = b.getBoolean("fromNotification");
Toast.makeText(this.getApplicationContext(),
"Error: " + getIntent().getExtras(),
Toast.LENGTH_LONG).show();
viewPager = findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = findViewById(R.id.tabs);
viewPager.setCurrentItem(1);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
}
else {
viewPager = findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = findViewById(R.id.tabs);
viewPager.setCurrentItem(0);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
} }