lost baby
lost baby

Reputation: 3268

How to initialize OnFragmentInteractionListener without onAttach(Context context) for use with FirebaseUI

I am trying to make my app (which uses com.firebase.ui and com.firebase.ui.auth) work on an old api level 15 (4.0.4) device. First I use the manifest tag:

 <uses-sdk tools:overrideLibrary="com.firebase.ui, com.firebase.ui.auth"/> 

but then I found that on the old device the onAttach(Context...) method was not getting called.
So I read some posts about it and this is what I came up with based on what I read:

  @SuppressWarnings("deprecation")
    @Override
    public void onAttach(Activity activity) {

        Log.d(TAG, "onAttach Activity 1A "  );
        super.onAttach(activity);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            setmListener(activity );
        }

    }

    private void setmListener(Context context){
        Log.d(TAG, "setmListener 1  "  );
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onAttach(Context context) {
        Log.d(TAG, "onAttach Context 1 "  );
        super.onAttach(context);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            setmListener(context);
        }
    }

When the code runs on the old api 15 device the onAttach(Context context) method does not get called just the onAttach(Activity activity) method (same for an emulator running Lollipop).

 D/StSt_MaxWListFrag: onAttach Activity 1A 
 D/StSt_MaxWListFrag: setmListener 1  

But on the device with M both methods run but the setmListener only gets called once as expected:

D/StSt_MaxWListFrag: onAttach Context 1 
D/StSt_MaxWListFrag: onAttach Activity 1A 
D/StSt_MaxWListFrag: setmListener 1  

So - so far it seems to be working, no problems so far. I am just wondering if there is something I am missing here - is this approach going to cause me headaches down the road or is it bad practise - maybe inefficient? Thanks for any insight!

Upvotes: 1

Views: 107

Answers (1)

azizbekian
azizbekian

Reputation: 62189

As you can see in docs, onAttach(Activity) is deprecated from API 23 upwards, instead onAttach(Context) is used. onAttach(Activity) won't call new onAttach(Context) automatically.

So, in order to support all versions of API and to perform attaching actions only once, you have to separate attach logics in a function and call that function from both callbacks performing a check:

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    attached();
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        attached();
    }
}

Upvotes: 0

Related Questions