reduce delay in display progress bar - android

As I created a Progress bar using below code in a on click method of button. but after clicking button it takes 2-3 seconds to display progress bar.how to reduce that delay to start progress bar.
public void getProgressBar() {
progressBar = new ProgressDialog(this);
progressBar.setCancelable(true);
progressBar.setMessage("Loading...");
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.show();
progressBarStatus = 0;
new Thread(new Runnable() {
public void run() {
while (progressBarStatus < 100) {
progressBarStatus = doSomeTasks();////I am loading service
progressBarHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
if (progressBarStatus >= 100 ) {
progressBar.dismiss();
startActivity(new Intent(getApplicationContext(),
StatisticDisplay.class));
}
}
}).start();
}

public class BackgroundAsyncTask extends AsyncTask<Void, Integer, Void> {
int myProgress;
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
myProgress = 0;
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
while(myProgress<100){
myProgress++;
publishProgress(myProgress);
SystemClock.sleep(100);
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
progressBar.setProgress(values[0]);
}
}

Use an AsyncTask instead. The example code in the link gives a good introduction on how to do it. In essence you do the job in doInBackground(), publish your progress using onProgressUpdate() and start your activiy in onPostExecute().

Related

Progress Bar Remains At 0%

I have tried to implement Async to handle the background unzipping of files with a progresbar however the unzip is happening while the progressbar displays 0%, after the unzipping the progresbar dismisses at 0%.. the onProgressUpdate method is not updating. my code below:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ib = (ImageButton) findViewById(R.id.ImageButton01);
ib.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
new DownloadFileFromURL().execute(file_url);
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
System.out.println("DIALOG:");
switch (id) {
case progress_bar_type: //
pDialog = new ProgressDialog(this);
pDialog.setMessage("Extracting. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
private void fileZ()
{
// TODO Auto-generated method stub
String zipFile = myDEST + myFolderImages + myFILEposterZIP;
String unzipLocation = myDEST + myFolderImages;
Decompress d = new Decompress(zipFile, unzipLocation);
d.unzip();
System.out.println("UNZIPPING");
}
class DownloadFileFromURL extends AsyncTask<String, String, String> {
#SuppressWarnings("deprecation")
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
fileZ();
return null;
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
#SuppressWarnings("deprecation")
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
}
}
}
Edit #1:
class ExtractFiles extends AsyncTask<String, String, String> {
#SuppressWarnings("deprecation")
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... f_url) {
// TODO Auto-generated method stub
Thread thread = new Thread()
{
public void run()
{
int prog = 0;
while(prog < 100)
{
pDialog.setProgress(prog);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
prog ++;
}
}
};
thread.start();
System.out.println("EXTRACTING...");
fileZ();
return null;
}
You don't update correctly your progress bar while you unzip the file..
Use a counter like :
count++;
and update progressbar..
publishProgress((int)((count));

Progress Dialog stops UI thread

I am showing some animation and making network request at the same time. Both are working fine independently. But when I try to place a progress dialog in asynctask the animation is not started until progress dialog until the onPostExecute(). My guess is that as the animation and progressdialog both run on the UI thread so only one can run at a time. Is there a way to show progress dialog and run animation at the same time both on the UI thread?
Here's my code:
public class DailyTarrotActivity extends FragmentActivity {
ImageView imageViewAnimation;
AnimationDrawable spinAnimation;
AnimatorSet set = new AnimatorSet();
FlipImageView imageViewCard;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily_tarrot);
imageViewAnimation = (ImageView) findViewById(R.id.imageViewAnimation);
imageViewAnimation.setBackgroundResource(R.drawable.spin_animation);
imageViewCard = (FlipImageView) findViewById(R.id.imageViewCard);
spinAnimation = (AnimationDrawable) imageViewAnimation.getBackground();
new DailyTarrotAsyncTask().execute();
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
Log.d("start", "focuschange");
if (hasFocus) {
spinAnimation.start();
}
}
public class DailyTarrotAsyncTask extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(DailyTarrotActivity.this);
pd.setCancelable(false);
pd.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
Thread thread = new Thread();
try {//just to mimic downloading behaviour
thread.sleep(10000);//animation starts only after 10 secs
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.dismiss();
Toast.makeText(DailyTarrotActivity.this, "async task finished",
Toast.LENGTH_SHORT).show();
}
}
}

