You have plenty of examples of the usage of AsyncTask
on the Internet, for example: AsyncTask reference doc, Stackoverflow question.
Regarding where, I'd suggest to create and execute the AsyncTask
in the onClick
method of the registered listener of btnLogin
. You could run userFunction.loginUser
in the doInBackground
method of the task and then check the login response in the onPostExecute
method.
For example:
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new AsyncTask<String, Void, JSONObject>(){
@Override
protected JSONObject doInBackground(String... args) { //This is run on a background thread
String email = args[0];
String password = args[1];
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email, password);
return json;
}
@Override
protected void onPostExecute(JSONObject json) { //This is run on the UI thread
if(json != null){
//... update the user interface ...
}else{
Log.e("LoginTask", "No login response was received");
}
super.onPostExecute(json);
}
}.execute(inputEmail.getText().toString(), inputPassword.getText().toString());
}
});
As a rule of thumb, all input / output operations and heavy tasks (network communications, parsing, etc) should be run on a background thread (while showing a progress dialog to the user). Once the results are obtained, the screen can be updated using the UI thread.
However, when using AsyncTasks
there are additional concerns, as explained in this discussion about holding references to the Context.