2011-04-04 19 views
0

我有一個線程發佈到rails服務器。我爲它創建了一個響應處理程序,它將UI設置爲該帖子的結果,但是我收到了來自錯誤線程異常的調用。如果我不應該在我的響應處理程序中更新我的用戶界面,我該怎麼辦?android-settext on responsehandler拋出錯誤

這裏是我的線程

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; 
     } 
    } 
}; 

回答

1

我從來沒有與ResponseHandler所工作,但看起來這是在額外的處理非UI線程使用,並且它可以將在handleReponse方法的上下文中創建的任何對象返回到UI線程。因此,由於您首先在後臺線程上調用了client.execute,因此您仍然需要使用Handler.post(Runnable)「發佈」回UI線程。