onActivityResult NOT called in MainActivity from previous Activity

我是研究僧i 提交于 2020-01-06 06:39:07

问题


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


回答1:


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




回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/52361204/onactivityresult-not-called-in-mainactivity-from-previous-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!