我正在创建一个将图像从java服务器发送到android客户端。 这是我的android代码:
protected Void doInBackground(Void... arg0) {
try {
socket = new Socket("192.168.237.1", 6666);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
// dataOutputStream.writeUTF(textOut.getText().toString());
String base64Code = dataInputStream.readUTF();
Log.d("String", ":" + base64Code);
//
byte[] decodedString;
decodedString = Base64.decode(base64Code);
Log.d("Ds",""+decodedString);
Log.d("St--", ":" + decodedString.length);
BitmapFactory.Options options=new BitmapFactory.Options();
options.inMutable=true;
bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length,options);
Drawable ob=new BitmapDrawable(getResources(),bitmap);
imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setBackgroundDrawable(ob);
/*//imageView.setImageBitmap(bitmap);
ByteArrayInputStream input=new ByteArrayInputStream(decodedString);
bitmap=BitmapFactory.decodeStream(input);
imageView.setImageBitmap(bitmap);*/
Log.d("Bitmap",""+bitmap);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
Log.d("Error", "" + e);
}
}
我已经在java usung apache公共编解码器中编码了字节数组,并在android程序中解码。
我得到的错误是它在NullPointeException
给出了imageView.setBackgroundDrawable (ob);
。
这段代码中的错误是什么?
答案 0 :(得分:0)
您可以从后台线程执行UI操作。它们需要在ui线程中执行。因此,尝试在onPostExecute()中执行操作。
答案 1 :(得分:0)
你需要这样做:
private class MyAsyncTask extends AsyncTask<Void, Void, Bitmap> {
@Override
protected Bitmap doInBackground(Void... params) {
try {
socket = new Socket("192.168.237.1", 6666);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
// dataOutputStream.writeUTF(textOut.getText().toString());
String base64Code = dataInputStream.readUTF();
Log.d("String", ":" + base64Code);
//
byte[] decodedString;
decodedString = Base64.decode(base64Code);
Log.d("Ds",""+decodedString);
Log.d("St--", ":" + decodedString.length);
BitmapFactory.Options options=new BitmapFactory.Options();
options.inMutable=true;
bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length,options);
return bitmap;
/*//imageView.setImageBitmap(bitmap);
ByteArrayInputStream input=new ByteArrayInputStream(decodedString);
bitmap=BitmapFactory.decodeStream(input);
imageView.setImageBitmap(bitmap);*/
Log.d("Bitmap",""+bitmap);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
Log.d("Error", "" + e);
}
return null;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
Drawable ob =new BitmapDrawable(getResources(), bitmap);
imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setBackgroundDrawable(ob);
} else {
// error
}
}
}