【发布时间】:2014-12-05 14:26:58
【问题描述】:
我有主要活动:
public class ChooseWriteSentenceActivity extends ActionBarActivity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String userName = "Zdzisiu";
String password = "Ziemniak";
MainServie service = new MainService(this);
boolean isExsist = service.findUser(String userName, String password);
//more code...
}
}
在我的应用服务中使用存储库和 jsonconsumers,但对于更简单的代码,我将跳过它们。
public class MyService{
private Context context;
public MyService(Context context){
this.context = context
}
public boolean findUser(String userName, String password){
String resultS = null;
try{
resultS = new QueryExecutorFindUser(context).execute(userName,password).get();
}
catch(Exception ex){
ex.printStackTrace();
}
boolean realRes = jsonConsumer(resultS).getFindUser();
return realRes;
}
}
public class QueryExecutorFindUser extends AsyncTask<String,Void,String> {
protected final String connectionUrl = "http://myWebService:44302/Service.svc/";
protected ProgressDialog progressDialog;
protected Context curContext;
public QueryExecutor(Context context){
curContext = context;
}
@Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = ProgressDialog.show(curContext,"Loading...",
"Loading application View, please wait...", false, false);
}
@Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
progressDialog.dismiss();
}
protected String doInBackground(String... args){
String result = null;
String url = connectionUrl + args[0] + "/" + args[1];
HttpResponse response = null;
HttpClient httpclient = this.getNewHttpClient();
HttpGet get = new HttpGet(url);
get.setHeader("Accept", "application/json");
get.setHeader("Content-type", "application/json");
try{
response = httpclient.execute(get);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
if(response != null){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
result = out.toString();
}
} else{
throw new IOException(statusLine.getReasonPhrase());
}
} catch(Exception ex){
ex.getMessage();
} finally{
if(response != null){
try{
response.getEntity().getContent().close();
} catch(Exception ex){
}
}
}
return result;
}
}
并显示进度对话框,但只有在 ChooseWriteSentenceActivity 中的 onCreatre 中的所有代码(包括来自 QueryExecutor 的 doInBacground(...) )完成之后(因此它几乎同时消失)。它看起来像是在等待带有 QueryExecutorFindUser.doInBackground() 的线程并且它像同步运行(?),我认为这是因为当我调试代码时 onPreExecute() 正在正确运行(并且在 doInBackground(...) 之前启动)和 progressDialog .isShowing() == true (但不在屏幕上:()。
如果我从 QueryExecutorFindUser 中删除 extends AsyncTask 并在主要活动中使用此扩展名创建私有类(并从 onCreated() 运行所有代码,包括 thisPrivateClass.doInBackground(...) 中的 service.findUser())它可以正常工作。
我更喜欢在所有主要活动中都没有progressDialog(当然实际上我对所有查询都使用QueryExecutor,不仅是findUser),但我不知道我做错了什么。我花了一整天都没有结果:(
【问题讨论】:
-
尝试在 onCreate 而不是 onPre 中启动进度对话框
-
谢谢,但没有帮助
标签: android asynchronous android-asynctask external progressdialog