문제

When I try to run this line in order to hide the keyboard (I get the InputMethodManager):

this.context = context;
InputMethodManager mgr = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); //this line crashes the app

What should I do to fix it? (I am running it from a fragment by the way)

Crash Log:

11-03 16:20:26.700: D/AndroidRuntime(2809): Shutting down VM
11-03 16:20:26.700: W/dalvikvm(2809): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
11-03 16:20:26.710: E/AndroidRuntime(2809): FATAL EXCEPTION: main
11-03 16:20:26.710: E/AndroidRuntime(2809): java.lang.NullPointerException
11-03 16:20:26.710: E/AndroidRuntime(2809):     at co.emuze.tabtest1.Tab1$1.onClick(Tab1.java:32)
11-03 16:20:26.710: E/AndroidRuntime(2809):     at android.view.View.performClick(View.java:4084)
11-03 16:20:26.710: E/AndroidRuntime(2809):     at android.view.View$PerformClick.run(View.java:16966)
11-03 16:20:26.710: E/AndroidRuntime(2809):     at android.os.Handler.handleCallback(Handler.java:615)
11-03 16:20:26.710: E/AndroidRuntime(2809):     at android.os.Handler.dispatchMessage(Handler.java:92)
11-03 16:20:26.710: E/AndroidRuntime(2809):     at android.os.Looper.loop(Looper.java:137)
11-03 16:20:26.710: E/AndroidRuntime(2809):     at android.app.ActivityThread.main(ActivityThread.java:4745)
11-03 16:20:26.710: E/AndroidRuntime(2809):     at java.lang.reflect.Method.invokeNative(Native Method)
11-03 16:20:26.710: E/AndroidRuntime(2809):     at java.lang.reflect.Method.invoke(Method.java:511)
11-03 16:20:26.710: E/AndroidRuntime(2809):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-03 16:20:26.710: E/AndroidRuntime(2809):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-03 16:20:26.710: E/AndroidRuntime(2809):     at dalvik.system.NativeStart.main(Native Method)

Full on click method:

public void onClick(View v) {
                text1.setText(editText1.getText().toString());
                InputMethodManager mgr = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                mgr.hideSoftInputFromWindow(editText1.getWindowToken(), 0);
            }
도움이 되었습니까?

해결책

It would appear context is null - you show the line this.context = context, and if the right hand side context is not a variable local to that method you're doing nothing. I think what you may be looking for is context = getApplicationContext()

다른 팁

Dont forget to use try catch blog because in case when your keyboard not open and if you use key key board hide code app crashed

User below code in Fragment

 try {
            InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        } catch (Exception e) {
            // TODO: handle exception
       }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top