Android: ProgressDialog not showing in AsyncTask called in onCreate() - android

I have a AsyncTask which will be executed in the onCreate method. However, my ProgressDialog isn't showing up. And from debugging, it is confirmed that the AsyncTask is being executed.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lifestyle);
context = getApplicationContext();
new testAsync().execute();
}
private class testAsync extends AsyncTask<Void,Void,Void> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this); // tried with context, no difference
pDialog.setTitle("Inserting sample data");
pDialog.setMessage("Please wait. This dialog will be dismissed upon completion.");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TableControllerReadings TCR = new TableControllerReadings(context);
// TCR.insertSampleData(getApplicationContext());
new Timer().schedule(new TimerTask() {
#Override
public void run() {
//delay for 5 seconds
}
}, 5000);
return null;
}
#Override
protected void onPostExecute(Void v) {
pDialog.dismiss();
}
}

Take your pDialog.dismiss(); into the your timer thread.
Reason: onPostExecute() immediately call because on background task is finished.
Its seprate thread which is on delay so cursor move to the onPostExecute()
private class testAsync extends AsyncTask<Void, Void, Void> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this); // tried with context, no difference
pDialog.setTitle("Inserting sample data");
pDialog.setMessage("Please wait. This dialog will be dismissed upon completion.");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TableControllerReadings TCR = new TableControllerReadings(context);
// TCR.insertSampleData(getApplicationContext());
new Timer().schedule(new TimerTask() {
#Override
public void run() {
//delay for 5 seconds
pDialog.dismiss();
}
}, 5000);
return null;
}
#Override
protected void onPostExecute(Void v) {
// pDialog.dismiss();
}
}

Activity will not show any view until onResume method is called. If your AsyncTask execution completes before onResume call then you will never see the ProgressDialog.
So better call new testAsync().execute(); in onResume

add pDialog.show(); in doInBackground and add new testAsync().execute(); in onResume

Your code is working fine with Thread.sleep(5000); if you want to add delay then use Thread.Sleep(/time in milisec/) instead of Timer.Schedule. Because of Timer.Schedule async task is executing so quickly before showing any dialog.

Related

progressdialog going behind a dialog

I have created dialog and it inflates xml which gets updated with the info .But the progress dialog is shown behind the dialog which pops up .How do I show those progressdialog on top of dialog with inflated xml.
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialog();
}
public class loadasync extends AsyncTask<Void, Void, JSONObject> {
ProgressDialog progressDialog ;
#Override
protected JSONObject doInBackground(Void... params) {
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("loading");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}
});
}
#Override
protected void onPostExecute(JSONObject result) {
runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.dismiss();
}
});
}
}
public void dialog() {
dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.dialogxml);
loadasync loadasyncdata=new loadasync();
loadasyncdata.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
dialog.show();
}
I cannot see that you are using the setProgressStyle() in your code. That is:
progessDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
for instance.
So in your code try the following:
public void run() {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("loading");
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}
Something to consider : OnPostExecute and onPreExecute are both run on the UI thread, so you can remove the runOnUIThread stuff, just do
protected void onPreExecute() {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("loading");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}
and respectively in onPostExecute
protected void onPostExecute(JSONObject result) {
progressDialog.dismiss();
}
Should maybe be a comment, but the reputation ...

Show ProgressBar for a certain time in Android

