Fragment getActivity returns null because onAttach not called yet, how to synchronize?

孤街浪徒 提交于 2019-12-12 02:09:28

问题


I have a customized Fragment tabulation application. At one moment I want to open one fragment when receiving such answer from server. And then call the processResult method inside this fragment. But I got null result from getActivity which I used inside the processing.

How to wait for the cycle to end to call the process method from my main?

Here is the code from main:

@Override
public void onDeleteReservation(final SCHttpResult result,
        final SCWebServiceError err) {
    final Fragment f = getCurrentFragment();
    if (f != null) {

        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                if (f instanceof MyTripsFragment) {
                    ((MyTripsFragment) f).processReservationCancel(result,
                            err);

                    if (err != null) {
                        if (err.getType() != SCWebServiceErrorType.SCWebServiceErrorTypeConfirmationNeeded) {
                            onSCError(err);
                        }
                    }
                }
            }
        });

        if (!(f instanceof MyTripsFragment)) {
            Fragment frag = new MyTripsFragment();
            replaceFragment(frag);
            ((MyTripsFragment)frag).processReservationCancel(result, err);
        }}}

If the fragment generating the application-server exchange is still displayed, all works fine, but if (there is an error (I have to add the if test on the error yet) AND the user has switched to another fragment) { I have to take him back to this fragment to deal with the error and ask him what he wants to do.}

In processReservationCancel I make a getActivity to retrieve the main function and display errors. That failed in this way:

06-17 15:16:57.580: E/SC - SCMainActivity(12692): Replace Fragmt: class com.snapcar.rider.fragment.MyTripsFragment
06-17 15:16:57.580: E/SC - MyTripsFragment(12692): Process Reservation Cancel
06-17 15:16:57.585: D/SC - BookingFormFragment(12692): BookingFormFragment-°°°°°° remove VIEW  °°°°°° 
06-17 15:16:57.585: D/SC - MyTripsFragment(12692): MyTripsFragment- result = {"confirmation_message":"\u00cates-vous s\u00fbr de vouloir annuler ? Des frais de r\u00e9servation de 10 \u20ac TTC vous seront factur\u00e9s."}
06-17 15:16:57.590: D/SC - SCBaseFragment(12692): SCBaseFragment-=== removeReq: tag_reservations_delete; removeLoading: true
06-17 15:16:57.590: D/SC - SCBaseFragment(12692): SCBaseFragment-=== cannot remove loading ===
06-17 15:16:57.590: E/SC - SCBaseFragment(12692): toggleLoading - null activity
06-17 15:16:57.590: E/SC - MyTripsFragment(12692): getActivity failed
06-17 15:16:57.605: D/SC - BookingFormFragment(12692): BookingFormFragment-°°°°°° remove VIEW  °°°°°° 
06-17 15:16:57.650: D/SC - MyTripsFragment(12692): MyTripsFragment-onAttach is CAAAAALLLED
06-17 15:16:57.650: E/SC - MyTripsFragment(12692): Fragment Mytrips created
06-17 15:16:57.670: D/AbsListView(12692): Get MotionRecognitionManager
06-17 15:16:57.670: D/SC - AnalyticsManager(12692): AnalyticsManager-tagScreen - MyTripsFragment starting
06-17 15:16:57.670: E/SC - MyTripsFragment(12692): onResume - start
06-17 15:16:57.670: E/SC - MyTripsFragment(12692): onResume - gonna start getMyTrips

As you can see, the main fonction is not waiting that the new fragment is done with its creation to launch processReservationCancel() and thus it fails.

Any ideas on how to do taht?

PS: I cannot easily give the argument for processReservationCancel via bundle + flag as it is not String or boolean but Http response and errors.


回答1:


I use a dirty trick like this (pseudocode)

private YourType pendingActionParams;

public void yourMethod(YourType parameters){
    if(isVisible()){
        performAction(parameters);
    }else{
        pendingActionParams = parameters;
    }
}

@Override
public void onActivityCreated (Bundle savedInstanceState){
    if(pendingActionParams != null){
        performAction(pendingActionParams);
        pendingActionParams = null;
    }
}



回答2:


So I used this way and it seems to work fine:

                    int i = 0;
                while (frag.getActivity() == null && i < 300) {
                    Dbg.d(TAG, " ---------- Sleeping while ");
                    i++;
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                ((MyTripsFragment)frag).processReservationCancel(result, err);

The answer from rciovati looks better to me as it does not use sleep. In my case, the while loop is called only once, sometimes twice, so it is very fast but still...



来源:https://stackoverflow.com/questions/17148575/fragment-getactivity-returns-null-because-onattach-not-called-yet-how-to-synchr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!