3

I got a situation here .

I have FragmentActivty which holds a Fragment . when i click on a button in Fragment i am going to a Activty . when i reach the activity i do something which will affect the data displayed in Fragment where i came from. So in order to bring that changes in fragment i would like to give a callback from the Activity to Fragment. First i thought of implementing onActivityResult. But i realized it's not what i needed.

Is my approach is wrong?? Please guide me

MyActivity extends FragmentActivity

MyActivity holds

MyFragment extends Fragment

From here i'm going to

SecondActivity extends Activity

from SecondActivity i need to get a callback to MyFragment . Is there anything wrong with my approach ??

EDIT:

 public class MainActivity extends FragmentActivity {
    private FrameLayout frameLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        frameLayout = (FrameLayout) findViewById(R.id.framelayout);
         loadFragment();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);

        return true;
    }

    private void loadFragment() {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        MyFragment myFragment = new MyFragment();
        fragmentTransaction.add(R.id.framelayout, myFragment);
        fragmentTransaction.commit();

    }
}

MyFragment.java

public class MyFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_view, container, false);
        Button button = (Button) view.findViewById(R.id.button);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                callActivity();

            }
        });

        return view;
    }



    private void callActivity() {
        Intent intent = new Intent(getActivity(), SecondActivity.class);
        startActivityForResult(intent, 10);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//      super.onActivityResult(requestCode, resultCode, data);
        Log.e("MyFragment Inside", "Onresultttt");
        if (requestCode == 10) {
            if (resultCode == Activity.RESULT_OK) {
                Log.e("Result code", Activity.RESULT_OK + " okkk");
            }
            if (resultCode == Activity.RESULT_CANCELED) {
                Log.e("Result code", Activity.RESULT_CANCELED + "cancelll inside fragment");
            }
        }
    }
}

SecondActivity.java

public class SecondActivity extends Activity {
    private static final String TAG = "second activity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.secondactivity_view);
    }

    @Override
    public void onBackPressed() {
        // super.onBackPressed();
        Intent intent = new Intent();
        setResult(RESULT_CANCELED, intent);
        Log.e(TAG, "result setted");
        finish();

    }
}
edwin
  • 7,985
  • 10
  • 51
  • 82

2 Answers2

1

If I understand your situation correctly, then the correct way of handling the communication is to have SecondActivity pass back information to MyActivity, which will in turn configure it's instance of MyFragment directly. You don't want to be accessing Fragments from Activities unless the Fragment is attached to the Activity.

As for how to do the communication, as you suggested, one way of doing it would be through the use of startActivityForResult(). See this answer for more details: How to manage `startActivityForResult` on Android?

Just a note about startActivityForResult(). If you are calling it from the Fragment then your Fragment will receive the result, not your Activity. There are also some other issues with calling startActivityForResult() from a Fragment, so I would generally recommend that you instead call it from the Activity and therefore handle the result from the Activity.

Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, INTENT_CODE);

The best practice way of communicating from a Fragment to an Activity is by defining an Interface in the Fragment, which the Activity implements.

public class MyFragment extends Fragment {
    public interface MyFragmentListener() {
        public void onMyFragmentEvent();
    }

    public void startTheActivityForResult() {
        ((MyFragmentListener)getActivity()).onMyFragmentEvent();
    }
}

public class MainActivity extends FragmentActivity implements MyFragmentListener{
    @Override public void onMyFragmentEvent() {

    }
}

The Fragment then simply casts the reference to the Activity it is attached to, knowing that the Activity must implement the Listener, thus allowing you to reuse the Fragment in other Activities.

Community
  • 1
  • 1
TheIT
  • 11,919
  • 4
  • 64
  • 56
  • Well i tried this . But onActivityResult get triggered before going to secondActivty . when coming back to fragment nothing happens – edwin Nov 18 '13 at 04:34
  • Also the link onActivityResult is implemented in FragmentActivity . will this affect other fragments that used via FragmentActivity?? – edwin Nov 18 '13 at 04:36
  • In the onActivityResult(int requestCode, int resultCode, Intent data) method, are you checking that the resultCode is the same as what you set in the Intent (INTENT_CODE)? There may be other intents coming through which you'll want to handle differently. Also, check the edits I made to my post, you may be passing in a reference to the Fragment when you create the Intent, which would explain why your Activity's onActivityResult() it isn't being called. – TheIT Nov 18 '13 at 04:40
  • So you are suggesting me to handle the onActivityResult in FragmentActivity . and push data from FragmentActivity to the fragment i need callback. Correct me if i am wrong – edwin Nov 18 '13 at 04:41
  • Correct. Handle the Intent in the FragmentActivity. From the FragmentActivity you should have a reference to your Fragment so you can just call it directly to configure it. – TheIT Nov 18 '13 at 04:45
  • well i had posted my code . you can see i am passing getActivity() from Myfragment .Still i got invoke at Myfragment not in FragmentActivty? do you think if i change the callback to Fragmnet activty. it will work as you said – edwin Nov 18 '13 at 04:56
  • I believe you are correct and I was mistaken. The call to startActivityForResult must be called from the FragmentActivity(). I will edit my answer. – TheIT Nov 18 '13 at 04:59
  • well i don't think this what i needed . here you are mentioning how to get a call back from the FragmentActivity that holding MyFragment right ?? – edwin Nov 18 '13 at 05:13
  • Correct, this is one of the potential hazards of using startActivityFromResult from a Fragment. Another is that nested Fragments are simply not supported and can produce unexpected results. – TheIT Nov 18 '13 at 05:15
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/41379/discussion-between-theit-and-edwin) – TheIT Nov 18 '13 at 05:19
1

Refer this question it will help you understand what is happening: onActivityResult is not being called in Fragment

Community
  • 1
  • 1
Rajiv yadav
  • 823
  • 8
  • 24