problem in Async Task implementation of httpconnection
im working on posting a form to google server and getting the response in the form of html string and finally i put that string on webview to display result....i use the async task for this, progress dialog it shows but some times it shows me message to "force to close" without any changes i do in to code....that means prediction about output is unexpected... My code is like this......
public class Urlasync extends Activity {
WebView engine=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new AddStringTask().execute();
}
class AddStringTask extends AsyncTask<Void, Void, HttpResponse>
{
HttpResponse end = null;
String endResult = null;
public static final int TIMEOUT_MS=10000;
HttpClient client=null;
HttpPost post =null;
List<NameValuePair> pairs=null;
BasicResponseHandler myHandler=null;
private final ProgressDialog dialog = new ProgressDialog(Urlasync.this);
@Override
protected void onPreExecute() {
client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), TIMEOUT_MS);
HttpConnectionParams.setSoTimeout(client.getParams(), TIMEOUT_MS);
post = new HttpPost("http://www.google.com/m");
pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("hl", "en"));
pairs.add(new BasicNameValuePair("gl", "us"));
pairs.add(new BasicNameValuePair("source", "android-launcher-widget"));
pairs.add(new BasicNameValuePair("q", "persistent"));
try {
post.setEntity(new UrlEncodedFormEntity(pairs));
SystemC开发者_开发问答lock.sleep(400);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.dialog.setMessage("starts...");
this.dialog.show();
}
@Override
protected HttpResponse doInBackground(Void... arg0) {
try {
HttpResponse response = client.execute(post);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
return response;
}
end = response;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) { //this exception is called
e.printStackTrace();
}
return end;
}
@Override
protected void onPostExecute(HttpResponse params) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
if(params!=null)
{
String endResult=null;
BasicResponseHandler myHandler = new BasicResponseHandler();
try {
endResult = myHandler.handleResponse(params);
} catch (HttpResponseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
engine = (WebView)findViewById(R.id.webview);
engine.loadDataWithBaseURL("http://", endResult, "text/html", "UTF-8", null);
setContentView(R.layout.main);
engine.requestFocus(View.FOCUS_DOWN);
}
Toast.makeText(Urlasync.this, "Done!", Toast.LENGTH_SHORT).show();
}
}
}
suggestions with code are welcome thank you..
You shan't do anything with UI in doInBackground
(like showing Toast
). Do it in onPostExecute
or in onProgressUpdate
instead.
精彩评论