36

I get a null pointer exception at this row:

public void hideKeyboard(){ 
InputMethodManager inputManager = (InputMethodManager)            
            this.getSystemService(Context.INPUT_METHOD_SERVICE);    
inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),      
            InputMethodManager.HIDE_NOT_ALWAYS);
}

This is called from the following method:

@Override
public void onBackPressed() {
    super.onBackPressed();
    hideKeyboard();
}

This is in the only activity. The back button is pressed from a fragment.

STACK:

09-28 19:14:40.301: E/InputEventSender(30324): Exception dispatching finished signal.
09-28 19:14:40.301: E/MessageQueue-JNI(30324): Exception in MessageQueue callback: handleReceiveCallback
09-28 19:14:40.325: E/MessageQueue-JNI(30324): java.lang.NullPointerException
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at com.example.ecohelp.MainActivity.hideKeyboard(MainActivity.java:75)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at com.example.ecohelp.MainActivity.onBackPressed(MainActivity.java:31)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.app.Activity.onKeyUp(Activity.java:2159)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.KeyEvent.dispatch(KeyEvent.java:2647)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.app.Activity.dispatchKeyEvent(Activity.java:2389)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1860)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:3791)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3774)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3483)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3540)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3516)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$ImeInputStage.onFinishedInputEvent(ViewRootImpl.java:3666)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.inputmethod.InputMethodManager$PendingEvent.run(InputMethodManager.java:1982)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.inputmethod.InputMethodManager.invokeFinishedInputEventCallback(InputMethodManager.java:1698)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.inputmethod.InputMethodManager.finishedInputEvent(InputMethodManager.java:1689)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.inputmethod.InputMethodManager$ImeInputEventSender.onInputEventFinished(InputMethodManager.java:1959)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.InputEventSender.dispatchInputEventFinished(InputEventSender.java:141)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.os.MessageQueue.nativePollOnce(Native Method)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.os.MessageQueue.next(MessageQueue.java:132)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.os.Looper.loop(Looper.java:124)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.app.ActivityThread.main(ActivityThread.java:5103)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at java.lang.reflect.Method.invokeNative(Native Method)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at java.lang.reflect.Method.invoke(Method.java:525)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at dalvik.system.NativeStart.main(Native Method)
Ahmed Ekri
  • 4,601
  • 3
  • 23
  • 42
basickarl
  • 37,187
  • 64
  • 214
  • 335

15 Answers15

53

I just need to check if there is a focused view before hiding the keyboard.

For example, if you have an EditText in your activity or fragment, it'll probably be the focused view. When the EditText isn't focused anymore, getCurrentFocus() may return null (unless some other view is focused).

void hideKeyboard() {
    InputMethodManager inputManager = (InputMethodManager) getActivity().getSystemService(
            Context.INPUT_METHOD_SERVICE);
    View focusedView = getActivity().getCurrentFocus();
    /*
     * If no view is focused, an NPE will be thrown
     * 
     * Maxim Dmitriev
     */
    if (focusedView != null) {
        inputManager.hideSoftInputFromWindow(focusedView.getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);
    }
}
Maksim Dmitriev
  • 5,985
  • 12
  • 73
  • 138
34

As CommonsWare mentioned, the getCurrentFocus() is null, since there is no View component inside the current Activity holding the focus.

If you already have a view in your Activity, use it to get the window token. For example, if I have a Button component:

