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.
Related
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();
}
In my Activity, I load the content for a list from a DB, and want to display a ProgressDialog while it´s loading.
I got both working on it´s own, but if I load the data in a thread (which I should do?), the list is displayed before it´s data is loaded. But if I use join, the ProgressDialog doesnt even appear.
How can I combine this? Or is this not possible at all with threads? (AsyncTask maybe?)
Here´s the code for reference:
final ProgressDialog progressD=ProgressDialog.show(ShopSwitchActivity.this, "", "Loading..", true);
Thread myThread = new Thread(new Runnable() {
#Override
public void run() {
try
{
getData();
}catch(Exception e){}
}
});
myThread.start();
try {
myThread.join();
} catch (InterruptedException e) {
}
progressD.dismiss();
EDIT: Updated Code with AsyncTask:
public class LoadList extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
ShopSwitchActivity activity;
public LoadList(ShopSwitchActivity activity) {
this.activity = activity;
dialog = new ProgressDialog(activity);
}
protected void onPreExecute() {
this.dialog.setMessage("Loading...");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
protected Boolean doInBackground(final String... args) {
try{
activity.getData();
} catch (Exception e) {
Log.e("error", e.getMessage());
}
return true;
}
}
Edit: My Solution
Using AsyncTask now to load the Data, and after it´s done, I refresh the list with the new data.
You can do it with AsyncTask. Write AsyncTask class in your main class that you want to do your operations. You can create the progress dialog in preexcecute of your async class and dismiss in onpostexecute of async class. Here is how you will do this:
class MyAsync extends AsyncTask<String, Void, Void> {
ProgressDialog pd;
Context co;
MyActivity ma;
public MyAsync (MyActivity ma){
this.ma= ma;
this.co = ma;
pd= new ProgressDialog(co);
}
#Override
protected void onPreExecute() {
this.pd.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
// do your database operations here
return null;
}
#Override
protected void onPostExecute(Void result) {
// show db results and dismiss progress dialog pd.dismiss();
super.onPostExecute(result);
}
}
in MyActivity call as :
MyActivity ma = this;
new MyAsync(ma).execute();
You seem to miss the point of a thread. A thread occurs at the same time as your application. So your app doesn't call start then wait for the thread to be over- if it did you could just use a function. Instead your code continues to run. So if you just call join immediately, you're not doing anything. You'd get around a NetworkOnMainThreadException this way, but you'd still hold up the UI thread making your app totally non-responsive (and as a result not showing the dialog), and you'd eventually crash when a watchdog timer kills you.
Instead, the best way to handle this is to use an AsyncTask. Call getData in doInBackground(). Then dismiss the dialog in onPostExecute.
You should use AsyncTask instead actually.
Here is the link to the library. It is fairly simple:
1) onPreExecute() = show ProgressDialog
2) doInBackground() = execute your code
3) onPostExecute() = dismiss ProgressDialog
Here's a nice tutorial too.
In general:
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(this.context);
dialog.setMessage("Loading...");
dialog.setCanceledOnTouchOutside(false);
}
#Override
protected void onPostExecute(String result) {
if(dialog.isShowing()) {
dialog.dismiss();
}
}
private Thread myThread;
private ProgressDialog mProgDialog;
mProgDialog = ProgressDialog.show(ShopSwitchActivity.this,"","Laden..", true);
myThread= new Thread(new Runnable()
{
public void run()
{
myThread.setPriority(Thread.MIN_PRIORITY);
try
{
getData();
}catch(Exception e){}
runOnUiThread(new Runnable()
{
public void run()
{
if (mProgDialog != null&& mProgDialog.isShowing())
mProgDialog.dismiss();
} }
});
}
});
myThread.start();
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();
}
});
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
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.