I have a fragment that implements one interface with one method. When I try to access the context in the method of this interface, the application crashes with a NullPointerException . What could be the problem?

 public class SomeFragment extends Fragment implements SomeInterface { @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return super.onCreateView(inflater, container, savedInstanceState); } @Override public void update(Object data) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { //do something } }); } } 
  • 3
    most likely the call to the update method occurs before the fragment attaches to activation - andreich

1 answer 1

And where is update called? Apparently, at this moment, the state of the fragment is invalid ( onAttach has not yet passed the call onAttach for example), checks and / or deferred calls are needed. If appropriate, you can use the Application context, or take onCreateView from container onCreateView