显示JSON上传进度 [英] show upload progress for JSON

查看:481
本文介绍了显示JSON上传进度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面这段code的,我会想这里这样的,我知道什么时候 JSON 内容被上传添加一个功能。 我上传 JSON 内容

I have the following piece of code and I would want to add a feature in here such that I know when the JSON content is uploaded. I am uploading a JSON content.

@Override
protected String doInBackground(JSONObject... params) {
    // TODO Auto-generated method stub
    String state = "";

    HttpPost httpPost = new HttpPost(commentURL);
    StringEntity se = null;
    HttpResponse response = null;
    HttpEntity entity = null;
    DefaultHttpClient httpClient = new DefaultHttpClient();
    InputStream is = null;

    try {
        se = new StringEntity(params[0].toString());
        Log.i("SE", params[0].toString());
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    try {
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                "application/json"));
        httpPost.setEntity(se);

        try {
            response = httpClient.execute(httpPost);
            Log.i("HTTP POST", httpPost.toString());
            Log.i("RESPONSE", response.toString());
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    entity = response.getEntity();

    try {
        is = entity.getContent();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        state = sb.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return state;
}

我试着研究自己,这是我偶然发现了 MultipartEntity ,但由于我上传一个简单的 JSON 文章内容我认为这没有必要使用。那么,如何展示了多大的进步在上传过程制成,也什么是JSON内容的总大小?我有点想通,我将不得不使用 StringEntity ?我说得对不对?

I tried researching myself, which is where I stumbled upon the MultipartEntity, but since I am to upload a simple JSON content through POST I didn't find this necessary to use. So how do I show how much progress is made in the upload process and also what is the total size of the JSON content ?? I sort of figured that I would have had to use the StringEntity ? Am I right ?

推荐答案

启动你的进度条

private ProgressDialog pDialog;

在上preExecute()

On onPreExecute()

@Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();

            pDialog = new ProgressDialog(getParent());
            pDialog.setMessage("Please wait ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

在onPostExecute()

On onPostExecute()

protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
pDialog.dismiss();
}

有关显示与百分比试进度条。

For showing progress bar with percentage try ..

  public class AndroidDownloadFileByProgressBarActivity extends Activity {

    // button to show progress dialog
    Button btnShowProgress;

    // Progress Dialog
    private ProgressDialog pDialog;
    ImageView my_image;
    // Progress dialog type (0 - for Horizontal progress bar)
    public static final int progress_bar_type = 0; 

    // File url to download
    private static String file_url = "your_url";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // show progress bar button
        btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
        // Image view to show image after downloading
        my_image = (ImageView) findViewById(R.id.my_image);
        /**
         * Show Progress bar click event
         * */
        btnShowProgress.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // starting new Async Task
                new DownloadFileFromURL().execute(file_url);
            }
        });
    }

    /**
     * Showing Dialog
     * */
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case progress_bar_type:
            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;
        }
    }

    /**
     * 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... f_url) {
            int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection conection = url.openConnection();
                conection.connect();
                // getting file length
                int lenghtOfFile = conection.getContentLength();

                // input stream to read file - with 8k buffer
                InputStream input = new BufferedInputStream(url.openStream(), 8192);

                // Output stream to write file
                OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress(""+(int)((total*100)/lenghtOfFile));

                    // writing data to file
                    output.write(data, 0, count);
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

            return null;
        }

        /**
         * 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 file_url) {
            // dismiss the dialog after the file was downloaded
            dismissDialog(progress_bar_type);

            // Displaying downloaded image into image view
            // Reading image path from sdcard
            String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
            // setting downloaded into image view
            my_image.setImageDrawable(Drawable.createFromPath(imagePath));
        }

    }
}

这篇关于显示JSON上传进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