Java - 将对象转换为 ByteArrayEntity (Android) 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 相机获取图像,然后将我的 HttpRequest
的 setEntity
发送到 ByteArrayEntity
并将我的图像POST
发送到服务器,然后在服务器上进行处理。
I have a ByteArrayEntity as follows:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
tempPic.compress(CompressFormat.PNG, 0, bos);
byte[] bitmapdata = bos.toByteArray();
photoByteArray = new ByteArrayEntity(bitmapdata);
tempPic
is of type android.graphics.Bitmap
.
What I then have to do is make a request using an AsyncTask that takes an array of Objects
which I later then cast to their various types. However, when attempting to cast my ByteArrayEntity later on, I get a ClassCastException
, I was wondering if anyone could explain this?
protected HttpResponse doInBackground(Object... httpRequest)
{
ByteArrayEntity dataPhoto = null;
// Further code
if(myCondition)
{
dataPhoto = (ByteArrayEntity)httpRequest[2];
}
}
I really need to get this working, but don't really have time currently to reimplement this completely, so any hacks or workarounds would be appreciated. I'm working with Android 2.2
The whole aim is to take an image from the Android camera, then setEntity
of my HttpRequest
to a ByteArrayEntity
and POST
my image to a server where this is then handled.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么不只传递一个 bean,而不是传递一个
Object[]
然后根据数组中的位置进行转换呢?无需铸造,更容易维护/扩展。
Rather than passing an
Object[]
and then casting based on the position in the array, why not just pass a bean?No casting required and much easier to maintain/extend.
您可以使用
AsyncTask
的不同类型参数化,以便不需要进行强制转换。如果您使用的是匿名类,那么:这样您就可以这样做:
如果您的参数确实是
ByteArrayEntity
类型。You might use a different type parameterization of
AsyncTask
so that you don't need to cast. If you're using an anonymous class then:So that you can do:
if your arguments are indeed intended to be of type
ByteArrayEntity
.