1

我想不出一种计算进度百分比的方法。我正在使用 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 的示例。请指导我。编辑:如果涉及多个插入?谢谢

4

2 回答 2

3

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 文档的示例

于 2012-11-09T09:43:18.790 回答
0

进度报告有点主观,并且根据您的任务正在做什么变化很大,但对于您的情况,您可以使用for来计算。

private int progress;
private int max;

max = total.length()
for(int i = 0; i < total.length(); i++){
   progress = i;
   publishProgress(progress);
}
于 2012-11-09T09:35:53.490 回答