我需要在我的 Android 项目上显示加载动画,等待响应即将到来。 我尝试显示加载消息。 我需要在响应到来后隐藏。
private void searchCustomer(final String username, final String
password, final String baseUrl, final ProgressDialog dialog) {
AsyncTask<String, String, String> checkLogin = new AsyncTask<String, String, String>() {
final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
@Override
protected String doInBackground(String... strings) {
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{nt"custUserName": ""+ username +"",nt"custPassword": ""+ password +""n}");
Request request = new Request.Builder()
.url(baseUrl + "customerLogin")
.post(body)
.addHeader("Content-Type", "application/json")
.build();
try {
Response response = okHttpClient.newCall(request).execute();
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
@Override
protected void onPostExecute(String s) {
dialog.setMessage("Processing...");
dialog.show();
StringBuilder sb = new StringBuilder();
char[] temp = s.toCharArray();
for (char current : temp) {
if (current != '"') {
sb.append(current);
}
}
String s1 = sb.toString();
if (s1.equals("true")) {
Notification.showSuccessMdToast("Login Successful", getApplicationContext());
Intent customerNav = new Intent(MainActivity.this, CustomerNav.class);
startActivity(customerNav);
}
}
};
checkLogin.execute();
}
在帖子中执行响应值为真。 但处理对话框未隐藏。
工作
完成时调用doInBackground
onPostExecute
回调。
您必须在onPreExecute()
内调用dialog.show();
并将其隐藏在onPostExecute()
上。 见下文:
AsyncTask<String, String, String> checkLogin = new AsyncTask<String, String, String>() {
final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Processing...");
dialog.show();
}
@Override
protected String doInBackground(String... strings) {
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{nt"custUserName": ""+ username +"",nt"custPassword": ""+ password +""n}");
Request request = new Request.Builder()
.url(baseUrl + "customerLogin")
.post(body)
.addHeader("Content-Type", "application/json")
.build();
try {
Response response = okHttpClient.newCall(request).execute();
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
@Override
protected void onPostExecute(String s) {
dialog.dismis();
StringBuilder sb = new StringBuilder();
char[] temp = s.toCharArray();
for (char current : temp) {
if (current != '"') {
sb.append(current);
}
}
String s1 = sb.toString();
if (s1.equals("true")) {
Notification.showSuccessMdToast("Login Successful", getApplicationContext());
Intent customerNav = new Intent(MainActivity.this, CustomerNav.class);
startActivity(customerNav);
}
}
};
checkLogin.execute();
您需要
隐藏if
语句中的对话框,如下所示:
if (s1.equals("true") {
dialog.dimiss();
}
附加提示:您可以在onPreExecute()
中显示进度对话框,而不是以onPostExecute()
显示