How to return requestCode from child activity to parent activity by default

I use the onActivityResult method in my ParentActivity , and I call ChildActivity from my ParentActivity in a Button click. In my ChildActivity , when I click the default back button, and when it goes to my ParentActivity , I don't get my requestCode , which I set in my ChildActivity in onStop() method, with:

setResult (2);

How can I return my requestCode from my ChildActivity to ParentActivity when I click the back button.

Please help me.

Thanks in advance.

Here is the ma code:

  //Parent activity protected void onActivityResult(int requestCode, int resultCode, Intent data) { Toast.makeText(this,resultCode+"", Toast.LENGTH_LONG).show(); if(resultCode==2){ finish(); } } //Child activity protected void onStop() { setResult(2); super.onStop(); } protected void onPause() { setResult(2); super.onStop(); } 
+4
source share
2 answers

This code can be used in child activity.

 @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK){ setResult(RESULT_OK); finish(); // If you have no further use for this activity or there is no dependency on this activity return true; } return super.onKeyDown(keyCode, event); } 

This piece of code will return the result code ok from your child activity to the parent activity.

Now in your parenting activity in

 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case 2: if(resultCode == -1){ // Here you write your code which you have to write on result receive } break; default: break; } super.onActivityResult(requestCode, resultCode, data); } 

Let me know if this helps you.

+2
source

Better to override onBackPressed () than to override onKeyDown ()

0
source

Source: https://habr.com/ru/post/1402609/


All Articles