Step 1:Complete the tutorial on Moving From One Activity to Another First.
Link
Step 2:
Edit the
nextAcvitiy method to pass out data.
//In MainActivity.java
public void nextActivity(View view){
//Create the intent object to pass to another activity
Intent intent = new Intent(this, MainActivity2Activity.class);
//Add information to the intent object
//The first parameter is the identifier string.
//The second parameter is the data itself. Look into
//the documentation for the Intent object for the
//types of data that can be passed.
intent.putExtra("myText1", "Hello"); //Storing a String
intent.putExtra("myNum1", 555); //Storing an int
//move another activity given by the intent object
startActivity(intent);
}
Step 3:In the other activity, MainActivity2Activity, we will display message passed in. We will edit the
onCreate method to receive the intent and display the data.
//In MainActivity2Activity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
//Receive the intent object
Intent intent = getIntent();
//Getting the data passed in from the intent.
//Put in the identifier string in the getStringExtra method
String passedMessage = intent.getStringExtra("myText1");
//Put in the identifier string and default number
int passedNumber = intent.getIntExtra("myNum1",0);
//Display the results
Context context = getApplicationContext();
CharSequence text = "text: " + passedMessage + "\nnumber:" + passedNumber;
Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
toast.show();
}
Step 4:
Run the code. Click the
button in
MainActivity. You should see..
