我是Progress Dialog
的新手。我创建了class DBOperations extends AsyncTask
并实施了methods onPreExecute
和onPostExecute
。我做了像
newDBOperations().execute( ... );
onPreExecute
和onPostExecute
方法完美调用,但我无法在模拟器上看到Progress Dialog
代码看起来像
@Override
protected void onPreExecute() {
ProgressDialog dialog = new ProgressDialog(context);
dialog.setCancelable(false);
dialog.setMessage("Please Wait ...");
dialog.show();
}
@Override
protected void onPostExecute(Object o) {
if(dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
我应该使用newHandler().postDelayed
吗?
提前致谢...
答案 0 :(得分:1)
这就是我做的。对我有用。
主要Activity.java
public class MainActivity extends AppCompatActivity {
Button button;
DBOperations task;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button); // declared in xml
button.setOnClickListener(new View.OnClickListener() { // starts AsyncTask on button click
@Override
public void onClick(View v) {
task = new DBOperations(MainActivity.this); // pass the context to the constructor
task.execute();
}
});
}
}
DBOperations.java
public class DBOperations extends AsyncTask<Void, Void, Void> {
Context ctx;
ProgressDialog dialog; // should be declared outside onPreExecute
public DBOperations(Context ctx) {
this.ctx = ctx;
}
@Override
protected void onPreExecute() {
dialog = new ProgressDialog(ctx);
dialog.setCancelable(false);
dialog.setMessage("Please Wait ...");
dialog.show();
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(3000); // waits 3 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
if(dialog != null && dialog.isShowing())
dialog.dismiss();
super.onPostExecute(aVoid);
}
}
希望这会有所帮助:)
答案 1 :(得分:0)
我将此代码放入一个独立的应用程序中,它显示了对话框:
ProgressDialog dialog = new ProgressDialog(MainActivity.this);
dialog.setCancelable(false);
dialog.setMessage("Please Wait ...");
dialog.show();
这与您使用的代码完全相同,只是我将context
变量替换为MainActivity.this
所以我相信您使用的context
变量是一个问题。确保使用正确的Context
。
此外,正如@MdSufiKhan在评论中指出的那样,您将无法正确解除它,因为您在onPreExecute()
本地创建它。将其保留为DBOperations