Search code examples
androidandroid-activityonesignal

Call String from Activity to another


I would like to call a String from an Activity to another. It is not a simple as normal calling but this calling happens when I open a notification. I have a notification open handler that store the strings. I want to call the value stored in the strings title and body Here is the code of the open handler.

 public class MyNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
// This fires when a notification is opened by tapping on it.
private Context mContext;
public MyNotificationOpenedHandler (Context context) {
   mContext = context;
}
@Override
public void notificationOpened(OSNotificationOpenResult result) {
    OSNotificationAction.ActionType actionType = result.action.type;
    JSONObject data = result.notification.payload.additionalData;
    String title = result.notification.payload.title;
    String body = result.notification.payload.body;
    String launchUrl = result.notification.payload.launchURL; // update docs launchUrl

    String customKey;
    String openURL = null;
    Object activityToLaunch = AboutActivity.class;

    if (data != null) {
        customKey = data.optString("customkey", null);
        openURL = data.optString("openURL", null);

        if (customKey != null)
            Log.i("OneSignalExample", "customkey set with value: " + customKey);

        if (openURL != null)
            Log.i("OneSignalExample", "openURL to webview with URL value: " + openURL);
    }


    Intent intent = new Intent(mContext, (Class<?>) activityToLaunch);
    intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra("openURL", openURL);
    Log.i("OneSignalExample", "openURL = " + openURL);
    mContext.startActivity(intent);

}
}

The main question how can I call the strings title and body in other activities


Solution

  • Use bundle or put extra immediately:

    Intent intent = new Intent(mContext, (Class<?>) activityToLaunch);
    intent.putExtra("title", title);
    intent.putExtra("body", body);
    mContext.startActivity(intent);
    

    In the next activity:

    Intent intent = getIntent();
    String title = intent.getStringExtra("title");
    String body = intent.getStringExtra("body");
    

    if the structure is complicated, you can use bundle.

    Bundle bundle = new Bundle();
    bundle.putString("title", title);
    bundle.putString("body", body);
    intent.putExtras(bundle);
    

    If the data is needed to be global variable to whole application, you can extend Application and implement getter and setter for these data.

    Also, you can put the title and body to Database or SharedPreferences, and read it from any activity you want. Just make sure that do not do the i/o task in UI thread.