3

I have a LoginActivity which extends AccountAuthenticatorActivity. This activity has several fragments which are androidx.fragment.app.Fragments. The Problem is from fragments I can't call:

((LoginActivity) getActivity()).setAccountAuthenticatorResult(intent.getExtras());

Because LoginActivity extends AccountAuthenticatorActivity which extends android.app.activity but getActivity() returns androidx.fragment.app.FragmentActivity which can't be cast to my LoginActivity. If I use android.app.Fragment I can't use methods like getViewLifecycleOwner() of androidx Fragment. So what's the solution here?

Update:

Although delegation pattern could solve this problem, this question has an interesting answer here:

AccountAuthenticatorActivity and fragments

Sina
  • 2,683
  • 1
  • 13
  • 25

3 Answers3

4

I think one solution is delegation pattern. It is a technique where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behavior to an associated object. For implementation of delegation pattern you should use an interface like this:

public interface Delegate extends Serializable {
    void setResult(Intent intent);
}

then AccountAuthenticatorActivity should implements this interface and inside setResult call the method.

 public void setResult(Intent intent){
        setAccountAuthenticatorResult(intent.getExtras());
 }

your Fragment class should be like this:

public  class MYFragment extends Fragment {

    Delegate delegate;

    public static MYFragment newInstance(Delegate delegate){
        MYFragment fragment = new MYFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("key", delegate);
        fragment.setArguments(bundle);
        return  fragment;
    }



    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup      container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.my_fragment,container,false);
        delegate = (Delegate) getArguments().getSerializable(<your_key>);
        delegate.setResult(<your_intent>);

        return view;
    }
Alireza Barakati
  • 1,016
  • 2
  • 9
  • 23
1

I accepted the delegation pattern answer, but I've still had the problem with androidx fragments in AccountAuthenticatorActivity. I think I should've used same pattern with AppCompatDelegate. For anyone facing the same issue I suggest this answer: AccountAuthenticatorActivity and fragments

Sina
  • 2,683
  • 1
  • 13
  • 25
0

migrate whole project to androidx

Please migrate whole project to androidx as screenshot above

Community
  • 1
  • 1
Edgar
  • 860
  • 1
  • 17
  • 38