在尝试了这么多之后,我让我的异步任务工作并更新ui的进度。这里的主要目标是从api调用添加一些数据到我的数据库。我的百分比计算有问题,因为在我的进度条中我将max设置为100,所以我需要让百分比正常工作。
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
}
}
除了它的百分比部分之外,其余代码都有效。
在你的代码中,我没有看到声明recordcount
的位置以及分配给它的值。如果它是一个整数,那么我认为currentRecord / recordcount
将永远是0
,因为整数除法。
更改:
publishProgress(count);
至
publishProgress(count, records.size());
所以你可以像这样计算正确的百分比:
int progress = (int)((1.0 * currentRecord / values[1]) * 100);
我相信你错过了对super.onProgressUpdate(values);
的调用它看起来应该是这样的
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(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
}