Dismissing ProgessDialog on Android - android

I've been to get rid of a ProgressDialog for some time now. After some googling and reading through questions on stackoverflow I round that I can only run ProgressDialog.dismiss() from the UI Thread. After some more reading I learned I need to create a handler and attach it to the UI Thread like this: new Handler(Looper.getMainLooper()); but alas, the stubborn ProgressDialog still refuses to die.
Here's what my code looks like:
/* Members */
private ProgressDialog mProgressDialog;
private Handler mHandler;
/* Class' constructor method */
public foo() {
...
this.mHandler = new Handler(Looper.getMainLooper());
...
}
/* The code that shows the dialog */
public void startAsyncProcessAndShowLoader(Activity activity) {
...
mProgressDialog = new ProgressDialog(activity, ProgressDialog.STYLE_SPINNER);
mProgressDialog.show(activity, "Loading", "Please wait...", true, false);
doAsyncStuff(); // My methods have meaningful names, really, they do
...
}
/* After a long process and tons of callbacks */
public void endAsyncProcess() {
...
mHandler.post(new Runnable() {
#Override
public void run() {
Log.d(TAG, "Getting rid of loader");
mProgressDialog.dismiss();
mProgressDialog = null;
Log.d(TAG, "Got rid of loader");
}
});
...
}
This doesn't seem to work, debugging shows that certain members of the PorgressDialog (mDecor) are null. What am I missing?

You should use the AsyncTask to do your async task:
AsyncTask task = new AsyncTask<Void, Void, Void>() {
private Dialog mProgressDialog;
protected void onPreExecute() {
mProgressDialog = new ProgressDialog(activity, ProgressDialog.STYLE_SPINNER);
mProgressDialog.show(activity, "Loading", "Please wait...", true, false);
}
protected Void doInBackground(Void... param) {
doAsyncStuff(); // My methods have meaningful names, really, they do
return null;
}
protected void onPostExecute(Void result) {
mProgressDialog.dismiss();
}
};
task.execute(null);

progressDialog.setCancelable(true);
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
Log.d(TAG, "Got rid of loader");
}
});

Try this:
public static final int MSG_WHAT_DISMISSPROGRESS = 100;
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg){
swtich(msg.what){
case MSG_WHAT_DISMISSPROGRESS:
mProgressDialog.dismiss();
break;
}
}
}
public void endAsyncProcess(){
handler.obtainMessage(MSG_WHAT_DISMISSPROGRESS).sendToTarget();
}

Related

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

ProgressDialog in a separate thread

I have a procedure that extracts data from a database and populates it to the list. I want to display progress dialog box while query is executed, but it visually appears only after the query is executed. I believe I have to run a ProgressDialog in a separate thread, but followed few suggestions and could not make it work.
So in my Activity I just have
private void DisplayAllproductListView(String SqlStatement) {
ProgressDialog dialog =
ProgressDialog.show(MyActivity.context, "Loading", "Please wait...", true);
//..................
//..................
//execute sql query here
dialog.dismiss();
}
thanks
1.show your process dialog in main thread
2.start a new thread (such as Thread A) to process your heavy job
3.when done, use handler to send a message from Thread A to main thread, the latter dismisses the process dialog
code like this
private ProcessDialog pd;
private void startDialog()
{
pd = ProgressDialog.show(MainActivity.this, "title", "loading");
//start a new thread to process job
new Thread(new Runnable() {
#Override
public void run() {
//heavy job here
//send message to main thread
handler.sendEmptyMessage(0);
}
}).start();
}
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
pd.dismiss();
}
};
Try something like this:
private class MyAwesomeAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog mProgress;
#Override
protected void onPreExecute() {
//Create progress dialog here and show it
}
#Override
protected Void doInBackground(Void... params) {
// Execute query here
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//update your listView adapter here
//Dismiss your dialog
}
}
To call it:
new MyAwesomeAsyncTask().execute();
All you need to do, is to tell Android to run it on the main UI thread. No need to create a Handler.
runOnUiThread(new Runnable() {
public void run() {
progressDialog.dismiss();
}
});

Android Async task porgress bar doesn't comes until background process is completed

I am building a project in which i use async task to show progress bar.
I am using get() method to wait the main thread so we can do the other task before .
but progress bar is showing after completion of doInBackground thered.
I Want to show the loading bar when the loading starts.
It will dismiss when onPostExecute calls.
public class TempConverterActivity extends Activity {
pojo p;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b= (Button) findViewById(R.id.btn);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showResult();
}
});
}
private void showResult() {
try {
new LoadData().execute().get();
} catch (Exception e) {
Log.e("async brix--", e.getMessage());
}
runned();
}
private void runned() {
ArrayList<String> al = p.getData();
for (String str : al){
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
}
}
private class LoadData extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(TempConverterActivity.this);
protected void onPreExecute() {
dialog.setMessage("Loading data...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
protected void onPostExecute(final Void unused) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
#Override
protected Void doInBackground(Void... params) {
p = new pojo();
new SoapParser(p);
return null;
}
}}
Please help . Thanks in advance.
You can try following code,
progDailog = ProgressDialog.show(loginAct,"Process ", "please wait....",true,true);
new Thread ( new Runnable()
{
public void run()
{
// your code goes here
}
}).start();
Handler progressHandler = new Handler()
{
public void handleMessage(Message msg1)
{
progDailog.dismiss();
}
}
Edited: In my previous answer I suggested using a Handler; however, AsyncTask eliminates the need to do this which I didn't spot.
Why do you feel the need to call AsyncTask.get()? This is a blocking call, and you call this from the UI thread, thus it is ultimately a race condition as to whether it or onPreExecute() is run first.
I see no reason why you should call get() in this context. You want to call runned() after the AsyncTask completes, but you could do this by launching a new thread from onPostExecute(). Alternatively you could do as you do now, using get(), but call that from a new thread instead of the UI thread.

Android: Thread with progressBar and setcurrentTab

final ProgressDialog Pdialog = ProgressDialog.show(SpinnerClass.this, "",
"Loading. Please wait...", true);
Thread ProgressThread = new Thread() {
#Override
public void run() {
try {
sleep(3000);
Pdialog.dismiss();
} catch(InterruptedException e) {
// do nothing
} finally {
}
}
};
ProgressThread.start();
TabHost1 TabHost1Object2 = new TabHost1();
TabHost1Object2.tabHost.setCurrentTab(2);
The problem I have with this thread is that it sets the current tab before the progress dialog starts. What have i done wrong ?
I want the dialog to run and dismiss, and after thread is done set tab.
use AsyncTask for this
some hints:
public class BackgroundAsyncTask extends AsyncTask<Void, Integer, Void> {
int myProgress;
#Override
protected void onPostExecute(Void result) {
TabHost1 tab = new TabHost1();
tab.tabHost.setCurrentTab(2);
progressBar.dismiss();
}
#Override
protected Void doInBackground(Void... params) {
while(myProgress<100){
myProgress++;
publishProgress(myProgress);
SystemClock.sleep(100);
}
return null;
}
#Override
protected void onProgressUpdate(Integer p) {
progressBar.setProgress(p);
}
}
The thing is that,you are starting a thread which will not affect your main UI. So what eventually happens is that, your thread will run separately which will now allow the next lines of your code to be executed. So in your case,
TabHost1 TabHost1Object2 = new TabHost1();
TabHost1Object2.tabHost.setCurrentTab(2);
these lines will be executed irrespective to your thread which is also getting executed simultaneously. So what you can do here is you can either go for AsyncTask or create handlers to handle this part of your code. You have to change your code like this.
Do this in your onCreate()
Handler handler;
handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (msg.what == 0) {
Pdialog.dismiss();
TabHost1 TabHost1Object2 = new TabHost1();
TabHost1Object2.tabHost.setCurrentTab(2);
}
};
And now in your thread,call the handler like this,
final ProgressDialog Pdialog = ProgressDialog.show(SpinnerClass.this, "",
"Loading. Please wait...", true);
Thread ProgressThread = new Thread() {
#Override
public void run() {
try {
sleep(3000);
} catch(InterruptedException e) {
// do nothing
} finally {
handler.sendEmptyMessage(0);
}
}
};
this will allow your tabhost to wait until the thread gets executed and will come into view after thread finishes execution.

Problem with a ProgressDialog

I don't understand the following error:
Activity [myActivity] has leaked window
com.android.internal.policy.impl.PhoneWindow$DecorView#4050c3f8 that was
originally added here
Here is my code:
private ProgressDialog progression;
private Handler handler;
private Thread thread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Conteneur général
ui = new RelativeLayout(this);
progression = ProgressDialog.show(this, "SwissParl", "Init", true);
handler = new Handler() {
public void handleMessage(Message msg) {
progression.dismiss();
}
};
thread = new Thread() {
public void run() {
firstMethod();
SecondOne();
andTheLast();
handler.sendEmptyMessage(0);
}
};
thread.start();
setContentView(ui);
}
Apparently, the problem is on the line where I instanciate my ProgressDialog...
Any idea?
That happens normally when the activity is destroyed when showing a dialog, for example rotation or finishing activities while showing dialogs.
Try adding a dismiss dialog onPause of activity.
I'm not sure what the problem is, but i suggest you use an AsyncTask
Something like this
private class MyBackgroundTask extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(ParentActivity.this);
#Override
protected Void doInBackground(Void... param) {
firstMethod();
SecondOne();
andTheLast();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(dialog.isShowing())
dialog.dismiss();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//dialog.setCancelable(false); //depending...
dialog.setMessage("Please Wait...");
dialog.show();
}
}
To execute it, call new MyBackgroundTask().execute() inside onCreate()
It's far cleaner than using a handler,thread combination...
private ProgressDialog progression;
private Handler handler;
private Thread thread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Conteneur général
ui = new RelativeLayout(this);
setContentView(ui);
progression = ProgressDialog.show(this, "SwissParl", "Init", true);
handler = new Handler() {
public void handleMessage(Message msg) {
progression.dismiss();
}
};
thread = new Thread() {
public void run() {
firstMethod();
SecondOne();
andTheLast();
handler.sendEmptyMessage(0);
}
};
thread.start();
}
You are trying to show a ProgressDialog before adding the main view to the activity.Use the setContentView before you start the ProgressDialog

Categories

Resources