android - Android AsyncTask 进度百分比的问题

标签 android json android-asynctask percentage android-sqlite

我想不出一种方法来计算进度百分比。我正在使用 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/

相关文章:

android - 如何隐藏应用程序图标但在 Action Bar Android 中保留向上按钮

javascript - JSON HTML 文件链接

android - 从哪里调用 Google 登录 Activity 中的异步任务?

java - 如何在 AsyncTask 中运行 ProgressDialog

android - 如何查找 Android Google Play 服务版本

android - 禁用 HTC 噪音消除

ios - NSURLSession.sharedSession().dataTaskWithRequest 函数运行缓慢

java - 在 Java 中将 XML 与 JSON 相互转换(无需额外的 <e> 和 <o> 元素)

java - 需要序列化的 EnqueueWork 导致 AsyncTask 崩溃

android - 键盘与 facebook 登录屏幕重叠