I have to wait some seconds in my Android App and I want to show a progress bar during this time, how can I do this?
I tried for example this code:
public boolean WaitTask() {
pDialog = ProgressDialog.show(context,null, "Lädt..",true);
new Thread() {
public void run() {
try{
// just doing some long operation
sleep(2000);
} catch (Exception e) { }
pDialog.dismiss();
}
}.start();
return true;
}
But the progressbar closes immediately without waiting the two seconds. Where is my problem?
The progressbar should look like the activity circle showing in this site from Android Developers.
UPDATE
The AsyncTask
private class WaitTime extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mDialog.show();
}
protected void onPostExecute() {
mDialog.dismiss();
}
#Override
protected void onCancelled() {
mDialog.dismiss();
super.onCancelled();
}
#Override
protected Void doInBackground(Void... params) {
long delayInMillis = 2000;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
mDialog.dismiss();
}
}, delayInMillis);
return null;
}
}
I call it like this:
mDialog = new ProgressDialog(CreateProject.this);
mDialog = ProgressDialog.show(context,null, "Lädt..",true);
WaitTime wait = new WaitTime();
wait.execute();
I reccomend you to use AsyncTask, then you can do something like this:
AsyncTask<Void, Void, Void> updateTask = new AsyncTask<Void, Void, Void>(){
ProgressDialog dialog = new ProgressDialog(MyActivity.this);
#Override
protected void onPreExecute() {
// what to do before background task
dialog.setTitle("Loading...");
dialog.setMessage("Please wait.");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// do your background operation here
return null;
}
#Override
protected void onPostExecute(Void result) {
// what to do when background task is completed
dialog.dismiss();
};
#Override
protected void onCancelled() {
dialog.dismiss();
super.onCancelled();
}
};
updateTask.execute((Void[])null);
and if you want to wait for some specific time, maybe you would like to use Timer:
final ProgressDialog dialog = new ProgressDialog(MyActivity.this);
dialog.setTitle("Loading...");
dialog.setMessage("Please wait.");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
long delayInMillis = 5000;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
dialog.dismiss();
}
}, delayInMillis);
mistake: calling pDialog.dismiss(); should be done from the UI thread instead of called from your new thread.
so your code should change to:
pDialog = ProgressDialog.show(context,null, "Lädt..",true);
new Thread() {
public void run() {
try{
// just doing some long operation
Thread.sleep(2000);
} catch (Exception e) { }
// handle the exception somehow, or do nothing
}
// run code on the UI thread
mYourActivityContext.runOnUiThread(new Runnable() {
#Override
public void run() {
pDialog.dismiss();
}
});
}.start();
generally - there are much better approaches performing background tasks (waiting and do nothing for two seconds is also background task) and performing something in the main UI thread when they finished. you can use AsyncTask class for example. it's better use this android built in mechanism, and not "primitive" thread creation, although it will work too - only if you will handle right your application and activity life-cycle. remember there is a chance that in the two seconds you are waiting - the user can navigate away from your application. in that case the dismiss(); method would be call on a destroyed context...
I suggest you read more in - http://developer.android.com/reference/android/os/AsyncTask.html

ProgressDialog doesn't show up. Again

