Ziggy
Ziggy

Reputation: 541

onActivityResult NOT called in MainActivity from previous Activity

I know this is a basic question and I have seen multiple answers on it in stackoverflow but I seem to be stuck still. The onActivityResult is just not being called.

Here is my code:

1> In MainActivity I have onActivityResult

public class MainActivity extends AppCompatActivity
        implements MasterListFragment.OnImageClickListener {

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.v(LOG_TAG, "Entering onActivityResult");

    }
}

2> In my second activity I have this

@Override
    public void onBackPressed() {

        Intent data = new Intent();
        data.putExtra("myData1", "Data 1 value");
        data.putExtra("myData2", "Data 2 value");
        setResult(Activity.RESULT_OK, data);
        finish();
    }

I do a Log and the Log statement is not displayed in the LOGCAT

Upvotes: 0

Views: 969

Answers (3)

KKumar Technologies
KKumar Technologies

Reputation: 267

Use MainActivity.this.startActivityForResult(intent, REQUEST_CODE);

Upvotes: 0

Faiz Mir
Faiz Mir

Reputation: 609

On Your MainActivity Open A Intent Like this:

Intent intent = new Intent(this,"Your c class name.class");
 startActivityForResult(intent, 1);

and in your Second Activity do this:

Intent returnIntent = new Intent();
  returnIntent.putExtra("result",result);//your changed value here
  setResult(Activity.RESULT_OK,returnIntent);
  finish();

The again in your MainActivity do this

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {

if (requestCode == 1) {
    if(resultCode == Activity.RESULT_OK){
        String result=data.getStringExtra("result");

        //you will get the changed data here
      }
      if (resultCode == Activity.RESULT_CANCELED) {
          //Write your code if there's no result
     }
  }
  }//onActivityResult

Upvotes: 2

Jaydip Kalkani
Jaydip Kalkani

Reputation: 2607

For getting result back in OnActivityResult you should use startActivityForResult(Intent,REQ_CODE) method for starting your second activity.

Upvotes: 2

Related Questions