Thursday, May 20, 2010

Android : startActivityForResult() Example

Hi,
Here is the code for startActivityForResult() method, I think it will help you to understand this method’s utility
to return the value from called Activity to calling activity.
Calling Activity
 package com.example.checkforresult;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class CheckStartActivityForResult extends Activity {
int requestCode;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
Log.d("CheckStartActivity","OnCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent i = new Intent(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
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==1){
Toast.makeText(this, "Pass", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(this, "Fail", Toast.LENGTH_LONG).show();
}
}
}
Called Activity
package com.example.checkforresult;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

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

And Please both services in your manifest file.