我从socket获取图像:
mByteArray = new char[size+1];
int count = 0;
r.read(mByteArray,0, size);
int nbrOfPixels = width*height;
Log.i("nbrOfPixels", String.valueOf(nbrOfPixels));
int pixels[] = new int[nbrOfPixels];
for(int i = 0; i < nbrOfPixels; i++) {
int r = mByteArray[3*i];
int g = mByteArray[3*i + 1];
int b = mByteArray[3*i + 2];
pixels[i] = Color.rgb(r, g, b);
}
bitmap = Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888);
oncreate中的ImageView定义为:
imageView = (ImageView)findViewById(R.id.imgView);
并在Async任务中:
private class ImageTransfer extends AsyncTask<Void,Void,Bitmap> {
public Bitmap bitmap1 = null;
ImageView im_v = null;
public ImageTransfer(ImageView view){
this.im_v= view;
}
@Override
protected Bitmap doInBackground(Void... params) {
try {
bitmap1 = doItOnServer();
} catch (Exception e) {
Log.v("Exception", e.getMessage());
}
return bitmap1;
}
当我尝试在Async任务中显示图像时,它会抛出空指针异常
protected void onPostExecute(Bitmap result) {
try {
if (bitmap1 != null) {
im_v.setImageBitmap(result);
} else {
Log.v("Error reading bitmap", "error");
}
} catch (Exception e) {
Log.e("OnPost Exec", "Exception", e);
}
}
为捕获的异常捕获的日志是:
3166-3166/junaidyounas.makerprojectjava E/OnPost Exec﹕ Exception
java.lang.NullPointerException
at junaidyounas.makerprojectjava.OpenCVSelecter$ImageTransfer.onPostExecute(OpenCVSelecter.java:639)
at junaidyounas.makerprojectjava.OpenCVSelecter$ImageTransfer.onPostExecute(OpenCVSelecter.java:615)
at android.os.AsyncTask.finish(AsyncTask.java:677)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:690)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5045)
at java.lang.reflect.Method.invokeNative(Native Method).....
答案 0 :(得分:0)
我只是修复了代码,但我认为你应该发布方法doItOnServer():
protected void onPostExecute(Bitmap result) {
try {
if (result != null) {
im_v.setImageBitmap(result);
} else {
Log.v("Error reading bitmap", "error");
}
} catch (Exception e) {
Log.e("OnPost Exec", "Exception", e);
}
}