Monday, 8 August 2011

Passing values from one Activity to another


Intent intent = new Intent(context, CalledActivity.class);
        intent.putExtra(key, value);
        startActivity(intent);
       
If you want some data back from called Activity then you can use startActivityForResult() as:

Intent intent = new Intent(context, CalledActivity.class);
        intent.putExtra(key, value);
        startActivityForResult(intent, requestCode);
       
In called activity you can set data as:

setResult(RESULT_OK, intent);

Note: Here you set the value in intent and pass it to setResult().       
       

On returning back to calling Activity you can get data by overriding:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            //Get data from Intent "data" and do your task here....
        }
    }
   
   
Note: You can pass primitive data type values thru Intent and if you want to pass other types then you have to use Bundle like this.

Bundle data = new Bundle();
        data.putIntArray(key, value);
        //same way you can set other values.......
//Now set this Bundle value to Intent as you do for primitive type....
Intent intent = new Intent(context, CalledActivity.class);
        intent.putExtra(data);
        startActivity(intent);

Receiving data in Activity:

//For primitive values:
DataType var_name = getIntent().getExtras().get(key);

//For Bundle values:
Bundle var_name = getIntent().getExtras().getBundle(key);


No comments:

Post a Comment

Post a Comment