progressDialoge未更新

时间:2019-03-18 09:28:58

标签: java android android-asynctask progressdialog

我一直在使用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 Earthquake}s
        //*List<FoodList> Food = extractFeatureFromJson(jsonResponse);
        Cursor foodTable = extractFeatureFromJson(jsonResponse);
        // Return the list of {@link Earthquake}s
        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);
    }
}

2 个答案:

答案 0 :(得分:0)

您必须发布进度,然后只有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”;
}

答案 1 :(得分:0)

根据android文档:

“ onProgressUpdate(Progress ...),在调用publishProgress(Progress ...)之后在UI线程上调用。执行的时间未定义。此方法用于在用户中显示任何形式的进度界面,而后台计算仍在执行。例如,它可用于为进度栏设置动画或在文本字段中显示日志。

使用它