1

From a file picker library on github,

When starting the file picker this code gets called, but there is another method which is the same but uses either getActivity() or getContext() depending on the build version:

I'm not sure which one i should use, what is the difference between getActivity and getContext?

First method:

public void start(@NonNull Activity activity, int requestCode) {
        activity.startActivityForResult(createIntent(activity), requestCode);
}

Same method but different Context depending on build version:

@RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
    public void start(@NonNull Fragment fragment, int requestCode) {
        Context context;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            context = fragment.getContext();
        } else {
            context = fragment.getActivity();
        }
        if (context != null) {
            fragment.startActivityForResult(createIntent(context), requestCode);
        }
}
Vince VD
  • 1,506
  • 17
  • 38
  • 1
    If you're using Support Library / AndroidX Fragments (which you should, as framework Fragments should not be used), they return the same object. – ianhanniballake Dec 17 '19 at 01:15

1 Answers1

0

TLDR; getActivity was added in API 11 getContext was added in API 23. You should use the one that applies to your need. First, the first method is calling startActivityForResult on an Activity, where the second method is calling startActivityForResult on a Fragment. So if you are in an Activity, use the first method; otherwise, use the second method.

Aside from that, the reason that there is a check is because of when the methods were added to the Fragment class. getContext wasn't added until API 23; whereas, getActivity was added in API 11. Source As a note, both of these have been deprecated as of API 28.

If you look at the different methods, you'll notice that getContext returns Context and getActivity returns Activity. They are used for similar things, but the difference between the 2 is that Context is the base class for Activity and Application. Often times, getting the Activity will allow you to use the Context but sometimes you might need (or want) the Application Context. You can reference this link for more information on the differences between the 2 Context instances.

BlackHatSamurai
  • 23,275
  • 22
  • 95
  • 156
  • Note that even for framework Fragments (where the API level difference matters), these methods still give you back the exact same object, so your last paragraph doesn't really apply as the `Context` you get back is still, in reality, an `Activity` for all practical purposes. – ianhanniballake Dec 17 '19 at 02:33