user739375
user739375

Reputation: 239

Progress Bar Problem in Android

My app contained download button and whenever that button is pressed, I want some Progress Bar to show up so that the user knows there is something happening. What I really want to do is, whenever the Progress Bar is finished, I want some Toast to pop out. Can some one guide me with this? I would really appreciate it a lot. Thanks in advance!

Here is the code I am using:

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final ProgressDialog dialog = new ProgressDialog(MyActivity.this);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setMessage("Downloading...");
        dialog.setCancelable(true);
        dialog.setMax(200);
        dialog.setProgress(0);
        dialog.show();

        Thread t = new Thread(new Runnable(){
            public void run() {
                while(dialog.getProgress() < dialog.getMax())
                {
                    dialog.incrementProgressBy(1);
                    try{Thread.sleep(50);}catch(Exception e){/* no-op */}
                }
                dialog.dismiss();
            }
        });
        t.start();
    }

Upvotes: 0

Views: 891

Answers (4)

Pinakin Shah
Pinakin Shah

Reputation: 877

You cannot run long tasks on UI thread. Create a background thread with Async Task but you cannot do a toast in a background thread.

Async task will notify when the task is complete.

I think Async task has the following methods.

onBackground onProgressUpdate PreExecute PostExecute (put a toast here)

Upvotes: 0

Umesh
Umesh

Reputation: 4256

AsyncTask would be the easiest but if you are adamant on using your code you can add this snippet after the dialog.dismiss() statement.

  runOnUiThread(new Runnable(){
        public void run() {
            Toast.makeText(YourClassName.this, "task finished", Toast.LENGTH_LONG).show();  
        }

  }); 

This is because the Toast must only be shown on the UI Thread.

Upvotes: 1

Rasel
Rasel

Reputation: 15477

After dialog.dismiss(); write

Toast.makeText(getApplicationContext(),"finish",Toast.LENGTH_LONG).show();

Upvotes: 0

Related Questions