Sarah Pöhler Sarah Pöhler - 1 month ago 17
Java Question

SetOnFocusChangeListener with NullpointerException

I have fragment A:

@Override
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(R.id.etAge);
customKeyboard.actionEt(etAge);
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) {
hideKeyboard(view);
} 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.

EDIT:
NOW THE APP RUNS. But the Edittexts dont hide.

Answer

Your code:

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

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(R.id.etAge);

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