我想不出一种计算进度百分比的方法。我正在使用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中的示例。请指导我。 编辑:如果涉及多个插入? 感谢
答案 0 :(得分: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 documentation
上找到示例答案 1 :(得分:0)
进度报告有点主观,并且根据您的任务的不同而变化很大,但对于您的情况,您可以使用for
进行计算。
private int progress;
private int max;
max = total.length()
for(int i = 0; i < total.length(); i++){
progress = i;
publishProgress(progress);
}