【发布时间】:2016-01-05 09:56:26
【问题描述】:
在async task class 中的onpostexecute 的结果之后,我正在尝试将位图图像转换为字节数组。结果在onpostexecute 中设置正确,但是当它到达转换部分(从位图转换为字节数组)时会抛出错误。
这是 on create 方法
...
public byte[] ImageArray;
public Bitmap ImageBitmap;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//This instantiate the async class
DownloadImageTask asyncTask =new DownloadImageTask(new AsyncResponse() {
@Override
public void processFinish(Bitmap output) {
ImageBitmap = output;
}
});
asyncTask.execute(imageurl);
//I want to be able to get the ImageArray on the main thread after the async task execution
....
}
/**
* This sub class downloads the attached image
* file to be viewed on the page.
*/
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
public AsyncResponse delegate=null;
public DownloadImageTask(AsyncResponse asyncResponse) {
delegate = asyncResponse; //Assigning call back interfacethrough constructor
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
delegate.processFinish(result);
//This converts the bitmap to an byte array
ByteArrayOutputStream stream = new ByteArrayOutputStream();
result.compress(Bitmap.CompressFormat.PNG, 50, stream);
ImageArray = stream.toByteArray();
}
}
//This creates an interface for the results from the async task
public interface AsyncResponse {
void processFinish(Bitmap output);
}
请问是否可以将位图图像转换为onPostExecute 中的字节数组并在主线程上获取ImageArray?如果是,请问我该怎么做,因为我所做的会破坏应用程序。感谢您的帮助
更新
请将logcat中的错误添加到问题中
8334-8334/com.myaapp.onookow E/AndroidRuntime: FATAL EXCEPTION: main java.lang.NullPointerException 在 com.myaapp.onookow.onokows$DownloadImageTask.onPostExecute(onokows.java:342) 在 com.myaapp.onookow.onokows$DownloadImageTask.onPostExecute(onokows.java:311) 在 android.os.AsyncTask.finish(AsyncTask.java:417) 在 android.os.AsyncTask.access$300(AsyncTask.java:127) 在 android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429) 在 android.os.Handler.dispatchMessage(Handler.java:99) 在 android.os.Looper.loop(Looper.java:130) 在 android.app.ActivityThread.main(ActivityThread.java:3687) 在 java.lang.reflect.Method.invokeNative(Native Method) 在 java.lang.reflect.Method.invoke(Method.java:507) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625) 在 dalvik.system.NativeStart.main(本机方法)。
奇怪的更新
在 API > 11 的设备上测试应用后,一切正常。但是在 API
【问题讨论】:
-
你认为发布它抛出的错误是无关紧要的,如何?
-
@StefandeBruijn 它在日志猫中给出
java.lang.NullPointerException错误 -
修复你的 logcat 错误..
-
但是在哪里发布你的 logcat 堆栈跟踪可能有用..
-
@StefandeBruijn 请我在问题中添加了 logcat 错误,抱歉耽搁了
标签: android bitmap android-asynctask