switching activity and sending data

There may be situation where you want to send data from one activity to another while switching from one activity to another.

FirstActivity.java

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); 
   } 
  }); 
 } 
}

 

SecondActivity.java

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(); 
   } 
  }); 
 } 
}

 

태그: 
youngdeok의 이미지

Language

Get in touch with us

"어떤 것을 완전히 알려거든 그것을 다른 이에게 가르쳐라."
- Tryon Edwards -