1

I have a tabbed interface that has two fragments (one for each tab). Once I leave one of the tabs I want the data input there to be passed to the other tab. However there seems to be error when using these methods in my main activity:

public void setAddresses(String[] addr)
{
    addrArray = addr;
}

public String[] getAddressArray()
{
    if(addrArray == null)
    {
      return null;
    }

    //Else return the array
    return addrArray;


}

One fragment is sending data using setAddresses via it's onPause method and the new tab/fragment that is selected is retrieving the data using it's onResume method.

However there seems to be some sort of lag between these fragments. When going to the new fragment getAddressArray returns null, but if I force it to call it's onResume method again then getAddressArray (correctly) returns an array. How can I avoid this split second lag?

2 Answers 2

2

There are certain circumstances where onPause/onResume won't get called at all. A ViewPager is an example, as the pages either side of the visible page are kept in an active state. I'm not 100% sure if this applies to tabs as I've not used them for ages, but it may be the case.

The approach for communication here is not really correct and a better way to do it would be to use a listener to communicate changes up to the activity, then for the activity to communicate relevant changes back down to other fragments.

Refer to this page in the docs for more info: http://developer.android.com/training/basics/fragments/communicating.html

2
  • So basically have a listener for my UI widgets to pass the data to the activity as often as possible?
    – jrowe08
    Feb 1, 2014 at 22:34
  • Well, be careful not to spam your activity with callbacks, but at least when relevant events are triggered within your fragment it might be a good time to populate changes up to your activity.
    – Philio
    Feb 1, 2014 at 22:39
1

The correct and good way as explained in the SDK Article

1.Activity-to-Fragment

The host activity can deliver messages to a fragment by capturing the Fragment instance with findFragmentById() or findFragmentBy(), then directly call the fragment's public methods. your Fragment can easily check if parent Activity implements this interface, so Fragment will be able to communicate its needs,

2.Fragment-to-Activity

To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the Activity. The Fragment captures the interface implementation during its onAttach() lifecycle method and can then call the Interface methods in order to communicate with the Activity.

Read the SDK article for detailed Example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.