Search code examples
javaandroidonactivityresult

onActivityResult return data from fragment to activity


I Have an activity A that opens an activity B using startActivityForResult.

Now in activity B it's an activity fragment holder as well it contains an ActionBar with menu items.

Now whenever I press action bar button in activity B it should return data from selected fragment of an activity B not to its holder instead it should return data to activity A because it's the one who did the launch.

So it's basically passing data fragment (inside activity B) to activity B then to Activity A.

I am trying hopelessly to find a way to solve it. Is there any possible way to do it?


Solution

  • Disclaimer there are many ways, this is the one I prefer, not the best ever and not the perfect one, I just like this.

    The easiest way, in my opinion, is to pass the data from Fragment inside B to ActivityB, then from ActivityB to ActivityA.

    Step 1 to pass data from Fragment to container activity you have many ways; the one I usually use is to use an Interface:

    Create interface for ActivityB

    public interface IActivityB {
        void setDataAAndFinish(whateverType data);
    }
    

    Implement interface in your activityB

    public class InterventoActivity extends AppCompatActivity implements IInterventoActivity {
    
        @Override
        protected void onResume() {
            super.onResume();
        }
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        }
    
        private Bundle dataA = null;
        @Override
        public void setDataAAndFinish(whateverType data) {
            dataA = data;
            Intent intent = new Intent();
            intent.putExtra("data", data)
            setResult(RESULT_OK, intent);        
            finish();
        }
    }
    

    Set activityA to request and accept return from ActivityB

    first, start activityB for result and not normally

    Intent i = new Intent(this, ActivityB.class);
    startActivityForResult(i, 1);
    

    Then read result

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
             if(resultCode == RESULT_OK) {
                 whateverType data = data.getStringExtra("data");
             }     
        }
    } 
    

    Now from fragment

    ((IActivityB)getActivity()).setDataAAndFinish(myDatas);