There may be situation where you want to send data from one activity to another while switching from one activity to another.
public class FirstActivity extends Activity {
// Initializing variables
EditText inputName;
EditText inputAge;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
inputName = (EditText) findViewById(R.id.name);
inputAge = (EditText) findViewById(R.id.age);
Button btnNextScreen = (Button) findViewById(R.id.btnNextScreen);
// Listening to button event
btnNextScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// Starting a new Intent
Intent nextScreen = new Intent(getApplicationContext(),
SecondActivity.class);
// Sending data to another Activity
nextScreen.putExtra("name", inputName.getText().toString());
nextScreen.putExtra("age", inputAge.getText().toString());
startActivity(nextScreen);
}
});
}
}
public class SecondActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
TextView txtName = (TextView) findViewById(R.id.txtName);
TextView txtEmail = (TextView) findViewById(R.id.txtAge);
Button btnBack = (Button) findViewById(R.id.btnBack);
Intent i = getIntent();
// Receiving the Data
String name = i.getStringExtra("name");
String age = i.getStringExtra("age");
Log.e("Second Screen", name + "." + age);
// Displaying Received data
txtName.setText(name);
txtEmail.setText(age);
// Binding Click event to Button
btnBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// Closing SecondScreen Activity
finish();
}
});
}
}
"If you would thoroughly know anything, teach it to other."
- Tryon Edwards -