0

I have code, that gets Menu Item and changes icon color. on Android 8.1 it's working fine, but when I tested it on android 4.1.1, app crashes.

Drawable drawable = menuos.getItem(1).getIcon();
                    if(drawable != null) {
                        drawable.mutate();
                        drawable.setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP);
                    }

Menuos:

Menu menuos = menu

It is located in onCreateOptionsMenu

Logcat:

07-28 11:20:15.794 3443-3443/com.developerfromjokela.edison E/AndroidRuntime: FATAL EXCEPTION: main
    java.lang.NullPointerException
        at com.developerfromjokela.edison.MainActivity$5.onPageStarted(MainActivity.java:223)
        at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:318)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4745)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
        at dalvik.system.NativeStart.main(Native Method)

onCreateOptionsMenu:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    menuos = menu;

    return super.onCreateOptionsMenu(menu);

}

1 Answers1

0

If this is the line that throws NPE:

Drawable drawable = menuos.getItem(1).getIcon();

then there are 2 options:
menuos is null or menuos.getItem(1) is null

so do this before the above line:

Log.i("menuos_isnull", menuos == null);
if (menuos != null) {
    Log.i("Item1_isnull", menuos.getItem(1) == null);
}

and see what'rs printed. This is debugging and you must use it more often.