Wednesday, 3 December 2014

Sending data from one activity to another in Android


Step1: Using Intent Object for sending data from one activity:

public class MainActivity extends Activity implements OnClickListener {
  
  EditText etFName;
  EditText etLName;
  
  Button btnSubmit;
  
  
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        etFName = (EditText) findViewById(R.id.etFName);
        etLName = (EditText) findViewById(R.id.etLName);
        
        btnSubmit = (Button) findViewById(R.id.btnSubmit);
        btnSubmit.setOnClickListener(this);
        
    }


  @Override
  public void onClick(View v) {
    Intent intent = new Intent(this, ViewActivity.class); 
    
 intent.putExtra("fname", etFName.getText().toString());
    intent.putExtra("lname", etLName.getText().toString());
 
     OR
     
 Bundle b = new Bundle();
    //Inserts a String value into the mapping of this Bundle
    b.putString("fname", etFName.getText().toString());
 b.putString("lname", etLName.getText().toString());
 intent.putExtras(b);
    
 startActivity(intent);
  } 
}

Step2: Using Intent Object for receiving data in another activity

public class AnotherActivity extends Activity {
  
  TextView tvView;
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.view);
    
    tvView = (TextView) findViewById(R.id.tvView);
    
    Intent intent = getIntent();
    String fName = intent.getStringExtra("fname");
    String lName = intent.getStringExtra("lname");
 
     OR
 Bundle b = getIntent().getExtras();
 String fName = b.getCharSequence("fname");
    String lName = b.getCharSequence("lname");
    
    tvView.setText("Your name is: " + fName + " " + lName);
  }
} 

Next Article:


For any questions, suggestions and feedback, Please write to us. Thanks for Reading :)

No comments:

Post a Comment