Android: How to launch an Activity with an Intent, while also passing “extra” data

Here’s a short example of how to use an Intent to launch an Android Activity, while also adding some data (an “extra”) to the activity-launching process:

Intent currentQuoteIntent = new Intent(this, LandingPageActivity.class);
currentQuoteIntent.putExtra(GlobalState.LANDING_PAGE_INTENT_KEY, GlobalState.);
startActivityForResult(currentQuoteIntent, 0);

I show how to get the “extra” from an Activity or Fragment in this article on How to attach an extra to an Intent/PendingIntent in a Notification., but in short, the receiving Activity/Fragment can access the extra data like this:

public static class ShowFullQuoteFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container,
                             Bundle savedInstanceState) {

        // get the 'extra'
        String quote = getActivity().getIntent().getStringExtra(PollingService.INTENT_KEY);
        Log.i(PF_TAG, "QUOTE: " + quote);

        // other code here ...
        View rootView = inflater.inflate(R.layout.fragment_show_full_quote, container, false);
        TextView quoteLabel = (TextView)rootView.findViewById(R.id.put_quote_here);
        quoteLabel.setText(quote);
        return rootView;
    }
}

If you wanted to see how to add an extra to an Intent, use the Intent to launch an Activity, and then access the Intent in an Activity or Fragment, I hope this code is helpful.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.