Java - 将对象转换为ByteArrayEntity(Android)ClassCastException

时间:2011-03-25 15:24:12

标签: android casting classcastexception

我有一个ByteArrayEntity如下:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
tempPic.compress(CompressFormat.PNG, 0, bos);
byte[] bitmapdata = bos.toByteArray();
photoByteArray = new ByteArrayEntity(bitmapdata);

tempPic的类型为android.graphics.Bitmap

我接下来要做的是使用AsyncTask发出请求,该请求采用Objects数组,然后我将其转换为各种类型。但是,在稍后尝试投射我的ByteArrayEntity时,我得到ClassCastException,我想知道是否有人可以解释这个?

protected HttpResponse doInBackground(Object... httpRequest) 
{
    ByteArrayEntity dataPhoto = null;

    // Further code


    if(myCondition)
    {
        dataPhoto = (ByteArrayEntity)httpRequest[2];
    }

}

我真的需要让这个工作,但目前没有时间完全重新实现这一点,所以任何黑客或变通办法都会受到赞赏。我正在使用 Android 2.2

整个目标是从Android相机拍摄图像,然后将我setEntity的{​​{1}}图像转换为HttpRequestByteArrayEntity我的图像到服务器,这是然后处理。

2 个答案:

答案 0 :(得分:2)

不是传递Object[]然后根据数组中的位置进行投射,为什么不直接传递bean呢?

public class MyBean {
    private ByteArrayEntity myByteArrayEntity;
    private String someString;

    // getters and setters
}

不需要铸造,更容易维护/扩展。

答案 1 :(得分:0)

您可以使用AsyncTask的其他类型参数化,以便不需要强制转换。如果你正在使用匿名类,那么:

new ArrayTask<ByteArrayEntity, Void, HttpResponse>() {
    ...

这样你就可以:

@Override
protected HttpResponse doInBackground(ByteArrayEntity... byteArrays) {
    ...
    dataPhoto = byteArrays[2];
    ...

如果您的参数确实属于ByteArrayEntity类型。

相关问题