Soft keyboard that gets a NullPointerException when calling canvas.drawtext

I am working on SoftKeyboard where I need to display text on keys as shown below in red blocks

enter image description here

As indicated in this link and this link , I use the code below,

 protected void onDraw(Canvas canvas) {
        if (canvas != null) {
            super.onDraw(canvas);
        }

        Paint paint = new Paint();
        paint.setTextSize(15);
        paint.setColor(Color.RED);

        int x2 = 0;
        int y2 = 0;
        int width = 0;
        List<Key> keys = SoftKeyboard.currentKeyboard.getKeys();
        for(Key key: keys) {
        if(key.codes[0] == 113)
            x2 = key.x; // value of x2 = 0;
            y2 = key.y; // value of y2 = 0;
            width = key.width; // value of width = 32;
            canvas.drawText("1", x2 + (width/2), y2 + 5, paint); // getting null pointer exception here line 240
        }
    }

My stack trace is shown below

FATAL EXCEPTION: java.lang.NullPointerException com.example.android.softkeyboard.CandidateView.onDraw(CandidateView.java:240) com.example.android.softkeyboard.CandidateView.setSuggestions(CandidateView.java:279) com.example.android.softkeyboard.SoftKeyboard.setSuggestions(SoftKeyboard.java:597) com.example.android.softkeyboard.SoftKeyboard.updateCandidates(SoftKeyboard.java:582) com.example.android.softkeyboard.SoftKeyboard.onFinishInput(SoftKeyboard.java:260) android.inputmethodservice.InputMethodService.doFinishInput(InputMethodService.java:1543) android.inputmethodservice.InputMethodService.doStartInput(InputMethodService.java:1552) android.inputmethodservice.InputMethodService $InputMethodImpl.startInput(InputMethodService.java:390) android.inputmethodservice.IInputMethodWrapper.executeMessage(IInputMethodWrapper.java:158) com.android.internal.os.HandlerCaller $MyHandler.handleMessage(HandlerCaller.java:61) android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:153) android.app.ActivityThread.main(ActivityThread.java:5000) java.lang.reflect.Method.invokeNative( ) java.lang.reflect.Method.invoke(Method.java:511) com.android.internal.os.ZygoteInit $MethodAndArgsCaller.run(ZygoteInit.java:821) com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584) at dalvik.system.NativeStart.main( ) 10-19 13: 26: 04.844: E/Trace (17693): : (2)

, , , , - , canvas null.

, - , canvas null - .

: popupCharacters , 3 , ,

enter image description here

, .

+1
3

. , KeyboardView, LatinKeyboard, .

+1

, canvas null. , . :

if (canvas != null) {
    super.onDraw(canvas);
}

, canvas null, -? , , canvas null, .

+1

DO NOT need to draw it . There is an easy way to achieve this. See here for more details .

0
source

All Articles