開啟了一個子線程,其中有兩個方法分別負責從服務器下載圖片和文字。下載成功後,兩個方法中都分別創建了message來將數據傳到主線程中的handlemessage()方法處理,第一個下載圖片的方法沒問題第二個下載文字後調用sendmessage時程序異常退出。求解? 代碼如下:
public class Query extends Activity {
String image_path = "http://img.ivsky.com/img/bizhi/pic/201504/27/benpaoba_xiongdi_dierji-001.jpg";
Bitmap b;
ImageView show;
ProgressDialog dialog;
private final int IS_FINISH = 3;
private final int IS_OK = 6;
private static final String TAG = "Query";
Handler handler = new Handler() {
public void handleMessage(Message msg) {
byte[] data = (byte[]) msg.obj;
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
show.setImageBitmap(bitmap);
if(msg.what == IS_FINISH) {
dialog.dismiss();
}
if(msg.what == IS_OK) {
String s = (String) msg.obj;
}
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_query);
Button download = (Button) this.findViewById(R.id.download);
show = (ImageView) this.findViewById(R.id.imageView_download);
download.setOnClickListener(new OnClickListener() {
public void onClick(View V) {
new Thread(new MyThread()).start();
}
});
}
public class MyThread implements Runnable {
public void run() {
downloadPicture();
showTest();
}
}
public void downloadPicture() {
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(image_path);
HttpResponse httpResponse = null;
try {
httpResponse = client.execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode() == 200) {
byte[] data = EntityUtils.toByteArray(httpResponse.getEntity());
Message message = Message.obtain();
message.obj = data;
message.what = IS_FINISH;
handler.sendMessage(message);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void showTest() {
String url_path = "http://192.168.1.94:8080/TestSysClient/servlet/AndroidServlet";
String jsonString = HttpTools.getJsonContent(url_path);
List<Device> list = JsonTools.getDeviceList("devices", jsonString);
System.out.println(jsonString);
Log.i(TAG, list.toString());
Message ms = Message.obtain();
Bundle data = new Bundle();
data.putString("message", jsonString);
ms.setData(data);
ms.what = IS_OK;
ms.obj = "haha";
handler.sendMessage(ms); //加上此處後程序出現問題。
}
如何解決問題呢?
ms.setData(data);
ms.what = IS_OK;
ms.obj = "haha";
handler.sendMessage(ms); //加上此處後程序出現問題。這裡的obj是“haha"
public void handleMessage(Message msg) {
byte[] data = (byte[]) msg.obj; //發送過來的"haha",轉成byte數組,類型不對了。