Ad

Some Calculations Like Percentage In My Async Task Not Working

After trying so much finally I have my async task working and updating ui on the progress. The main objective here is to add some data from an api call to my database. I am having a problem with my percentage calculation working because in my progress bar I have set max to 100 and so I need to get the percentage working correctly.

class AddtoDBTask extends AsyncTask<List<RecordModel>, Integer, String> {
        @Override
        protected String doInBackground(List<RecordModel>... lists) {
            List<RecordModel> records = lists[0];
            for (int count = 0; count < records.size(); count ++) {
                publishProgress(count);
                RecordModel record = new RecordModel();
                record.recordid = records.get(count).recordid;
                record.name = records.get(count).name;
                record.idnumber = records.get(count).idnumber;
                record.gender = records.get(count).gender;
                record.dobirth= records.get(count).dobirth;
                SQLiteHelper.addRecord(record);
                Log.d("Log: ", record.title + " added");
            }
            return "Task Completed.";
        }
        @Override
        protected void onPostExecute(String result) {
            syncProgress.setVisibility(View.GONE);
            statusText.setText(String.format("Thanks for your patience, We are done syncing!"));
        }
        @Override
        protected void onPreExecute() {
            statusText.setText(String.format("Task 2 of 2 in progress..."));
        }
        @Override
        protected void onProgressUpdate(Integer... values) {
            int currentRecord = (values[0] + 1);
            int progress = (currentRecord / recordcount) * 100;
            syncPercentage.setText(progress + " %"); //not working
            syncSize.setText(String.format("Record " + currentRecord + " of " + recordcount));
            syncProgress.setProgress(progress); //not working
        }
    }

The rest of this code works except for the percentage part of it.

Ad

Answer

In your code I don't see where recordcount is declared and what value has been assigned to it. If it is an integer then I suppose currentRecord / recordcount will always be 0 because of integer division.
Change:

publishProgress(count);

to

publishProgress(count, records.size());

so you can calculate the correct percentage like this:

int progress = (int)((1.0 * currentRecord / values[1]) * 100);
Ad
source: stackoverflow.com
Ad