ClassCastException in android (pre 3.0) when loading Drawable

I was trying to load a Drawable object for use in a project based on Android 2.3.3, but I kept getting this error:

java.lang.ClassCastException: android.graphics.drawable.ColorDrawable
at bv.getView(BackgroundGallery.java:163)
at android.widget.Gallery.makeAndAddView(Gallery.java:748)
at android.widget.Gallery.fillToGalleryRight(Gallery.java:700)
at android.widget.Gallery.layout(Gallery.java:631)
at android.widget.Gallery.onLayout(Gallery.java:339)
at android.view.View.layout(View.java:7228)
at android.widget.FrameLayout.onLayout(FrameLayout.java:338)
at android.view.View.layout(View.java:7228)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1254)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1130)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1047)
at android.view.View.layout(View.java:7228)
at android.widget.FrameLayout.onLayout(FrameLayout.java:338)
at android.view.View.layout(View.java:7228)
at android.view.ViewRoot.performTraversals(ViewRoot.java:1157)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1877)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3687)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)

I went back, checked the image and everything seemed to be ok. Getting frustrated I started looking online for answers.
Finally I found a bug report with others having the same issue.
It turns out that on Android versions before 3.0 there is a bug in the OS which causes the first Drawable in the resources folder to be loaded as a ColorDrawable.
Obviously this will cause an error if you’re just trying to load an image.
The solution for me was to create a dummy image named a.png and placing it in res/drawable, making sure to never use it.
After that I was able to use my other images without any issues.
Original bug report

Share