I have an AsyncTask linked to a refresh Button (when I click on my refresh button my AsyncTask is called).
I have on my Layout a LinearLayout field for my ProgressBar :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="@color/grey">
<Button android:id="@+id/refresh_p"
android:text="@string/refresh_promo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/custom_button1"/>
<LinearLayout android:id="@+id/linearlayoutProgressBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"/>
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:listSelector="@color/tabTransparent"
android:cacheColorHint="#00000000"/>
<!-- <ListView android:id="@+id/list_promo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>-->
</LinearLayout>
In my AsyncTask :
@Override
protected void onPreExecute()
{
super.onPreExecute();
pb = new ProgressBar(context);
LinearLayout ll = (LinearLayout) ((Activity) context).findViewById(R.id.linearlayoutProgressBar);
ll.addView(pb);
pb.setVisibility(View.VISIBLE);
}
@Override
protected void onPostExecute(ArrayList<HashMap<String, String>> promoList)
{
...
if (pb!=null)
{
pb.setVisibility(View.GONE);
((LinearLayout)pb.getParent()).removeView(pb);
}
}
The problem I have is when I make more than 2 clicks on my Refresh Button then Multiple ProgressBar are displaying into the screen.. I just want that the new ProgressBar replace the old at the same position ..
My guess is that you are probably starting your AsyncTask in a manner similar to this:
Instead of that, create an instance variable in your activity. Let’s say this is named mTask and substitute the above code for the following call:
This way you will ensure that only one instance of your task is running at a given time and the user will have to wait until the refresh is finished before he can start a new refresh.
If you want the user to be able to cancel an existing refresh task and run a new one, you will have to cancel the old one before starting a new one:
This way the old task and it’s ProgressBar will be properly replaced by the new one.