Skip to content Skip to sidebar Skip to footer

Android Progressdialog Progress Bar Doing Things In The Right Order

I just about got this, but I have a small problem in the order of things going off. Specifically, in my thread() I am setting up an array that is used by a Spinner. Problem is the

Solution 1:

Don't know if you've ever solved this, but this works for me:

publicclassStartextendsActivity {
privatestaticfinalStringTAG="PriceList";

ArrayAdapter<ProductCategory> category_adapter;
ArrayAdapter<ProductGroup> group_adapter;

ArrayList<ProductCategory> categories;
ArrayList<ProductGroup> groups;

ArrayList<Price> prices;

Spinner group_spinner;
Spinner category_spinner;
ProgressDialog progressDialog;

/** Called when the activity is first created. */@OverridepublicvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    group_spinner = (Spinner) findViewById(R.id.group_spinner);
    category_spinner = (Spinner) findViewById(R.id.category_spinner);

    // product category spinner
    categories = newArrayList<ProductCategory>();

    category_adapter = newCustomArrayAdapter<ProductCategory>(categories);
    category_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // load category spinner from database
    loadCategory();     // adapter MUST be setup before this is called

    category_spinner.setAdapter(category_adapter);
    category_spinner.setOnItemSelectedListener(newOnItemSelectedListener () {


    ..... other stuff ...... 


privatefinalHandlerhandler=newHandler() {
    @OverridepublicvoidhandleMessage(final Message msg) {
        Log.v(TAG, "worker thread done, setup adapter");

        switch (msg.what) {
        case Constants.CATEGORIES:
            category_adapter.notifyDataSetChanged();
            break;
        case Constants.GROUPS:
            group_adapter.notifyDataSetChanged();
            break;
        case Constants.PRICES:
            startActivity(newIntent(Start.this, ShowPrices.class));
            break;
        default:
        }
        // dismiss dialog
        progressDialog.dismiss();
    }
};

    // loadCategory() essentially the same....privatevoidloadGroup(final String cat) {
    Log.v(TAG, "loadGroup");

    progressDialog = newProgressDialog(this);
    progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    progressDialog.setMessage("Retrieving Product Groups...");
    progressDialog.setMax(100);
    progressDialog.setProgress(0);
    progressDialog.show();

    newThread() {

        @Overridepublicvoidrun() {

            intcount=100;
            inti=0;

            SQLiteDatabasedb= DbUtils.getStaticDb();

            Cursorc= db.rawQuery("select count(*) from productgroup where category = \'"
                            + cat + "\';", null);
            c.moveToFirst();
            if (!c.isAfterLast()) {
                count = c.getInt(0);
            }
            c.close();

            progressDialog.setMax(count);

            groups.clear();
            groups.add(newProductGroup("-1", "--- Select ---"));

            StringBuildersb=newStringBuilder("select _id,description from productgroup");
            sb.append(" where category = \'");
            sb.append(cat);
            sb.append("\' order by description;");
            Log.v(TAG, sb.toString());

            c = db.rawQuery(sb.toString(), null);
            c.moveToFirst();
            while (!c.isAfterLast()) {
                Log.v(TAG, c.getString(0));
                groups.add(newProductGroup(c.getString(0), c.getString(1)));
                i++;
                if (i % 5 == 0) {
                    progressDialog.setProgress(i);
                }
                c.moveToNext();
            }
            c.close();

            // tell UI thread OK
            handler.sendEmptyMessage(Constants.GROUPS);
        }
    }.start();
}

    // custom ArrayAdapter allows us to have our own ArrayList<T>classCustomArrayAdapter<T> extendsArrayAdapter<T> {

    CustomArrayAdapter(ArrayList<T> list) {
        super(Start.this, android.R.layout.simple_spinner_item, list);
    }

}

Solution 2:

All the work after loadData() in onCreate() needs to be done after the work in run() in the thread triggered in loadData() has been completed. Try inlining loadData(), and adding this post-setup work to a runOnUiThread() after pd.dismiss().

Solution 3:

I would also suggest you to use https://github.com/commonsguy/cwac-task it has very nice AsyncTaskEx impl, which you can use to do heavy work without locking the ui.

Example class;

protectedclassDoHeavyWorkAsyncextendsAsyncTaskEx<Void, Integer, String> {
        privatestatic final StringTAG = "DoHeavyWorkAsync";

        @OverrideprotectedStringdoInBackground(Void... arg0) {

            // do heavy work here. e.g. loadDataFromSomewhere();YourActivity.this.runOnUiThread(newRunnable() {
                publicvoidrun() {
                    // you can do ui work on the main activity from here
                }
            });

            returnnull;
        }

        @OverrideprotectedvoidonPreExecute() {
            super.onPreExecute();

            Log.d(TAG, "onPreExecute()");
                    //e.g. display "loading..." 
        }
        @OverrideprotectedvoidonPostExecute(String result) {
            super.onPostExecute(result);
            Log.d(TAG, "onPostExecute()");
        }
    }

from your main activity you can call like this;

(new DoHeavyWorkAsync()).execute();

Post a Comment for "Android Progressdialog Progress Bar Doing Things In The Right Order"