【发布时间】:2017-06-01 14:09:57
【问题描述】:
我有一个名为 RestClient 的类,它从我的 webService 获取一些信息,然后返回,我试图在它访问 Internet 时运行一个进度对话框。因为我在不止一个地方使用这个类,所以我不会在活动本身中做。这是我的RestClient 课程:
public class RestClient extends AsyncTask<URL, String, String> {
private Context context;
private String string;
public RestClient(Context context, String string)
{
this.context = context;
this.string = string;
}
@Override
protected void onPreExecute() {
dialog = ProgressDialog.show(context, "Buscando seu Produto","Por favor, espere um momento...",true ,false);
//I've already tried:
/*ProgressDialog dialog = new ProgressDialog(context);
dialog.setTitle("Buscando seu Produto");
dialog.setMessage("Por favor, espere um momento...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);*/
dialog.show();
super.onPreExecute();
}
@Override
protected String doInBackground(URL... params) {
try {
//Some WebService gets and Json conversions using my string variable
//and some Thread.sleep that counts 2000 miliseconds to do all the queries
dialog.dismiss();
} catch (IOException | InterruptedException |JSONException e) {
e.printStackTrace();
dialog.dismiss();
return e.getMessage();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
在我的活动中,当我单击这样的按钮时,我调用了 RestClient 类:
--- 编辑:我忘了提到我在同一个活动中有一个 AlertDialog,有时可以在 ProgressDialog 之前和之后显示 ---
private Button buttonConfirm;
private EditView evString;
private String theString;
private String returnFromExecute;
private RestClient restClient;
private AlertDialog.Builder dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_access_webservice);
evString = (EditText) findViewById(R.id.editViewMyString);
buttonConfirm = (Button) findViewById(R.id.buttonConfirm);
dialog = new ProgressDialog(IdentificacaoDeProdutoActivity.this);
dialog.setTitle("Error");
dialog.setMessage("Please try again");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
buttonConfirmar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
theString = evString.getText().toString();
if(!(theString!=null && theString.trim().length()>0)) //To check if theString is not null
{
dialog.show();
}
restClient = new RestClient(AccessWebserviceActivity.this, theString);
//Then I call execute and put a Thread.sleep a bit longer to compensate the ones I have in my doInBackground
restClient.execute();
try {
Thread.sleep(2050);
} catch (Exception e) {
dialog.show();
return;
}
}
}
}
问题是我的ProgressDialog 从不显示。我已经尝试过getParent()、getApplication() 和getApplicationContext() 而不是AccessWebserviceActivity.this,但都没有奏效。有人知道发生了什么,我应该怎么做?
【问题讨论】:
-
你能告诉我你的 AsyncTask 类是你的 Activity 类的子类还是 AsnctaskClass 有不同的包?
-
@AmeerHamza,它不是我的 Activity 的子项,因为我在其他 Activity 中使用它,但是是的,它与我的 Activity 不在同一个包中。
标签: java android android-asynctask progressdialog