winkbrace
winkbrace

Reputation: 2711

Android - creating progress dialog filled by thread

Let me start by explaining this is my first Android app. So I don't have a full grasp of all concepts yet. I expect this problem to relate to that lack of knowledge, but I can't seem to google the solution to this issue this time.

I have this snippet of code to fetch some data from a remote Mysql database to fill a ListView with. This works just fine.

// fetch family and determine length of the arrays
Familielid[] familie = Mysql.getFamilie();
int len = familie.length;
namen = new String[len]; // groups
lijsten = new String[len][];  // children

// loop through the family and fill names and lists
for (int i=0; i<len; i++)
{
    namen[i] = familie[i].getNaam();
    Lijst lijst = new Lijst(Mysql.getLijst(familie[i].getId()));
    lijsten[i] = lijst.getOmschrijvingen();
}

Now because this can take some time, I want to show a progress bar that gets filled for each "Familielid" (= family member) that has been loaded. (I want to do it this way mainly to find out how to do it) This code however, is throwing an application error. :(

// show progress bar while loading 
ProgressDialog progressDialog = new ProgressDialog(VerlanglijstenActivity.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Lijstjes ophalen...");
progressDialog.setCancelable(false);
progressDialog.show();

// load lijstjes with progress bar
Thread loadLijstjes = new Thread(new Runnable() {
    public void run() {
        // fetch family and determine length of the arrays
        Familielid[] familie = Mysql.getFamilie(); 
        int len = familie.length;
        namen = new String[len]; // groups
        lijsten = new String[len][];  // children

        // loop through the family and fill names and lists
        for (int i=0; i<len; i++)
        {
            namen[i] = familie[i].getNaam();
            Lijst lijst = new Lijst(Mysql.getLijst(familie[i].getId()));
            lijsten[i] = lijst.getOmschrijvingen();
            // show progress
            progressDialog.incrementProgressBy((int) Math.floor(100/len));
        }
        progressDialog.setProgress(100); // just make sure it's 100% when we're done
        progressDialog.dismiss() ; // close the progress bar
    }
});
loadLijstjes.start();

Any idea what I'm doing wrong? Or should it be done entirely differently?

Upvotes: 0

Views: 447

Answers (1)

kabuko
kabuko

Reputation: 36302

Here's a doc for an excellent start to some approaches to dealing with threading in Android. The source of your problem is that you are trying to update your UI from a non-UI thread. You can fix this most easily by handling your background work in an AsyncTask as described in the doc, and putting the progress updates in the onProgressUpdate method.

Upvotes: 1

Related Questions