inputManager.hideSoftInputFromWindow(myButton.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

Or even worse, if I do not have any view already in my Activity, I could do this:

inputManager.hideSoftInputFromWindow(new View(this).getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

This would solve your problem of NPE, but I hope you find the description useful.

One more thing about keyboards is that when user presses the back button while the keyboard is visible, the keyboard receives and consumes the back key press to hide itself. Or at least most keyboards behave that way.

Armin
  • 1,807
  • 20
  • 21
  • 1
    "new View(this).getWindowToken()" always returns null for me. However, using an existing view to get the windowToken works. – Steve B Mar 06 '15 at 06:59
27

Everybody above correctly pointed that the getWindowToken() was returning null.

I was using the default code getCurrentFocus().getWindowToken() to hide keyboard when I encountered the same issue.

I then realized that as there's no View obtaining the focus I got the NullPointerException.

We can change the above to:

anyView.getWindowToken()

where anyView is simply any view in your layout.

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
Atul O Holic
  • 6,692
  • 4
  • 39
  • 74
  • 1
    I had a lot of problems with getCurrentFocus, some times plainly didnt work, until I found getWindowsToken, works every time – cutiko Mar 26 '16 at 19:19
  • 1
    Thanks, It helped. I was using a base class and hideSoftKeyboard() method was in that class. So, I'd to use getWindow().getDecorView().getWindowToken() – Anu Bhalla Feb 07 '19 at 05:36
12

If you want to hide keyboard when touching in the screen, use the below code

       @Override
public boolean onTouchEvent(MotionEvent event) {
    InputMethodManager imm = (InputMethodManager)this.getSystemService(Context.
            INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(this.getWindow().getDecorView().getRootView().getWindowToken(), 0);
    return true;
}

If you want to do this in specific view (EditText)

      public void  hideKeyBoard(EditText edt) {
    InputMethodManager imm = (InputMethodManager)this.getSystemService(Context.
            INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(edt.getWindowToken(), 0);

}

or you can use any View.

To get the current view

    imm.hideSoftInputFromWindow(this.getWindow().getDecorView().getRootView().getWindowToken(), 0);
sreenadh
  • 185
  • 1
  • 11
9

This works for me. Simply add the getWindow().getDecorView().getRootView().getWindowToken() following instead of using getCurrectFocus(). After that You can use this method for any where in your activity.

public static void hideSoftKeyboard(Activity activity) {
        InputMethodManager inputMethodManager =
                (InputMethodManager) activity.getSystemService(
                        Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(
                activity.getWindow().getDecorView().getRootView().getWindowToken(), 0);
    }
Nuwan Withanage
  • 393
  • 7
  • 19
7

I had the same issue where getCurrentFocus() was returning null. So this method worked for me, and I would just call it on my onClick to hide the keyboard if its shown or still not throw a null pointer exception even if the keyboard was not shown:

public void hiddenInputMethod() {

    InputMethodManager imm = (InputMethodManager) getSystemService(MyActivity.this.INPUT_METHOD_SERVICE);
    if (getCurrentFocus() != null)
        imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
Richmond
  • 235
  • 3
  • 4
3

The problem happens when there is no element focused, si it is enough with this validation:

if(activity.getCurrentFocus() != null)
{
    InputMethodManager inputMethodManager =
    (InputMethodManager) activity.getSystemService(
    Activity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(
    activity.getCurrentFocus().getWindowToken(), 0);
}
Alejandro Luna
  • 161
  • 1
  • 2
2

Use this if you are getting error : Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.IBinder android.view.View.getWindowToken()' on a null object reference


InputMethodManager inputMethodManager = (InputMethodManager) MainActivity.this.getSystemService(Activity.INPUT_METHOD_SERVICE);

   if(MainActivity.this.getCurrentFocus() != null)
        {
         inputMethodManager.hideSoftInputFromWindow(MainActivity.this.getCurrentFocus().
getWindowToken(), 0);
        }
  • This is not related to OP problem – ρяσѕρєя K Jun 16 '16 at 06:09
  • If the error is related to getWindowToken() pointing to null then this could work. If the activity get paused then when it resumes then it could not have any view focused 'getCurrentFocus()' so it indicates that we are applying getWindowToken() on null. – Manvendra Priyadarshi Jul 31 '18 at 20:00
1

The main problem is in

getCurrentFocus().getWindowToken()

Here getcurrentFocus() is the issue. This problem can be solved easily through providing a valid view residing on your current screen like

yourButtonOnScreen.getWindowToken()

That button wo'nt be null as that is showing on your screen so it will resolve the issue.

Still if you do'nt have any valid view on your screen the just replace

getCurrentFocus().getWindowToken()...

with

//in case of fragment

new View(getActivity()).getWindowToken()

//in case of activity

new View(this).getWindowToken()

hope this will resolve the issue..good luck!

Ali Nawaz
  • 2,016
  • 20
  • 30
1

I was facing the same issue while hiding the keyboard , i found the simple solution by making root view of layout focusable in touch mode.

<RelativeLayout xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:id="@+id/rlSignActivity"
android:focusableInTouchMode="true"
xmlns:android="http://schemas.android.com/apk/res/android" >
    .......
</RelativeLayout>
Apoorv Singh
  • 1,295
  • 1
  • 14
  • 26
1

It can show error if instance of InputMethodManager is null. Try the below code it worked for me.

void hideKeyboard() {
InputMethodManager inputManager = (InputMethodManager) 
getActivity().getSystemService(
        Context.INPUT_METHOD_SERVICE);
View focusedView = getActivity().getCurrentFocus();

if (focusedView != null) {

    try{
    assert inputManager != null;
    inputManager.hideSoftInputFromWindow(focusedView.getWindowToken(),
            InputMethodManager.HIDE_NOT_ALWAYS);
}catch(AssertionError e{
     e.printStackTrace();
    }
  }
}
Neeraj Sewani
  • 3,952
  • 6
  • 38
  • 55
0

The warning stoped after I checked that the Input Manager was also != null

View view = this.getCurrentFocus();
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    if (view != null && imm != null) {
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
Vega
  • 27,856
  • 27
  • 95
  • 103
0
void hideKeyboard() {

InputMethodManager inputManager = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
View focusedView = getActivity().getCurrentFocus();
      
if (focusedView != null) {

inputManager.hideSoftInputFromWindow(focusedView.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);

    }
}
Dr Mido
  • 2,414
  • 4
  • 32
  • 72
-2

Just use this one:

public void hideKeyboard(View v){ 
  InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
  imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
CSchulz
  • 10,882
  • 11
  • 60
  • 114
Govtart
  • 332
  • 1
  • 9
-3

try this:

public void hideKeyboard(){ 
InputMethodManager inputManager = (InputMethodManager)            
            this.getSystemService(Context.INPUT_METHOD_SERVICE);    
inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
}
Ahmed Ekri
  • 4,601
  • 3
  • 23
  • 42