Search code examples
androidnullpointerexceptionimageviewandroid-actionbar-compat

setPadding on ImageView crashes activity


I use actionbarcompat to have an actionbar also on pre honeycomp devices.

As there is no space between the home icon and the title of the actionbar, I added this to my activites:

// add padding to the right of home item
ImageView view = (ImageView)findViewById(android.R.id.home);
view.setPadding(0, 0, 10, 0);

Actually the second line (setPadding) is causing the crash.

It is working fine on Jelly Bean devices. But I get a Null Pointer exception running this on e.g. Android 2.3 device.

This is the logcat output of the crash:

12-29 11:44:36.968: E/AndroidRuntime(329): FATAL EXCEPTION: main
12-29 11:44:36.968: E/AndroidRuntime(329): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.GetRichOrDieSmoking/com.GetRichOrDieSmoking.MainScreen}: java.lang.NullPointerException
12-29 11:44:36.968: E/AndroidRuntime(329):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
12-29 11:44:36.968: E/AndroidRuntime(329):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
12-29 11:44:36.968: E/AndroidRuntime(329):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
12-29 11:44:36.968: E/AndroidRuntime(329):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
12-29 11:44:36.968: E/AndroidRuntime(329):  at android.os.Handler.dispatchMessage(Handler.java:99)
12-29 11:44:36.968: E/AndroidRuntime(329):  at android.os.Looper.loop(Looper.java:123)
12-29 11:44:36.968: E/AndroidRuntime(329):  at android.app.ActivityThread.main(ActivityThread.java:3683)
12-29 11:44:36.968: E/AndroidRuntime(329):  at java.lang.reflect.Method.invokeNative(Native Method)
12-29 11:44:36.968: E/AndroidRuntime(329):  at java.lang.reflect.Method.invoke(Method.java:507)
12-29 11:44:36.968: E/AndroidRuntime(329):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-29 11:44:36.968: E/AndroidRuntime(329):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-29 11:44:36.968: E/AndroidRuntime(329):  at dalvik.system.NativeStart.main(Native Method)
12-29 11:44:36.968: E/AndroidRuntime(329): Caused by: java.lang.NullPointerException
12-29 11:44:36.968: E/AndroidRuntime(329):  at com.GetRichOrDieSmoking.MainScreen.onCreate(MainScreen.java:463)
12-29 11:44:36.968: E/AndroidRuntime(329):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
12-29 11:44:36.968: E/AndroidRuntime(329):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
12-29 11:44:36.968: E/AndroidRuntime(329):  ... 11 more

Solution

  • android.R.id.home was introduced only in API level 11. So the view could not be created in Android 2.3. Hence in the following line when you try to set padding on the null view you get NullPointerException.