0

In my fragment I call a method from my parentActivity which has a ViewPager with a FragmentStatePagerAdapter.

I read on some posts that casting an Activity can cause errors, but because I only have one parentActivity which manages all my fragments, I don't see why it would cause an error.

Method call in fragment

((MainActivity) getActivity()).getSDCardAccess();

Method in parentActivity

public void getSDCardAccess(){
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
    startActivityForResult(intent, REQUEST_EXTERNAL_ACCESS);
}
Peter Staranchuk
  • 1,343
  • 3
  • 14
  • 29
Vince VD
  • 1,506
  • 17
  • 38
  • 1
    If you are sure that your fragment will only be used by your mainActivity, I think there is no problem... – diAz Dec 09 '19 at 15:18
  • @diAz Ok thanks for clarifying. I was not sure because it seems that casting Activities is frowned upon in alot of posts. – Vince VD Dec 09 '19 at 15:20
  • However, it seems more interesting to use an interface if you plan to use your fragment with another activity: https://stackoverflow.com/a/42166370/7528285 – diAz Dec 09 '19 at 15:25
  • 2
    It isn't recommended because it tightly couples your `Fragment` to your `Activity` - my answer [here](https://stackoverflow.com/a/36360141/1219389) goes into more detail – PPartisan Dec 09 '19 at 15:27

1 Answers1

0

Since you have only one ParentActivitythat handles all the fragments in your application, it is possible to use the way you mentionned. But I would advice you to follow Google recommended way of using interfaces to allow Fragment to communicate up to it's Activity or else these classes will be coupled.

If you decide to follow up your approach, please consider that getActivity() may return null if the Fragment is associated with a Context.

M A
  • 21
  • 7