Reputation: 270
I'm new to Progress Dialog
. I created a class DBOperations extends AsyncTask
and implemented methods onPreExecute
and onPostExecute
. I made DB calls like
newDBOperations().execute( ... );
The onPreExecute
and onPostExecute
methods invoked perfectly, but i was not able to see the Progress Dialog
on my emulator
Code look like
@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();
}
}
Should i use newHandler().postDelayed
?
Thanks in advance...
Upvotes: 0
Views: 121
Reputation: 11
This is how I did it. Works good for me.
Main 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();
}
});
}
}
And 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);
}
}
Hope this helps :)
Upvotes: 1
Reputation: 6105
I put this code into an isolated application, and it showed the dialog:
ProgressDialog dialog = new ProgressDialog(MainActivity.this);
dialog.setCancelable(false);
dialog.setMessage("Please Wait ...");
dialog.show();
It's the exact same code you use, except I replaced your context
variable with MainActivity.this
So I believe the context
variable you are using is an issue. Make sure you're using the correct Context
.
Also, as @MdSufiKhan pointed out in the comments, you won't be able to dismiss it properly, since you create it locally in onPreExecute()
. Leave it as a field of DBOperations
Upvotes: 0