我想使用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;
}
这是调用click事件的类
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()的服务器结果? 谢谢。
答案 0 :(得分:0)
创建一个onPostExecute方法以在textview上显示结果。
protected onPostExecute (String result){
TextView tv = (TextView) findViewById(R.id.textview1);
if(result != null){
tv.setText(result);
}
}