经过很多尝试,终于让我的异步任务工作了,并根据进度更新了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
}
}
此代码的其余部分(除百分比部分外)有效。
答案 0 :(得分:1)
在您的代码中,我看不到recordcount
的声明位置以及为其分配了什么值。如果它是整数,那么由于整数除法,我想currentRecord / recordcount
将始终为0
。
更改:
publishProgress(count);
到
publishProgress(count, records.size());
因此您可以像这样计算正确的百分比:
int progress = (int)((1.0 * currentRecord / values[1]) * 100);
答案 1 :(得分:0)
我相信您未接打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
}