我想不出一种方法来计算进度百分比。我正在使用 JSON 检索数据,然后所有数据都将插入到 sqlite 中。我想在运行 asynctask 时计算所有进程并显示百分比。
@Override
protected Void doInBackground(Void... params) {
//int progress = 0; //progress testing
//while(progress < 100) {
//progress += 10;
//SystemClock.sleep(1000);
//publishProgress(progress);
//}
getAllChannels(); //function get json data and insert db.
return null;
}
...
public void getAllChannels(){
try {
headline = jsheadline.getJSONArray(TAG_NEWLIST);
headline2 = jsheadline2.getJSONArray(TAG_NEWLIST2);
headline3 = jsheadline3.getJSONArray(TAG_NEWLIST3);
insertDatabase(headline,TABLE_HEADLINE);
insertDatabase(headline2,TABLE_HEADLINE2);
insertDatabase(headline3,TABLE_HEADLINE3);
}catch (Exception e) {
}
}
public void insertDatabase(JSONArray total, String tablename) throws JSONException{
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
for(int i = 0; i < total.length(); i++){
JSONObject c = total.getJSONObject(i);
// Storing each json item in tablecolumn
String subject = c.getString(KEY_NEWS_SUBJECT);
db.addNews(tablename, subject);
}
这是我如何将数据存储到 sqlite 中的示例。请带我出去。 编辑:如果涉及多次插入? 谢谢
最佳答案
onProgressUpdate
支持多个参数:
protected void onProgressUpdate(Integer... progress) {
int current = progress[0];
int total = progress[1];
float percentage = 100 * (float)current / (float)total;
// Display your progress here
}
你可以有这样的处理方法:
protected Void doInBackground(Void... params) {
JSONArray headlines = jsheadline.getJSONArray(TAG_NEWLIST);
int count = headlines.length();
for (int i=0; i<count; ++i) {
// Insert a single item in the DB
JSONObject headlineItem = headlines.getJSONObject(i);
insertDatabase(headlineItem);
// We have processed item 'i' out of 'count'
publishProgress(i, count);
// Escape early if cancel() is called
if (isCancelled()) break;
}
return null;
}
您在 SDK documentation 上也有一个示例
关于android - Android AsyncTask 进度百分比的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13305280/