i want to show in my activity a progress bar as a response to a button click.
i read in another question that i should use async task in order to show/not show the progress bar but when i click on the button the progress bar is not shown properly (it appears for much less time then it should)
any suggestions?
the activity code:
public void chooseContactFromList(View view){
ProgressBar pBar = (ProgressBar) findViewById(R.id.progressBar1);
circleActivity progressTask = (circleActivity) new circleActivity(pBar).execute();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
CharSequence[] cs=nameList.toArray(new CharSequence[nameList.size()]);
builder.setTitle("Make your selection");
builder.setItems(cs, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
reciverNumber = phoneList.get(item);
}
});
AlertDialog alert = builder.create();
alert.show();
progressTask.cancel(true);
}
the AsyncTask code:
public class circleActivity extends AsyncTask<Void, Void, Void> {
private ProgressBar progressBar;
public circleActivity(ProgressBar pBar) {
progressBar=pBar;
}
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(Void result) {
progressBar.setVisibility(View.INVISIBLE);
}
#Override
protected void onProgressUpdate(Void ... progress) {
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
return null;
}
}
thanks
As you are doing nothing in the doInBackground(), the progressBar is shown for few moments only. If you really want to see it, then try doing some operation in doInBackground() which will take some time.
eg. Try Thread.sleep(1000); in doInBackground to test it.
And I suggest you to refer following links.
http://www.vogella.com/articles/AndroidBackgroundProcessing/article.html
http://developer.android.com/reference/android/os/AsyncTask.html
Related
How to show a dialog box in AsyncTask. Getting BadToketException in dialog.show();
I tried many ways but I could not solve it.
Also tried to pass context to the dialog box in different ways, but it is giving me the same result.
public class RetriveStock extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
message = client.clientReceive(1); // I get data here.
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPostExecute(Void result) {
if (message.contains("AlertExecuted:")) {
final Dialog dialog = new Dialog(CreateAlert.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.display_dialog);// Dialog layout
TextView dialogText = (TextView) dialog.findViewById(R.id.digMsg);
dialogText.setText("Alert Executed!");
Button ok = (Button) dialog.findViewById(R.id.ok);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
try {
dialog.show(); //WindowManager$BadTokenException
} catch (Exception e) {
e.printStackTrace();
}
}
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
Please help.
protected void onPreExecute() {
// TODO Auto-generated method stub
// progressDialog = ProgressDialog.show(this, "", "loading news content");
progressDialog = new ProgressDialog(context , AlertDialog.THEME_HOLO_LIGHT);
progressDialog.setMessage(""+getString(R.string.laodnews));
progressDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.animate));
progressDialog.setCancelable(false);
progressDialog.show();
}
start dailoge in pre execute and stop in onpostexecute..
is CreateAlert registered activity in manifest..if not then you have to pass registered activity context
I know that there are many similar AsyncTask questions already, but in my case something is very unusual or am I missing something !?
As the AsyncTask is not allowed to run more than once. I call it with new B().execute(); so it should create a separated instance on each run !? Right?
The problem is after the B class is created and executed once, it wont work the second time the user calls the startBClass() method (just opens the dialog, but the actual work is not happening).
I just Debugged the code and realize that after the Dialog is closed, the Thread is still running in the background. What is the proper way to stop the background thread when the Dialog is closing? - And since I'm closing the first Dialog inside B class and create another instance of the B class, why is the second one not working? Can't multiple AsyncTasks run in parallel !?
I simplified the classes for easier understanding what I'm trying:
public class A {
/* Is called when user clicks a button */
private void startBClass() {
new B().execute();
}
/* Opens a Dialog with a countdown TextView (works first call only) */
private class B extends AsyncTask<Void, Integer, Void> {
private int secondsPassed = 0;
private double totalToPay = 0;
private Dialog dialog;
private TextView tvCost;
private Button dialogBtn;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new Dialog(ConfigurationActivity.this);
dialog.setCancelable(true);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog);
dialog.setCanceledOnTouchOutside(false);
dialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
onPostExecute(null);
}
});
tvCost = (TextView) dialog.findViewById(R.id.textCounter);
dialogBtn = (Button) dialog.findViewById(R.id.button1);
dialogBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.cancel();
}
});
dialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
while(true){
publishProgress(secondsPassed++);
SystemClock.sleep(1000);
}
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
totalToPay = 12.00;
tvCost.setText(totalToPay + " USD");
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
final AlertDialog alert = new AlertDialog.Builder(ConfigurationActivity.this).create();
alert.setTitle("Information");
alert.setMessage("You should pay about " + totalToPay + " USD.");
alert.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface alertDialog, int which) {
alertDialog.dismiss();
}
});
alert.show();
}
}
}
dialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
onPostExecute(null);
}
});
This is no good. Per the docs:
Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually.
To end it, I'd change both the code above, and the while loop in doInBackground().
protected Void doInBackground(Void... arg0) {
while(running){
publishProgress(secondsPassed++);
SystemClock.sleep(1000);
}
}
running is a boolean you set to true in onPreExecute(). Set it to false when you want to end it. Then your loop will exit and onPostExecute() will be called correctly.
Side note: Where is secondsPassed ever used?
i want to add a progress Dialog button when i click on this button before the new activity apperar, i think i don't need a thread, i did search but i find only that i need to do a thread and many other think it s not clear
i just want when i clik on a progress Dialog say to the user to wait so a few sec the other activity will appear that's all:
btn_newsfeed.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Launching News Feed Screen
Intent i = new Intent(getApplicationContext(), CustomizedListView.class);
startActivity(i);
}
});
There are three different different ways in which you can use a ProgressDailog -using threads, handlers and async tasks.
here a example of async task for using a progress Dialog
private class Operation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params)
{
// code to be executed in background thread
for(int i=0;i<5;i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
// runs on UI thread and updated UI after executing doInBackground
progressDialog.dismiss();
}
#Override
protected void onPreExecute() {
ProgressDialog progressDialog = ProgressDialog.show(MainActivity.this, "Title ", "Loading...");
progressDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
// runs on UI thread and starts first
}
}
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.
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();
}
}