Monday, 28 May 2012

StartActivityForResult

 Start another activity from your activity and it expect to get some data from child activity and return that to parent activity.
Here,  CallingActivity.java expect result from CalledActivity.java,
CallingActivity.java
public class CallingActivity extends Activity {
    /** Called when the activity is first created. */
    int requestCode;
    TextView show;
    Button start;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        start = (Button)findViewById(R.id.button1);
        show = (TextView)findViewById(R.id.text);
       
        start.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent i = new Intent(CallingActivity.this,CalledActivity.class);     
                startActivityForResult(i, requestCode);
               
            }
        });
       
    }
   
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("CheckStartActivity","onActivityResult and resultCode = "+resultCode);
        // TODO Auto-generated method stub
        String value;
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==1){
            Toast.makeText(this, "Pass", Toast.LENGTH_LONG).show();
            value = Integer.toString(resultCode);
            show.setText(value);
        }
        else{
            Toast.makeText(this, "Fail", Toast.LENGTH_LONG).show();
        }
    }
}
CalledActivity.java
public class CalledActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("CalledActivity","OnCreate ");
        //String value = "rahul";
        Intent in = new Intent();
        setResult(1,in);//Here I am Setting the Requestcode 1, you can put according to your requirement
        finish();
    }
}



No comments:

Post a Comment