进度对话框未更新
Posted
技术标签:
【中文标题】进度对话框未更新【英文标题】:progressDialoge not Updating 【发布时间】:2019-08-08 15:12:01 【问题描述】:我一直在使用 AsyncTask 下载某个文件并浏览了一些教程,但未能让进度条随着下载移动。代码是 AsyncTask,它调用一个方法来进行 HTTP 连接,然后返回以适当的方式对数据进行分类,以便为应用程序操作它
这是我在 MainActivity 上的 AsynTask
private class getFood extends AsyncTask<Void, Integer, Cursor>
private ProgressDialog mProgressDialog;
@Override
protected Cursor doInBackground(Void... params)
// Create URL object
String site = "https://afternoon-ridge-50060.herokuapp.com/allsnacks";
URL url = createUrl(site);
// Perform HTTP request to the URL and receive a JSON response back
String jsonResponse = null;
try
String jsonResponseEmpty = "";
// If the URL is null, then return early.
if (url == null)
jsonResponse = jsonResponseEmpty;
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try
assert url != null;
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(20000 /* milliseconds */);
urlConnection.setConnectTimeout(25000 /* milliseconds */);
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Authorization", "\"token\": " + token);
urlConnection.connect();
// If the request was successful (response code 200),
// then read the input stream and parse the response.
if (urlConnection.getResponseCode() == 200)
int fileLength = urlConnection.getContentLength();
Log.d("size", String.valueOf(fileLength));
inputStream = urlConnection.getInputStream();
StringBuilder output = new StringBuilder();
if (inputStream != null)
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
jsonResponse = output.toString();
else
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
catch (IOException e)
Log.e(LOG_TAG, "Problem retrieving the Food JSON results.", e);
finally
if (urlConnection != null)
urlConnection.disconnect();
if (inputStream != null)
// Closing the input stream could throw an IOException, which is why
// the makeHttpRequest(URL url) method signature specifies than an IOException
// could be thrown.
inputStream.close();
catch (IOException e)
Log.e(LOG_TAG, "Problem making the HTTP request.", e);
// Extract relevant fields from the JSON response and create a list of @link Earthquakes
//*List<FoodList> Food = extractFeatureFromJson(jsonResponse);
Cursor foodTable = extractFeatureFromJson(jsonResponse);
// Return the list of @link Earthquakes
Log.d("food", "done");
return foodTable;
@Override
protected void onProgressUpdate(Integer... values)
// if we get here, length is known, now set indeterminate to false
mProgressDialog.setProgress(values[0]);
@Override
protected void onPreExecute()
super.onPreExecute();
// Create progress dialog
mProgressDialog = new ProgressDialog(loginActivity.this);
// Set your progress dialog Title
mProgressDialog.setTitle("Downloading");
// Set your progress dialog Message
mProgressDialog.setMessage("Downloading Important Files, Please Wait!");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// Show progress dialog
mProgressDialog.show();
@Override
protected void onPostExecute(Cursor data)
try
int foodNumberColIndex = data.getColumnIndex(COLUMN_NDB_NO);
int foodNameColIndex = data.getColumnIndex(COLUMN_NAME);
int waterColIndex = data.getColumnIndex(COLUMN_WATER_G);
int energyColIndex = data.getColumnIndex(COLUMN_ENERGY_KCAL);
int proteinColIndex = data.getColumnIndex(COLUMN_PROTEIN_G);
int lipidColIndex = data.getColumnIndex(COLUMN_LIPID_TOT_G);
int ashColIndex = data.getColumnIndex(COLUMN_ASH_G);
int carboColIndex = data.getColumnIndex(COLUMN_CARBOHYDRT_G);
while (data.moveToNext())
Log.d("in", " progress");
FoodList foodItem = new FoodList(data.getInt(foodNumberColIndex),
data.getString(foodNameColIndex).trim().replace(",", "."),
data.getDouble(waterColIndex),
data.getDouble(energyColIndex),
data.getDouble(proteinColIndex),
data.getDouble(lipidColIndex),
data.getDouble(ashColIndex),
data.getDouble(carboColIndex));
allFood.add(foodItem);
finally
data.close();
mProgressDialog.dismiss();
startActivity(intentNew);
private URL createUrl(String stringUrl)
URL url = null;
try
url = new URL(stringUrl);
catch (MalformedURLException e)
Log.e(LOG_TAG, "Problem building the URL ", e);
return url;
private Cursor extractFeatureFromJson(String foodJSON)
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(foodJSON))
return null;
try
// Create a JSONArray from the JSON response string
JSONArray foodArray = new JSONArray(foodJSON);
for (int i = 0; i < foodArray.length(); i++)
JSONObject foodObject = foodArray.getJSONObject(i);
ContentValues values = new ContentValues();
values.put(COLUMN_NDB_NO, foodObject.optInt(COLUMN_NDB_NO));
values.put(COLUMN_NAME, foodObject.optString(COLUMN_NAME));
values.put(COLUMN_WATER_G, foodObject.optDouble(COLUMN_WATER_G));
values.put(COLUMN_ENERGY_KCAL, foodObject.optDouble(COLUMN_ENERGY_KCAL));
values.put(COLUMN_PROTEIN_G, foodObject.optDouble(COLUMN_PROTEIN_G));
values.put(COLUMN_LIPID_TOT_G, foodObject.optDouble(COLUMN_LIPID_TOT_G));
values.put(COLUMN_ASH_G, foodObject.optDouble(COLUMN_ASH_G));
values.put(COLUMN_CARBOHYDRT_G, foodObject.optDouble(COLUMN_CARBOHYDRT_G));
foodNutriProvider insert = new foodNutriProvider();
insert.insert(CONTENT_URI, values);
catch (JSONException e)
// If an error is thrown when executing any of the above statements in the "try" block,
// catch the exception here, so the app doesn't crash. Print a log message
// with the message from the exception.
Log.e("foodSearch", "Problem parsing the earthquake JSON results", e);
Log.e("foodSearch", foodJSON);
foodNutriProvider getTable = new foodNutriProvider();
// Return the list of earthquakes
return getTable.query(CONTENT_URI, null, null, null, null);
【问题讨论】:
请评论或删除super.onProgressUpdate(values);
,然后检查
@SanjuRajpal 没有修复它
【参考方案1】:
您必须发布进度,然后只有 Integer... values
具有正确的值。
类似:
@Override
protected String doInBackground(Context... params)
//Part-1 of the task done
publishProgress(20);
//Part-2 of the task done
publishProgress(50);
//Part-3 of the task done
publishProgress(100);
return “success”;
【讨论】:
以及这些整数如何代表下载的实际数据【参考方案2】:根据安卓文档:
"onProgressUpdate(Progress...),在调用publishProgress(Progress...)之后在UI线程上调用。执行的时间是未定义的。该方法用于在用户中显示任何形式的进度后台计算仍在执行时的界面。例如,它可用于动画进度条或在文本字段中显示日志"
使用它
【讨论】:
以上是关于进度对话框未更新的主要内容,如果未能解决你的问题,请参考以下文章
Android - 仅在 AsyncTask 未完成时单击按钮时显示进度对话框
Android 中ProgressDialog进度条对话框的使用(使用子线程模拟更新进度)
Activity 为 launchMode="SingleTask" 时,进度对话框未显示 2 次