How to call startactivityforresult from a non-activity class to get the resuts

onactivityresult in non activity class
onactivityresult not called
onactivityresult resultcode
when is onactivityresult called
onactivityresult requestcode
onactivityresult overrides nothing
startactivityforresult in non activity class
start fragment for result

Is it possible to call startActivityForResult() from a non-activity class to get the results?

Scenario is something like this:

I have a class NonActivity (it doesn't derive from Activity as its not a UI). This class will have bunch of functions(steps basically) to run. One of the steps requires to show UI(Activity) and then get the result (user enter something). Then been able to use that data in next following steps.

How can this be achieved without deriving from activity class as I don't have UI component? Also since I don't want to derive from activity class that means I cannot override OnActivityResult(). Where results actually come from?

startActivityForResult() is only available from real on-screen activities, since it is a method in, well, Activity. Please redesign your application so that the user interface is driven from activities.

On the other hand, if your non Activity class is initialized and used from an onscreen Activity, you could pass that instance of the Activity to your class as a parameter in the constructor and use it to launch other Activities.

Be careful though. Using this method increases the risk of a memory leak, as the external class (Utils in my example) might keep a reference to the Activity even after its gone.

If all you want to do is access data, then you could try writing it to SharedPreferences or a Database or some files and then using the application context (passed in via a constructor again) to read it. This reduces the risk of a memory leak. Something like:

MyApiClass myApiClass = new MyApiClass(getApplicationContext());


Main Activity:

public class Main extends FragmentActivity {

    protected void onCreate(Bundle savedInstanceState) {

        Utils util = new Utils(this);


    protected void onActivityResult(int arg0, int arg1, Intent arg2) {
        Toast.makeText(this, "onActivityResult called", Toast.LENGTH_LONG).show();

        super.onActivityResult(arg0, arg1, arg2);


Utils class (which launches for result):

public class Utils {

    Activity activity;

    public Utils(Activity ac) {
        activity = ac;

    public void startTest() {
        Intent i = new Intent(activity, Test.class);
        activity.startActivityForResult(i, 1);



Test Activity:

public class Test extends FragmentActivity {

    protected void onCreate(Bundle savedInstanceState) {
        Toast.makeText(this, "Test", Toast.LENGTH_LONG).show();




call to startActivityForResult() from non activity class and getting , So, calling startActivityForResult() in an activity and expecting to see the result in a fragment does not work. Either move the request to fragment, or the response handling to activity. Also, if you don't handle a result, pass it on to the super implementation. On the other hand, if your non Activity class is initialized and used from an onscreen Activity, you could pass that instance of the Activity to your class as a parameter in the constructor and use it to launch other Activities. Be careful though.

StartActivityForResult from a class using a fragment with no visible GUI. You might find something like this in a utility class.

see runGetUserAccount below. It creates its own fragment and executes a startActivityForResult. Then it has it's own onActivityResult.

public class MyGooglePlay {

    private static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 31502;
    private ActionBarActivity activity;
    private FragmentManager fragManager;

    public MyGooglePlay(ActionBarActivity activity) {
        this.activity = activity;
        this.fragManager = activity.getSupportFragmentManager();

     * Starts an activity in Google Play Services so the user can pick an
     * account
    private String mEmail = "";
    static final int REQUEST_CODE_PICK_ACCOUNT = 1000;    
    public void runGetUserAccount() {
        if (TextUtils.isEmpty(mEmail)) {
            // run this code in gui less fragment so we can pickup the 
            // on activity result from inside the mygoogleplay class.
            Fragment f = new Fragment() {
                public void onAttach(Activity activity) {
                    String[] accountTypes = new String[] { "" };
                    Intent intent = AccountPicker.newChooseAccountIntent(null,
                            null, accountTypes, false, null, null, null, null);
                    startActivityForResult(intent, REQUEST_CODE_PICK_ACCOUNT);

                public void onActivityResult(int requestCode, int resultCode,
                        Intent data) {
                    if (requestCode == REQUEST_CODE_PICK_ACCOUNT) {
                        if (resultCode == Activity.RESULT_OK) {
                            // getUsername();
                    super.onActivityResult(requestCode, resultCode, data);

                //this is to verify the fragment has been removed.
                //you can log or put a breakpoint to verify
                @Override public void onDestroy(){
            FragmentTransaction fragmentTransaction = this.fragManager
            fragmentTransaction.add(f, "getusername");

     * @param mEmail
     *            the mEmail to set
    private void set_Email(String mEmail) {
        this.mEmail = mEmail;
        if (!TextUtils.isEmpty(mEmail)) {
            // TODO notify caller email is ready;
            // activity.onEmailReady(mEmail);
        //we are done with the "getusername" fragment
        Fragment f = fragManager.findFragmentByTag("getusername");
        if (f!=null) {

Calling startActivityForResult in a non-activity class : androiddev, I have a class with a UI with a button and a listener for that … unable to run start activity for result because the class I'm trying to run it in is not an activity class. Calling startActivityForResult in a non-activity class hey guys, I'm crazy new to android dev and I'm hoping you guys can help me out a bit. I have a class with a UI with a button and a listener for that button.

U should pass context as Activity,then u will get solution. try this below will work

In non Activity class

public class nonActivity {

public static void method(Activity activity)
     Intent intent = new Intent(activity, SecondActivity.class);
     activity. startActivityForResult(intent, REQUEST_CODE);

In SecondActivity

 Intent intent = getIntent();
 intent.putExtra("data", "data");   //here u can pass data to previous activity
 setResult(RESULT_OK, intent);

In firstActivity

protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    try {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            String status = data.getStringExtra("data");
            //Do what u want with data
    } catch (Exception e) {
        System.out.println("=====Exception=====" + e.toString());

How to call onActivityResult from non activity class, finish() And get result in Activity1 as below; #Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (this. requestCode ==� Instead of declaring private Context context in the anonymous implementation of Animation.AnimationListener, you should reference Context from the class that calls animlation.setAnimationListener. For this example I'll assume your class is called MyClass , and you should then change the call from

If you want the result back from the activity to your normal class, supposed it is a class with a custom adapter within it.

  1. you cannot use startActivityForResult because you are not in an activity
  2. what I did is that i launched the activity from the class with an intent. Then I calculated or did what I have to. From this activity I send the information to the main class supposed with a method MainActivity.the_method() and in the main activity I changed the custom adapter o did what I have to using the adapter object and calling adapter.getItem(position)

Hope this can give you an idea

Getting a result from an activity, Getting a result from an activity, startActivityForResult method, requires a result Create an inner class in the non Activity class and define your activity results Android StartActivityForResult Example, Which method is used to call another� If you are referring to something like: [code ]new MainActivity().doMyMethod();[/code] then this isn’t possible. The actual answer depends entirely on what you are trying to achieve.

How to use onActivityResult method from other than Activity class, EditText; public class GiveResultActivity extends Activity { EditText editText; ( You can call startActivityForResult more than once before you get any results. Re: [android-developers] How to call startactivityforresult from a non-activity class to get the resuts Jan 2013 Re: [android-developers] Re: why couldn't create webservice using android?

How to Get Results Back from an Activity in Your Android App , Launch an activity for which you would like a result when it finished. Using a negative requestCode is the same as calling startActivity(Intent) (the activity is int hashCode = ColorPickerActivity. class . you may not get the result when you expect. Yes, we thought about that, the only problem is that startActivityForResult is a method that only exists on the Activity class, not on the Context class. So this basically means we'd have to create two IntentBuilder class per Activity class.

startActivityForResult, setResult & onActivityResult, Before we get into the undocumented behavior, let's look at the known behavior. activity. It could send the result back using setResult by sending in the When we call Fragment's startActivityForResult (note: NOT activity? In this code, the last two statements are really saying, “With this activity’s own context, start running an instance of OtherActivity.” (If all goes well, the class OtherActivity extends Android’s Activity class, and you’re good to go.) In the example, the Intent class’s constructor takes two parameters — a context and a Java class.

  • startActivityForResult method not work from non Activity class becuase we can only override onActivityresult in Activity
  • @ρяσѕρєяK I just tried it and it works fine. Let me post some example code.
  • Thanks for your reply. Bascially reason for using Non-Activity class is that I want to encapsulate the whole process into a class(API) then anyone who wants to use this class can call its API. This API executes series of steps and some of them involves taking data from user in form of activity. Even if we forget about startActivityForResult all I want is data from a activity in the non activity class is this scenario not a valid one in android?
  • @RaghavSood : yes i agree with u , we must override onActivityResult in Activity instead of non activity class as OP asking
  • Yes, I figured that's what you meant but threw in my 2 cents. +1 for clarity :)
  • But you are passing an activity in the constructor, the op wants to do it w/o activity
  • just using the activity to get the fragment manager. Nothing special magic happens with it. I actually called this code from a fragment and cast to activity before calling. Havving a class that took fragment as input I couldn't call it from an activity so it wouldn't be reusable. It works otherwise when you just call getActivityForResult from a fragment the result would come back to the main activity. Maybe its fixed we are at what version N now. Maybe use this method and it helps you out. Good Luck