Send Data to New Activity

You can add data (“extras”) to an Intent to send data from one activity to another. Do this before your startActivitiy() method call.

Then, in the second activity you create a Bundle object in the onCreate() method using the getExtras method.

This Bundle contains the “extras” from the the previous activity.

Example:
http://www.leylakapi.com/blog/2014/11/08/how-to-use-getextra-and-putextra-in-android-for-string-data/

Another Example:
https://stackoverflow.com/questions/5265913/how-to-use-putextra-and-getextra-for-string-data/25291944#25291944

Video Example:

Main Activity Example Code:

  • Notice the putExtra() method. This adds a key value pair of data to the Intent object that will launch the next activity. The next activity will be able to access this data.
  • You can include multiple extras if you call the putExtra() method multiple times.
public class MainActivity extends AppCompatActivity {
    EditText infoText;
    Button nextScreen;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        infoText = findViewById(R.id.infoText);
        nextScreen = findViewById(R.id.nextScreen);
    }

    void clicked(View v){
        String value = infoText.getText().toString();
        Intent intent = new Intent(this, NextScreen.class);
        intent.putExtra("key", value);
        startActivity(intent);
    }
}

Second Activity Example Code:

  • The second activity retrieves the extras that were included in the Intent object.
  • getIntent() retrieves the Intent object, which includes a Bundle of extras data from the previous activity.
  • getExtras retrieves a Bundle of extras from the Intent.
  • Bundles have a “get()” method that retrieves the data from the Bundle that is associated with a particular key.
public class NextScreen extends AppCompatActivity {
    TextView display;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_next_screen);
        display = findViewById(R.id.display);

        Intent intent = getIntent();
        Bundle bd = intent.getExtras();
        String info = (String) bd.get("key");
        display.setText(info);
    }
}