ProgressDialog/ProgressBar
How do we update progressDialog
or progressBar
when app receives data(from web) ?
We need two classes. One is MainViewActivity
class another is WebServiceAPI
class
- MainViewActivity is main View activity that is responsible for show progressbar.
public class MainViewActivity extends Activity implements WebServiceAPI.OnProductDataReceivedListener
{
private ProgressBar mProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.main_view, null);
Util.WebServiceAPI.addProductDataReceivedListener(this); // Add Data Received Listener
mProgressBar = (ProgressBar)view.findViewById(R.id.progressBar);
runWebService();
}
@Override
public void onDataReceive(long total, long current)
{
final int max = (int)total;
mProgressBar.setMax(max);
final int progress = (int)current +1;
runOnUiThread(new Runnable() {
@Override
public void run() {
mProgressBar.setProgress(progress);
}
}
);
}
}
- WebServiceAPI is responsible for receiving data from web and notice the caller by interface event. Notice:
Thread.sleep(100)
is very import. If you don't using Thread.sleep, the progress bar UI will not update fluently.
public class WebServiceAPI
{
private static List<OnProductDataReceivedListener> _OnProductDataReceivedListener = new ArrayList<OnProductDataReceivedListener>();
public interface OnProductDataReceivedListener
{
abstract void onDataReceive(long total, long current);
}
public static void addProductDataReceivedListener(OnProductDataReceivedListener listener)
{
_OnProductDataReceivedListener.add(listener);
}
public static void removeProductDataReceivedListener(OnProductDataReceivedListener listener)
{
_OnProductDataReceivedListener.remove(listener);
}
public static void clearProductDataReceivedListener()
{
_OnProductDataReceivedListener.clear();
}
public static void runWebService()
{
//1. Run Web Service
//blabla
//We Assiume the data total is 100;
int count = 100;
for (int index = 0 ; index < count ; index++)
{
_OnProductDataReceivedListener.get(0).onDataReceive(count, index);
Thread.sleep(100); //This is very import. If you don't using sleep, the progress bar UI will not update fluently.
}
}
}