Android Horizo​​ntal Progress栏无法获取JSON

时间:2015-11-28 14:38:06

标签: android json android-progressbar

我正在尝试设置进度条以通过显示百分比从服务器获取大量JSON但它不起作用。我不知道这个。所以请从头开始帮助我。

Test.java

   public class Test extends  AppCompatActivity {
    // Progress Dialog
    private ProgressDialog pDialog;
    private Toolbar mToolbar;
    public static final int progress_bar_type = 0;
    List<NameValuePair> params;
    // File url to download
    private static String file_url = "http://dcntv.in:3035/area_list";
    Connect cn = new Connect();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);
        params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("opid", "19"));
        new DownloadFileFromURL().execute(file_url);
    }

    /**
     * Background Async Task to download file
     * */
    class DownloadFileFromURL extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread
         * Show Progress Bar Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(progress_bar_type);
        }

        /**
         * Downloading file in background thread
         * */
        @Override
        protected String doInBackground(String...urls) {
                return cn.readJSONFeed(urls[0],params);
        }

        /**
         * Updating progress bar
         * */
        protected void onProgressUpdate(String... progress) {
            // setting progress percentage
            pDialog.setProgress(Integer.parseInt(progress[0]));
        }

        /**
         * After completing background task
         * Dismiss the progress dialog
         * **/
        @Override
        protected void onPostExecute(String result) {
            Dialog d = new Dialog(Test.this);
            TextView tv = new TextView(Test.this);
            tv.setText(result.toString());
            ScrollView sv = new ScrollView(Test.this);
            sv.addView(tv);
            d.setContentView(sv);
            d.show();
            // dismiss the dialog after the file was downloaded
            dismissDialog(progress_bar_type);
        }

    }

    /**
     * Showing Dialog
     * */
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case progress_bar_type: // we set this to 0
                pDialog = new ProgressDialog(this);
                pDialog.setMessage("Downloading file. Please wait...");
                pDialog.setIndeterminate(false);
                pDialog.setMax(100);
                pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                pDialog.setCancelable(true);
                pDialog.show();
                return pDialog;
            default:
                return null;
        }
    }


}

Connect.java (对于cn对象)

    public class Connect {

    public String readJSONFeed(String URL,List<NameValuePair> params) {

        StringBuilder stringBuilder = new StringBuilder();
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(URL);

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            HttpResponse response = httpClient.execute(httpPost);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream inputStream = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                inputStream.close();
            } else {

                Log.d("JSON", "Failed to download file");

            }
        } catch (Exception e) {

        }
        return stringBuilder.toString();
    }


}

1 个答案:

答案 0 :(得分:0)

  

进度条弹出窗口但进度计数无法正常工作

因为没有从publishProgress调用doInBackground方法在UI线程上发布进度更新。

使用当前代码发布更新进行以下更改:

1。readJSONFeed中添加一个参数以获取DownloadFileFromURL的对象:

    public String readJSONFeed(String URL,List<NameValuePair> params,
                                 DownloadFileFromURL objDownloadFileFromURL) {
     ... ...
     while ((line = reader.readLine()) != null) {
           stringBuilder.append(line);
           // add this line
           objDownloadFileFromURL.publishProgress(stringBuilder.length()); 
      }

  ....
}

2。DownloadFileFromURL.this致电readJSONFeed后通过doInBackground

return cn.readJSONFeed(urls[0],params,DownloadFileFromURL.this);