Luke
Luke

Reputation: 103

Can someone please explain the 'putExtra()' method? Please be simple and specific

I know that it adds extra data to an 'intent' and that "an Intent can carry data types as key-value pairs called extras. The putExtra() method takes the key name in the first parameter and the value in the second parameter," but what does this mean exactly? I was following the basic android app creation training at http://developer.android.com/training/basics/firstapp/starting-activity.html and came across the term. I'd like to understand this now for future reference. The relevant code is as follows:

    public void sendMessage(View view) 
    {
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.edit_message);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    }

Thanks for your help!

Upvotes: 1

Views: 1386

Answers (2)

Edalat Feizi
Edalat Feizi

Reputation: 1401

when you want to send some information to another activity or other components you could use putExtra() method of intent for example you have two activity loginActivity and mainActivity you want to send username to mainActivity after login so you can use of this code:

Intent intent = new Intent(loginActivity.this,mainActivity.class);
intent.putExtra("username",userName);
startActivity(intent);

in your mainActivity use below code to get username or other information

    Bundle bundle = getActivity().getIntent().getExtras();
    username= bundle.getInt("username");

Upvotes: 0

Rohit Sharma
Rohit Sharma

Reputation: 2017

Intent has several method called putExtra(String name, …..) that allows us to save inside the Intent our information. Reading the API Doc we know that we can add string, longs, CharSequence, int and so on. It behaves like a Map where there’s the key and the value.

Here is internal implementation of putExtra:

/**
 * Add extended data to the intent.  The name must include a package
 * prefix, for example the app com.android.contacts would use names
 * like "com.android.contacts.ShowAll".
 *
 * @param name The name of the extra data, with package prefix.
 * @param value The integer data value.
 *
 * @return Returns the same Intent object, for chaining multiple calls
 * into a single statement.
 *
 * @see #putExtras
 * @see #removeExtra
 * @see #getIntExtra(String, int)
 */
public Intent putExtra(String name, int value) {
    if (mExtras == null) {
        mExtras = new Bundle();
    }
    mExtras.putInt(name, value);
    return this;
}

Upvotes: 4

Related Questions