Sarah Pöhler Sarah Pöhler - 3 months ago 32
Java Question

SetOnFocusChangeListener with NullpointerException

I have fragment A:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_main, container, false);
CustomKeyboard customKeyboard = new CustomKeyBoard(getActivity());

etAge = (EditText) getActivity().findViewById(;
return view;

And I have class B:

public class CustomKeyboard {

private Context context;

public CustomKeyboard (Context context) {
this.context = context;

private void hideKeyboard(View view) {
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
public void actionEt(Edittext edittext){
editText.setOnFocusChangeListener((view, hasFocus) -> {
if(!hasFocus) {
} else {

The Exception:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setOnFocusChangeListener(android.view.View$OnFocusChangeListener)' on a null object reference

What is the reason of the problem? Hope for some help.

NOW THE APP RUNS. But the Edittexts dont hide.


Your code:

etAge = (EditText) getActivity().findViewById(;

Is wrong because it inflates from an activity instead of the view it is located in. The cause is comparable to getting a Nullpointer when finding a view in a different layout

Correct code:

etAge = (EditText) view.findViewById(;

As this finds the EditText in the view instead of the activity(which has no defined view inflated)