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
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad