0

I have code in Java that hides the soft keyboard using the InputMethodManager. When I convert the code to Kotlin, the same code throws a NoMethodFound exception.

I can easily switch between the Java and Kotlin versions and demonstrate the correct behaviour in Java and incorrect behaviour in Kotlin.

Java code

            searchText.clearFocus();
            InputMethodManager imm = (InputMethodManager)dialog.getContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
            try {
                imm.hideSoftInputFromWindow(searchText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            } catch (Throwable t) {
                String stop = "here";
            }

Kotlin code

            searchText!!.clearFocus()
            val imm = dialog!!.context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
            try {
                imm.hideSoftInputFromWindow(searchText!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
            } catch (t: Throwable) {
                val stop = "here"
            }

The Java code exhibits the correct behaviour and dismisses the soft keyboard. The Kotlin code throws the exception

"java.lang.NoSuchMethodError: No virtual method hideSoftInputFromWindow(Landroid/os/IBinder;I)V in class Landroid/view/inputmethod/InputMethodManager; or its super classes (declaration of 'android.view.inputmethod.InputMethodManager' appears in /system/framework/framework.jar:classes2.dex)"

Gerald
  • 1
  • 1

2 Answers2

0

It look like this method not available in Context. Try use Context from your application Context. For getting Context of application do something like this or some googling about getting application in kotlin may help.

Firdavs Khodzhiev
  • 336
  • 2
  • 4
  • 18
  • The code in the original question runs in a dialog within an activity started as an intent from a main activity. Using your suggestion, I have determined that the application context is identical to the activity context but different from the dialog context. However, both contexts provide the same InputMethodManager. – Gerald Oct 12 '19 at 21:01
0

This is not an answer but a workaround. I refactored the Kotlin code back into Java and placed it as a static method in a helper class. The method is called from Kotlin.

public class DialogHelper {
public static void hideKeyboard(EditText searchText, Dialog dialog) {
    searchText.clearFocus();
    InputMethodManager imm = (InputMethodManager)dialog.getContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
    try {
        imm.hideSoftInputFromWindow(searchText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    } catch (Throwable t) {
        String stop = "here";
    }
}

}

Now the code works like it's supposed to: the soft keyboard is hidden and no exception is thrown.

I still wonder if anyone can shed any light on why this works and the straight Kotlin code does not.

Gerald
  • 1
  • 1