I am working on an Application which is using the AsyncTask. I am trying to connect to my website, check user login details and return true if user exists and false if not found. Based on the response I will display an error message or load up the relevant screen for the user.
However I am wondering if the below code should be placed in the onClick listener of my login button or in the onPreExecute() method of the AsyncTask?
I call the asyncTask like this
public void onClick(View v) {
//Call background task
new HttpTask().execute(url);
}
});
Does it matter where I call the below code? Should it ideally be in the onPreExecute() method?
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.mysite.com/checklogindetails.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", name));
nameValuePairs.add(new BasicNameValuePair("password", pass));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
Thanks for any info regarding this guys. It’s not a problem as such, it’s more a learning curve for me and I’m curious what I should do.
thanks.
Your HTTP code needs to be in the
doInBackground()method, otherwise it is still running in the main (UI) thread and can cause exceptions on new Android versions (not to mention lockups if your request takes a long time).Here is an example (note the constructor addition) I decided to keep the pairs inside
doInBackground(). Since you haven’t given us all code, this probably won’t work right off the bat.And you’d call using