java.lang.ClassCastException:android.graphics.drawable.ColorDrawable无法强制转换为android.graphics.drawable.BitmapDrawable

时间:2017-03-12 00:34:41

标签: java android classcastexception

我试图从具有以下规格的设备上分解我的Android应用程序崩溃:

Device
PAP3400DUO 1
Manufacturer — Android version Android 4.2 RAM (MB) — Screen size 480 × 800 Screen density (dpi) 240 OpenGL ES version 2.0 Native platform armeabi-v7a

错误:

java.lang.ClassCastException: android.graphics.drawable.ColorDrawable cannot be cast to android.graphics.drawable.BitmapDrawable
    at com.yitter.android.activity.EditProfileActivity.lambda$setSubmitProfileChangesClickListener$46(EditProfileActivity.java:120)
    at com.yitter.android.activity.EditProfileActivity.access$lambda$1(EditProfileActivity.java)
    at com.yitter.android.activity.EditProfileActivity$$Lambda$2.onClick(Unknown Source)
    at android.view.View.performClick(View.java:4212)
    at android.view.View$PerformClick.run(View.java:17476)
    at android.os.Handler.handleCallback(Handler.java:800)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:194)
    at android.app.ActivityThread.main(ActivityThread.java:5371)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:525)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
    at dalvik.system.NativeStart.main(Native Method)

它真的指向120行吗?那里的代码大致显示了这个:

ImageView imageView = (ImageView) findViewById(R.id.profile_picture);
            Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] image = stream.toByteArray();
            ParseFile file = new ParseFile("profilePicture.png", image);
            user1.put("profilePicture", file);

问题可能是什么?我研究了抛出的ClassCastException,但我似乎无法将两者结合在一起。 drawable.ColorDrawable在这里与我的位图有什么关系?

修改

<ImageView
                        android:id="@+id/profile_picture"
                        android:layout_width="87dp"
                        android:layout_height="87dp"
                        android:layout_gravity="center_horizontal|center_vertical"
                        android:clickable="true"
                        android:contentDescription="@string/content_desc_profile_picture"
                        android:scaleType="fitXY"
                        android:src="@android:color/transparent" />

1 个答案:

答案 0 :(得分:1)

Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();

显然,imageView在发生此异常的情况下不包含BitmapDrawable,而是ColorDrawable。您需要检查填充此ImageView的所有不同位置。或者,更好的是,不是试图从ImageView中抽出一个可绘制的,而是从模型对象或您用来填充ImageView的任何数据源中获取图像。 / p>