Fragment not attached to a context

Create a fragment instance is not enough.
It needs to be attached to Activity through a transaction:

getFragmentManager()
    .beginTransaction()
    .replace(R.id.container_layout, fragment)
    .commit();

After a successful commit, onAttach method in the fragment is called, the view is created and then you can interact with its views.

In your case, create the fragment instance and attach it in activity onCreate, then call sortByPopularity later in a click event.

Read more about fragment life cycle: https://developer.android.com/guide/components/fragments


Kotlin:

My problem happened with getString()

Changing it to context.getString() solved it


In my case, this problem occurred when I was calling getString()

changing this calls to getActivity().getString() solved the problem.


Using commit() can not solve the problem, we should try to find the solution in the source code of Fragment.

So, consider from the error stack you provided, the requireContext() in Fragment was:

    public final Context requireContext() {
        Context context = getContext();
        if (context == null) {
            throw new IllegalStateException("Fragment " + this + " not attached to a context.");
        }
        return context;
    }

This means the system will check the Context from getContext(), if it's null, the exception will be thrown.

So, to avoid this problem, we can check the result of getContext() before do our business.