我有一个帖子发布到rails服务器。我已经为它创建了一个响应处理程序,它将UI设置为该帖子的结果,但是我从错误的线程异常中获得了一个调用。如果我不应该在我的响应处理程序中更新我的UI,我还能怎么做呢?
这是我的主题
Thread translateText = new Thread(new Runnable(){
public void run(){
try{
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post=new HttpPost("[my url]");
List<NameValuePair> form=new ArrayList<NameValuePair>();
form.add(new BasicNameValuePair("test", "test"));
post.setEntity(new UrlEncodedFormEntity(form, HTTP.UTF_8));
String responseBody=client.execute(post, finishTranslation);
}
catch(Exception t){
System.out.println(t.toString());
}
}
});
这是我的回复处理程序
ResponseHandler<String> finishTranslation = new ResponseHandler<String>() {
public String handleResponse(
HttpResponse response) throws ClientProtocolException, IOException {
HttpEntity entity = response.getEntity();
if (entity != null) {
String res = EntityUtils.toString(entity);
System.out.println(res);
tv_Translation.setText(res); // error gets thrown here
return res;
} else {
return null;
}
}
};
答案 0 :(得分:1)
我从未使用过ResponseHandler,但它看起来像是在非UI线程上用于其他处理,并且它可以将您在handleReponse方法上下文中创建的任何对象返回到UI线程。 / p>
所以,既然你首先在后台线程上调用client.execute,你仍然需要使用Handler.post(Runnable)“发布”回UI线程