我的活动是登录页面。当用户单击时,如果凭据良好,则在数据库中执行asyncTask检查。在任务期间,我想显示一个ProgressDialog但是在点击按钮后,它会保持按下5秒钟然后我的ProgressDialog quiclky显示(不到1秒)并且出现toast。
有我的onClick功能:
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();
}
}
});
我的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();
}
}
有什么想法吗?
谢谢!
答案 0 :(得分:2)
问题是你正在等待(阻塞) AsynchTask 在主线程上完成执行(这使得它无用): 请参阅此处的AsynchTask get方法文档:AsynchTask.get()
相反,您应该使用onPostExcute
回电来获取结果。
代码:
@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);
}
并在你的asynchTask中:
protected void onPostExecute(String result){
connectionProgressDialog.dismiss();
Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
}