Confused about Simple Asyntask app

I am trying to make a simple AsynTask sample. I can't make it run. When I click the Button, ProgressDialog is supposed to be displayed. But nothing happens. I don't get any Exceptions. Probably I'm missing out a few things.
ProgressDialog dialog=null;
Button btnstart;
MyAsynTask mytask;
static final int SLEEP_TIME=(15*1000)/100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnstart=(Button)findViewById(R.id.button1);
btnstart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mytask=new MyAsynTask();
mytask.execute();
}
});
}
public class MyAsynTask extends AsyncTask<Void, Integer, Void>{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog=new ProgressDialog(MainActivity.this);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
for (int i = 0; i < 100; i++) {
if(isCancelled()){
break;
}
else {
publishProgress(i);
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
dialog.setProgress(values[0]);
}
You are doing it right.
Use Logs in onPreExecute(),doInBackBackground() to see what's happening actually.
Add one more method to Asynctask class
onPostExcute()
{
dialog.dismiss();
}
OnPost method in the asynctask excutes after doinbackgournd method there you need to dismiss the dialog

how to stop AsynchTask in android?

hi guy
m using a asynctask for running a progressbar. i am using it for showing my songs duration.i want that when i press stop Button, the asynctask should be stop and progressbar should reach on initial position.
public class BackgroundAsyncTask extends
AsyncTask<Void, Integer, Void> {
int myProgress;
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
Toast.makeText(AudioPlayer2.this,
"onPostExecute", Toast.LENGTH_LONG).show();
seekbar.setClickable(true);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
Toast.makeText(AudioPlayer2.this,
"onPreExecute", Toast.LENGTH_LONG).show();
myProgress = 0;
//seekbar.setProgress(myProgress);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
while(myProgress<100){
myProgress++;
//seekbar.setProgress(myProgress);
publishProgress(myProgress);
Log.d("AAAAAAAAAAAAAAAAAAAAAAAAAAAAA", bundleDuration);
SystemClock.sleep(2000) ;
}
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
// myProgress=0;
// seekbar.
publishProgress(0);
seekbar.setProgress(0);
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
seekbar.setProgress(values[0]);
}
}
//=====================================
for starting and stopping m using this code
public void onClick(View src) {
switch (src.getId()) {
case R.id.buttonStart:
new BackgroundAsyncTask().execute();
break;
case R.id.buttonStop:
backgrondasynctask.cancel(true);
break;
I think you use wrong method for this example. You can easily implement progress bar. Here is a nice article,http://blog.sptechnolab.com/2011/01/17/android/simple-progress-bar-in-android-using-thread/ contains example to implement progress bar. Through this example you can easily start, stop and play the progress bar.

Android Development: seekbar count down!

Is it possible, if yes how, how do i go from progress 100 to 1 without the user doing anything.
Like for every .05sec seekbar.setProgress(-=1)
So without the user doing anything the seekbar will go down until it reach 1.
Please anser how to do this
Thank-you
class Async extends AsyncTask<Void, Integer, Void>{
ProgressDialog dialog;
public Async(Context ctx) {
dialog = new ProgressDialog(ctx);
dialog.show();
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
dialog.incrementProgressBy(1);
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
dialog.dismiss();
super.onPostExecute(result);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
int i=0;
while (i < 1000) {
publishProgress(1);
i++;
}
return null;
}
}
You may be forced to write your own progress bar. Here's an example: http://techdroid.kbeanie.com/2010/04/custom-progressbar-for-android.html
There's more than one way to do it...
Something roughly like this (note: may not compile):
private int progressStatus = 100;
new Thread(new Runnable()
{
public void run()
{
while (progressStatus > 1)
{
progressStatus = doSomeWork();
//---Update the progress bar---
handler.post(new Runnable()
{
public void run() {
progressBar.setProgress(progressStatus);
}
});
}
handler.post(new Runnable()
{
public void run() {
// Do your thing here when it's done
}
});
}
private int doSomeWork()
{
try
{
//---simulate doing some work---
Thread.sleep(50);
} catch (InterruptedException e)
{
e.printStackTrace();
}
int progress = progressStatus - 1;
return progress;
}
}).start();

Categories

Resources