Cancel ProgressDialog and stop thread - android

I have a thread that run several operations once and I would like to stop it when the user cancels the ProgressDialog.
public void run() {
//operation 1
//operation 2
//operation 3
//operation 4
}
This thread runs only once, so I can't implement a loop to check if he thread should still be running.
Here is my ProgressDialog :
//Wait dialog
m_dlgWaiting = ProgressDialog.show(m_ctxContext,
m_ctxContext.getText(R.string.app_name),
m_ctxContext.getText(R.string.msg_dlg_analyse_pic),
true, //indeterminate
true,
new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
m_bRunning = false;
}
});
As I don't know how to stop the thread, would it be correct to sequence the thread's operations through a loop to see if it should still be running, or is there a better way ?
public void run() {
int op = 0;
while(m_bRunning) {
switch(op) {
case 0 :
//operation 1
break;
case 1 :
//operation 2
break;
case 2 :
//operation 3
break;
case 3 :
//operation 4
break;
}
op++;
}
}
Even with this solution, if there are too much operations in the thread, it could be hard to sequence the operations. Is there a better way to achieve this ?

Use callbacks or AsyncTask
http://developer.android.com/reference/android/os/AsyncTask.html
final AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
private ProgressDialog dialog;
#Override
protected void onPreExecute()
{
this.dialog = new ProgressDialog(context);
this.dialog.setMessage("Loading...");
this.dialog.setCancelable(true);
this.dialog.setOnCancelListener(new DialogInterface.OnCancelListener()
{
#Override
public void onCancel(DialogInterface dialog)
{
// cancel AsyncTask
cancel(false);
}
});
this.dialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
// do your stuff
return null;
}
#Override
protected void onPostExecute(Void result)
{
//called on ui thread
if (this.dialog != null) {
this.dialog.dismiss();
}
}
#Override
protected void onCancelled()
{
//called on ui thread
if (this.dialog != null) {
this.dialog.dismiss();
}
}
};
task.execute();

You can use Asynctask like below
FetchRSSFeeds fetchRss = new FetchRSSFeeds()
fetchRss.execute();
private class FetchRSSFeeds extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(HomeActivity.this);
/** progress dialog to show user that the backup is processing. */
/** application context. */
protected void onPreExecute() {
this.dialog.setMessage(getResources().getString(
R.string.Loading_String));
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
try {
/**
* Write your RUN method code here
*/
if (isCancelled()) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
return true;
} catch (Exception e) {
Log.e("tag", "error", e);
return false;
}
}
#Override
protected void onPostExecute(final Boolean success) {
}
}
And when you want to cancel your background process do below
if (fetchRss.getStatus() == AsyncTask.Status.RUNNING) {
fetchRss.cancel(true);
}

Related

AlertDialog not showing in AsyncTask