I'm confused because this has been working for me quite fine in other activities, and here I just basically copy-pasted the code, but ProgressDialog doesn't show up. Here's the code:
public class MyListActivity extends ListActivity {
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mylayout);
final ProgressDialog progress = new ProgressDialog(this);
progress.setProgressStyle(STYLE_SPINNER);
progress.setIndeterminate(true);
progress.setMessage("Working...");
progress.show();
Thread thread = new Thread()
{
public void run()
{
//long operation populating the listactivity
progress.dismiss();
}
};
thread.run();
}
}
Not sure if this is the root cause of your problem, but try executing thread.start() instead of thread.run(). Executing start() will actually start a new thread and maybe give the progress dialog a chance to show.
You should use AsyncTask to manage the long operation.
private class LongOperation extends AsyncTask<HttpResponse, Integer, SomeReturnObject>
{
ProgressDialog pd;
long totalSize;
#Override
protected void onPreExecute()
{
pd = new ProgressDialog(this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMessage("Please wait...");
pd.setCancelable(false);
pd.show();
}
#Override
protected SomeReturnObject doInBackground(HttpResponse... arg0)
{
// Do long running operation here
}
#Override
protected void onProgressUpdate(Integer... progress)
{
// If you have a long running process that has a progress
pd.setProgress((int) (progress[0]));
}
#Override
protected void onPostExecute(SomeReturnObject o)
{
pd.dismiss();
}
}
From the above code, it's actually showing the dialog and closing it immediately in the Thread run() method. If you really want to see if it shows put a Thread.sleep(2000) to test, but yes what John Russell said is the way to go to use an AsyncTask instead.

Dismiss a dialog when a thread is done

I'm creating a thread in android for a time consuming operation. I want the main screen to show a progress dialog with a message informing that the operation is in progress, but I want that dialog to dismiss once the thread is done. I've tried with join but it locks the thread and doesn't show the dialog. I tried using:
dialog.show();
mythread.start();
dialog.dismiss();
but then the dialog doesn't show. How can I make that sequence but wait for the thread to end without locking the main thread?
This is as far as I got:
public class syncDataElcanPos extends AsyncTask<String, Integer, Void> {
ProgressDialog pDialog;
Context cont;
public syncDataElcanPos(Context ctx) {
cont=ctx;
}
protected void onPreExecute() {
pDialog = ProgressDialog.show(cont,cont.getString(R.string.sync), cont.getString(R.string.sync_complete), true);
}
protected Void doInBackground(String... parts) {
// blablabla...
return null;
}
protected void onProgressUpdate(Integer... item) {
pDialog.setProgress(item[0]); // just for possible bar in a future.
}
protected void onPostExecute(Void unused) {
pDialog.dismiss();
}
But when I try to execute it, it gives me an exception: "Unable to add window".
When your thread is done, use the runOnUIThread method to dismiss the dialog.
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
To do that there is two ways to do it , ( and i prefer the first second one : AsyncTask ) :
First : you display your alertDialog , and then on the method run() you should do like this
#override
public void run(){
//the code of your method run
//....
.
.
.
//at the end of your method run() , dismiss the dialog
YourActivity.this.runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
}
Second : Using an AsyncTask like this :
class AddTask extends AsyncTask<Void, Item, Void> {
protected void onPreExecute() {
//create and display your alert here
pDialog = ProgressDialog.show(MyActivity.this,"Please wait...", "Downloading data ...", true);
}
protected Void doInBackground(Void... unused) {
// here is the thread's work ( what is on your method run()
items = parser.getItems();
for (Item it : items) {
publishProgress(it);
}
return(null);
}
protected void onProgressUpdate(Item... item) {
adapter.add(item[0]);
}
protected void onPostExecute(Void unused) {
//dismiss the alert here where the thread has finished his work
pDialog.dismiss();
}
}
well in AsyncTask in the on postexecute you can call dismiss
here is an example from other thread
class AddTask extends AsyncTask<Void, Item, Void> {
protected void onPreExecute() {
pDialog = ProgressDialog.show(MyActivity.this,"Please wait...", "Retrieving data ...", true);
}
protected Void doInBackground(Void... unused) {
items = parser.getItems();
for (Item it : items) {
publishProgress(it);
}
return(null);
}
protected void onProgressUpdate(Item... item) {
adapter.add(item[0]);
}
protected void onPostExecute(Void unused) {
pDialog.dismiss();
}
}

progressbar in android with thread

I am build one application in which, I can get data from a server so simply I want to put progress bar on it but I can't give specific time duration. it is dismiss randomly while fetch entire data from server. so can you tell me how can I do this ?
can you give one simple example with elaboration
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.event_detail);
pd = ProgressDialog.show(this, "Please Wait", "Loading ....", true,true);
Thread thread = new Thread(this); //Implment Runnable;
thread.start();
// setData();
}
#Override
public void run()
{
//Do your all work except User Interface Updation
han.sendEmptyMessage(0);
}
private Handler han=new Handler()
{
#Override
public void handleMessage(Message msg)
{
dismiss dialog
}
};
You can use these http://developer.android.com/reference/android/widget/ProgressBar.html sample but it's better to integrate with async task Example of async task and since you don't know how long it will take just use the onPostExecute to close the progress.
hope it helps
What you need is to combine AsynTask and indeterminate ProgressDialog together. Something like this:
private class DownloadTask extends AsyncTask<...> {
private ProgressDialog progressBar;
protected void onPreExecute() {
progressBar = ...;
progressBar.show();
}
protected Long doInBackground() {
// blah blah
}
protected void onPostExecute() {
progressBar.dismiss();
}
}
Don't forget to handle if user wants to cancel the progress.
U can use AsyncTask
private class Myclass extends AsyncTask<Void, Integer, Void> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
pDialog= ProgressDialog.show(context, "", "loading...");
pDialog.show();
super.onPreExecute();
}
#Override
protected Long doInBackground(Void... unused) {
// your code here
return null;
}
#Override
protected void onPostExecute(Void unused) {
pDialog.dismiss();
}
}

Categories

Resources