0

我想使用 asyntask 创建 httpconnection。三个参数被发布到服务器用户名、密码和搜索项。搜索由用户在 EditText 中提供,这样当用户单击按钮时,搜索项被发送到服务器。我想在 OnclickListener 中执行 doInbackground() 方法并在 listviews 上显示来自服务器的响应。这是 AsyncTask 类

public class PostToServer extends AsyncTask<String, Void, String> {

@Override
protected void onPostExecute(String result) {

}

@Override
protected String doInBackground(String... arg0) {
     try {
         HttpClient client = new DefaultHttpClient();  
         String postURL = "url";
         String username ="username";
         String password = "password";

         HttpPost post = new HttpPost(postURL);
             List<NameValuePair> params = new ArrayList<NameValuePair>();
             params.add(new BasicNameValuePair("user", username));
             params.add(new BasicNameValuePair("pass", password));
             UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
             post.setEntity(ent);
             HttpResponse responsePOST = client.execute(post);  
             HttpEntity resEntity = responsePOST.getEntity(); 

             if (resEntity != null) {    
                 Log.i("RESPONSE",EntityUtils.toString(resEntity));
             }
     } catch (Exception e) {
         e.printStackTrace();
     }
    return null;    
}

这是调用点击事件的类

public class StartPost extends Activity  {

 @Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
     setContentView(R.layout.result_page);
}
    Button Submit = (Button) findViewById(R.id.btn_search);
     EditText textvalue = (EditText)findViewById(R.id.searcheditText);
     String value = textvalue.getText().toString();
     PostToServer post = new PostToServer();
     CheckInternetConnection check = new CheckInternetConnection(null);

 private OnClickListener click = new OnClickListener() {
     @Override
     public void onClick(final View v) {
         switch(v.getId()){
             case R.id.btn_search:
                 post.execute();
                break;   
         }  
     }
 };
}

问题 1.我做错了什么,因为帖子似乎无法正常工作,如何显示来自 onPostExecute() 的服务器结果?谢谢你。

4

1 回答 1

0

创建一个 onPostExecute 方法以在您的文本视图上显示结果。

protected onPostExecute (String result){
   TextView tv = (TextView) findViewById(R.id.textview1);
   if(result != null){
      tv.setText(result);
   }
}
于 2013-09-24T10:05:32.760 回答