8

In my app I got to a point where, in landscape mode, I need to attach two fragments. In order to do that, the second fragment needs to wait until the first fragment has been attached (added), before it's being added. The reason for it is that the first fragment needs to execute a function that the second fragment needs. I managed to do that via a thread, but in this case it only waits the amount of time indicated, before attaching the second fragment, and in case the first fragment isn't attached in the time given, the app will crush because the second fragment doesn't have the necessary data.

Any better practices (examples) then the code below (like waiting until the first fragment is attached, and no on a certain time interval) ? :

getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.mainContent, fragment).commit();
        Thread thread = new Thread() {
            @Override
            public void run() {
                try {
                    synchronized (this) {
                        wait(1000);
                    }
                } catch (InterruptedException e) {

                }
                if (isLandscape) {
                openSecondFragment(mIndex, R.id.rightConent);
                }
            }
        };
        thread.start();

Much appreciated.

The handler i need to be executed in the first fragment:

@SuppressLint("HandlerLeak")
protected void loadAccountList() {

    LoadAccountList loadAccountListThread = new LoadAccountList(new Handler() {

        @SuppressWarnings("unchecked")
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case LOAD_SUCCESSFUL_CODE:
                items = (ArrayList<Account>) msg.obj;
                break;
            case LOAD_FAILED_IOEXCEPTION_CODE:
                getActivity().showDialog(ERROR_DIALOG);
                break;
            default:
                break;
            }
        }
    });
    loadAccountListThread.start();

4 Answers 4

8

Fragments lifecycle works in your favor here. According to the documentation the method onStart() is "Called when the Fragment is visible to the user", so I suggest you do something like this in your first fragment class:

public void onStart() {

    super.onStart();
    ((MainActivity)getActivity()).loadSecondFragment();
}

And in your Activity:

public void loadSecondFragment() {
    if (isLandscape) {
        openSecondFragment(mIndex, R.id.rightConent);
    }    
}

And voilá! Try any of the lifecycle methods and see which one works best for your purpose.

15
  • Thanks for your answer. I tried your suggestions but the result is the same. The second fragment is added too soon, therefore the app crashes because it hasn't the necessary data from the first fragment.
    – Phantom
    Feb 11, 2015 at 15:03
  • Just one remark, call ((MainActivity)getActivity()).loadSecondFragment(); after you executed your function. not just randomly in some lifecycle method.
    – SnyersK
    Feb 11, 2015 at 15:03
  • What @SnyersK says is very important, where do you call that necessary function in your first fragment?
    – Carlos J
    Feb 11, 2015 at 15:05
  • To be more specific, the first fragment contains a thread that interrogates a server, and I need that information from the server on the second fragment.
    – Phantom
    Feb 11, 2015 at 15:06
  • Ok, so just wait till the server response and after that you call ((MainActivity)getActivity()).loadSecondFragment(); and that should do the trick
    – Carlos J
    Feb 11, 2015 at 15:08
2

You can observe Fragments creation by registering FragmentLifecycleCallbacks in FragmentManager.

Implement callbacks of Your interest such as onFragmentAttached, onFragmentResumed.

0

onCreateView is called when Fragment is created

public static class CustomFragment extends SupportMapFragment{

        public CustomFragment() {}

        @Override
        public View onCreateView(LayoutInflater arg0, ViewGroup arg1, Bundle arg2) {
            return super.onCreateView(arg0, arg1, arg2);

        }
}
3
  • Yes, but I need to access this from the activity somehow. I tried something like: fragment.isAdded() instead of the thread, but in this case it returns null every time.
    – Phantom
    Feb 11, 2015 at 14:48
  • you probably want to wait until onAttach. Then see developer.android.com/training/basics/fragments/… on how to notifiy the activity that the fragment is ready
    – njzk2
    Feb 11, 2015 at 14:50
  • Ok, add a listener in the constructor and call it in onCreateView Feb 11, 2015 at 14:51
0

first off @SuppressLint("HandlerLeak") is bad. If you're not carefull with leaks, you're memory is gonna fill up.

My solution (it's a personal preference)

I like to use Otto to pass around messages while still having loose coupling. It allows you to set-up an EventBus to which different classes can simply register and receive the events they want. In this case, you could make a helper class which loads the data and fires an event when it has received the data (or an error). Then you catch this in your second fragment and populate your list. (in the meantime you can show an indefinite progressbar or something)

This way, you don't have to wait for the data to be received before you load your fragment.

You can find the documentation here: https://github.com/square/otto

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.