I have an activity with a button that starts an AsyncTask:
public void search(View view) {
if (searchTask != null) {
return;
}
searchTask = new SearchTask(this);
searchTask.execute((Void)null);
}
And this is the task:
public class SearchTask extends AsyncTask<Void, Void, Boolean> {
private final Activity activity;
private final ProgressDialog dialog;
public SearchTask(Activity activity) {
this.activity = activity;
this.dialog = new ProgressDialog(activity);
}
#Override
protected Boolean doInBackground(Void... params) {
try {
wait(3000);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
#Override
protected void onPreExecute() {
dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing())
dialog.dismiss();
}
}
I'm not calling get() so I shouldn't be blocking the UI thread. The problem is that the progress dialog is not being shown.
Is this not the correct way to show a dialog within an AsynTask?
wait() causes IllegelMonitorException. to apply a delay in the task Thread.sleep() should be used.
try after removing return; from below code-
public void search(View view) {
if (searchTask != null) {
return;
}
searchTask = new SearchTask(this);
searchTask.execute((Void)null);
}

Show progressDialog in Android

I want to show a progressDialog on my page when the user clicks on the button.On click of button i am sorting my results that is a List.Now how can we show a progressDialog on click of a button.Please suggest me
This function i am using to sort that data :
public void sortByDate(View v) {
Collections.sort(tripParseData.getDetails());
setData(tripParseData);
}
After #Monica Suggestion
public void sortByDate(View v) {
new LoadData().execute();
}
class LoadData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
Collections.sort(tripParseData.getCoroprateBookingDetails());
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
progressDialog.dismiss();
setApprovalDetailsData(tripParseData);
}
}
you have to call progressdiolog.show before the long calculation starts and then the calculation has to run in a separate thread. A soon as this thread is finished, you have to call pd.dismiss() to close the prgoress dialog.
here you can see an example:
the progressdialog is created and displayed and a thread is called to run a heavy calculation:
Override
public void onClick(View v) {
pd = ProgressDialog.show(lexs, "Search", "Searching...", true, false);
Search search = new Search( ... );
SearchThread searchThread = new SearchThread(search);
searchThread.start();
}
and here the thread:
private class SearchThread extends Thread {
private Search search;
public SearchThread(Search search) {
this.search = search;
}
#Override
public void run() {
search.search();
handler.sendEmptyMessage(0);
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
displaySearchResults(search);
pd.dismiss();
}
};
}
Don't forget to vote me up :)
Paste This Class in ur activity and call new LoadData().execute to start the prgress dialog :
class LoadData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
ProgressDialog pg=new ProgressDialog(ChartsActivity.this);
pg=pg.show(ChartsActivity.this, "Loding", "Plz Wait...");
}
#Override
protected Void doInBackground(Void... params) {
sortByDate();
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pg.dismiss();
}
}
I have not tested it but I think it can help you.
Declare these two objects in your class and member variables.
Thread thread = null;
ProgressDialog bar = null;
Use this logic on your button click listener it can work in your case. I have not tested it but It will give you Idea how things should work. you can also use handlemessage in place of runonuithread
if (thread == null
|| (thread != null && !thread.isAlive())) {
thread = new Thread(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
//DISPLAY YOUR PROGRESS BAR HERE.
bar = ProgressDialog.show(getApplicationContext(), "LOADING..", "PLEASE WAIT..");
}
});
// SORT COLLECTION HERE
runOnUiThread(new Runnable() {
#Override
public void run() {
//CLOSE YOUR PROGRESS BAR HERE.
bar.dismiss();
}
});
}
});
thread.start();
}
Hope this will help you.
try to use AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html
Sample code:
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
//Show UI
//Start your progress bar
showProgress();
}
#Override
protected Void doInBackground(Void... arg0) {
// do your sorting process
return null;
}
#Override
protected void onPostExecute(Void result) {
//Show UI
//dismiss your progress bar
hideProgress();
}
};
task.execute((Void[])null);
Show and hide progress code
public void showProgress() {
progressDialog = ProgressDialog.show(this, "",
"Loading. Please wait...");
progressDialog.setCancelable(false);
}
public void hideProgress() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}

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

My ProgressDialog doesn't dismiss even after the view has been loaded.

I want to show a Progress-Dialog before my view has been loaded.
First i wrote the code in onCreate() but the dialog doesn't appear in that case. So i wrote it in onResume() but in this case, it doesn't disappear even after the view has been loaded. can anyone tell whats going wrong here?
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
dialog = ProgressDialog.show(this, "", "Please wait...", true);
//dialog.cancel();
new Thread()
{
public void run()
{
try
{
sleep(1500);
// do the background process or any work that takes time to see progress dialog
}
catch (Exception e)
{
Log.e("tag",e.getMessage());
}
// dismiss the progressdialog
dialog.dismiss();
}
}.start();
citySelected.setText(fetchCity);
spinner.setSelection(getBG);
}
You cant update UI(which is in main UIthread) from other threads. If you want to run any query in the background, you can use AsyncTask.
In onPreExecute method, show dialog and onPostExecute you can dismiss the dialog.
If you want to use Thread, then update UI using handlers.
Using AsyncTask
public class MyAsyncTask extends AsyncTask<String, Void, String> {
ProgressDialog dialog = new ProgressDialog(ActivityName.this);
#Override
protected void onPreExecute() {
dialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
super.onPostExecute(result);
}
}
In Activity onCreate Method,
MyAsyncTask task = new MyAsyncTask();
task.execute();
better to use Asynctask ......... but if you still want same or want to know the solution only then can try
new Thread()
{
public void run()
{
try
{
sleep(1500);
// do the background process or any work that takes time to see progress dialog
}
catch (Exception e)
{
Log.e("tag",e.getMessage());
}
YourActivity.this.runOnUIThread(new Runnable(){
#Override
public void run(){
// dismiss the progressdialog
dialog.dismiss();
});
}
}.start();
You can use AsyncTask. It is better than Thread
private class DownloadingProgressTask extends
AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(ShowDescription.this);
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
try {
downloadFile(b.getString("URL"));
return true;
} catch (Exception e) {
Log.e("tag", "error", e);
return false;
}
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}

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();
}
}

Categories

Resources