Reputation: 48
My activity is a login page. When the user clicks, an asyncTask check in a database if credentials are good. During the task, I want to display a ProgressDialog but after clicking on the button, it stays pressed for 5 seconds and then my ProgressDialog quiclky shows up (less than 1 second) and the toast appears.
There is my onClick function :
Button connect = (Button)findViewById(R.id.connectButton);
final EditText loginED = (EditText) findViewById(R.id.login);
final EditText passwordED = (EditText) findViewById(R.id.password);
connect.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View arg0) {
String login = loginED.getText().toString();
String password = passwordED.getText().toString();
String[] params = {login, password};
DoAsyncLogin doAsyncLogin = new DoAsyncLogin();
try {
String result = doAsyncLogin.execute(params).get();
Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
});
And my AsyncTask :
private class DoAsyncLogin extends AsyncTask<String, Void, String>
{
ProgressDialog connectionProgressDialog = new ProgressDialog(MainActivity.this);
@Override
protected String doInBackground(String... params) {
return getLoginData(params);
}
protected void onPreExecute(){
connectionProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
connectionProgressDialog.setMessage("Logging in...");
connectionProgressDialog.show();
}
protected void onPostExecute(String result)
{
connectionProgressDialog.dismiss();
}
}
Any ideas ?
Thanks !
Upvotes: 1
Views: 2670
Reputation: 9276
The problem is that you are waiting (blocking) for the AsynchTask to finish its execution on the main thread ( which makes it useless ): See the documentations for AsynchTask get method here :AsynchTask.get()
Instead you should use onPostExcute
call back to get your results.
Code:
@Override
public void onClick(View arg0) {
String login = loginED.getText().toString();
String password = passwordED.getText().toString();
String[] params = {login, password};
DoAsyncLogin doAsyncLogin = new DoAsyncLogin();
doAsyncLogin.execute(params);
}
and in your asynchTask:
protected void onPostExecute(String result){
connectionProgressDialog.dismiss();
Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
}
Upvotes: 2