Pass data between activity

When start a new activity in our main activity using startActivity(), data can be passed using Bundle.

Inside the main activity, MainActivity.java
            Intent intent = new Intent();
intent.setClass(MainActivity.this, NewActivity.class);

Bundle bundle = new Bundle();
bundle.putCharSequence("extraCharSequence", "hello");
bundle.putInt("extraInt", 12345);
//...
intent.putExtras(bundle);
startActivity(intent);


Get the data in onCreate() of the new activity, NewActivity.java
    public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Bundle bundle = this.getIntent().getExtras();
CharSequence dataCharSequence = bundle.getCharSequence("extraCharSequence");
int dataInt = bundle.getCharSequence("extraInt");


};


The code this.getIntent().getExtras() return the map of all extras previously added with putExtra(), or null if none have been added.

0 Response to "Pass data between activity"

Posting Komentar