2012-04-27 63 views
1

我是新来创建Android应用程序和第一次使用asynctask。我想在后台运行一个httpost,但不断收到错误。我使用正确的参数吗?我是否也需要postexecute?asynctask httpost?

这里是我的代码

公共无效发送(视图v){ 新 sendtask()执行()。如果需要更新用户界面使用 }

private class sendtask extends AsyncTask<String,Void, String> { 


    String msg = msgTextField.getText().toString(); 
    String msg1 = spinner1.getSelectedItem().toString(); 
    String msg2 = spinner2.getSelectedItem().toString(); 


    protected String doInBackground(String...url) { 

      try { 

       HttpClient httpclient = new DefaultHttpClient(); 
       HttpPost httppost = new HttpPost("http://10.0.2.2:80/test3.php"); 
       List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);; 
       nameValuePairs.add(new BasicNameValuePair("id", "12345")); 
       nameValuePairs.add(new BasicNameValuePair("name", msg)); 
       nameValuePairs.add(new BasicNameValuePair("gender",msg1)); 
       nameValuePairs.add(new BasicNameValuePair("age",msg2)); 
       httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));     
       httpclient.execute(httppost); 

       msgTextField.setText(""); // clear text box 
      } catch (ClientProtocolException e) { 
       // TODO Auto-generated catch block 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
      } 
     return null; 
+0

应该读取Logcat中的消息。WOuld比“我得到一个错误”更有用 – 2012-04-27 20:00:51

+0

对不起,我忘了添加日志猫。 – user1356620 2012-04-27 22:20:11

回答

1

OnPostExecute(也可以不更新方法doInBackground(字符串的用户界面。.. URL)),由接收到的OnPostExecute参数,则返回该值通过doInBackground(String。.. url),而不是你的案例是否与用户相关通知你是否发布了这个帖子

0

你应该包含错误以帮助识别和解决问题,但在这种情况下,解决方案可能是以下内容:

private class sendtask extends AsyncTask<String, Void, String> { 
    String msg = msgTextField.getText().toString(); 
    String msg1 = spinner1.getSelectedItem().toString(); 
    String msg2 = spinner2.getSelectedItem().toString(); 

    protected String doInBackground(String... url) { 
     try { 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost("http://10.0.2.2:80/test3.php"); 
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4); 
      nameValuePairs.add(new BasicNameValuePair("id", "12345")); 
      nameValuePairs.add(new BasicNameValuePair("name", msg)); 
      nameValuePairs.add(new BasicNameValuePair("gender", msg1)); 
      nameValuePairs.add(new BasicNameValuePair("age", msg2)); 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
      httpclient.execute(httppost); 

      return ""; 
     } catch (ClientProtocolException e) { 
      return "ClientProtocolException"; 
     } catch (IOException e) { 
      return "IOException"; 
     } 
    } 

    protected void onPostExecute(String result) { 
     msgTextField.setText(result); // clear text box 
    } 
} 

重要的变化是msgTextField.setText("");现在在onPostExecute()中,并且它从doInBackground()收到要显示的文本。您必须在主线程上执行每个UI更改,即不在doInBackground()中。

+0

非常感谢。解决问题。 – user1356620 2012-04-27 22:41:35