java - 从android中的json get方法下载数据时设置进度条百分比

标签 java android json android-asynctask android-progressbar

我想显示进度条以及从 json 下载数据的百分比。现在,我正在从 url 获取数据,并将其存储在其他类的本地数据库中,该类在 MainActivity 中调用。现在我想显示 progressbar 以及从 json url 下载文件的百分比。

这是我的代码

public class Web_Product {

Context context;
List<Variable> list = new ArrayList<Variable>();
//List<Variable> list1;
String url = "https://api.androidhive.info/progressdialog/hive.jpg";
URL url1 = null;
InputStream is1 = null;
String product_id, product_name, product_image;
private byte[] logoImage;
private JSONArray jsonArray;

public Web_Product(Context context) {
    this.context = context;
    Log.e("hello", "Message");

}

public void product_insert() {
    // new AsyncLogin().execute();
    ServiceHandler sh = new ServiceHandler();

    // Making a request to url and getting response
    String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

    Log.e("TEST", "jsonStr:-" + jsonStr);

    if (jsonStr != null) {
        try {

            JSONObject jsonRootObject = new JSONObject(jsonStr);

            //Get the instance of JSONArray that contains JSONObjects
            JSONArray jsonArray = jsonRootObject.optJSONArray("product");

            //Iterate the jsonArray and print the info of JSONObjects
            for (int i = 0; i < jsonArray.length(); i++) {
                Log.e("TEST_P", "in");
                JSONObject details = jsonArray.getJSONObject(i);

                product_id = details.getString("product_id");
                product_name = details.getString("product_name");
                product_image = details.getString("product_image");

                logoImage = getLogoImage(product_image);

                Variable variable_object = new Variable();
                variable_object.setProduct_id(product_id);
                variable_object.setProduct_name(product_name);
                variable_object.setProduct_url_image(logoImage);

                list.add(variable_object);

            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

    } else {
        Log.e("ServiceHandler", "Couldn't get any data from the url");
    }
    Log.e("TEST1", " Ritunjay" + list.size());
    Product_data product = new Product_data(context);
    product.Insert_Product(list);
    Log.e("listpo", "" + list);

}

public JSONArray json_web_prod() {
    ServiceHandler sh = new ServiceHandler();

    // Making a request to url and getting response
    String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

    Log.e("TEST", "jsonStr:-" + jsonStr);

    if (jsonStr != null) {
        try {

            JSONObject jsonRootObject = new JSONObject(jsonStr);

            //Get the instance of JSONArray that contains JSONObjects
            jsonArray = jsonRootObject.optJSONArray("product");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return jsonArray;
}`

主要 Activity

   class add extends AsyncTask<String, Integer, String> {

    ProgressDialog mProgressDialog;

    @Override
    protected void onProgressUpdate(Integer... values) {
        mProgressDialog.setProgress(values[0]);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgressDialog = new ProgressDialog(MainActivity.this);
        mProgressDialog.setTitle("Downloading Data...");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();
    }

    @Override
    protected void onPostExecute(String aVoid) {
        super.onPostExecute(aVoid);
        mProgressDialog.dismiss();
        flag = true;
        Intent intent = getIntent();
        startActivity(intent);
        finish();

        Log.e("flag , post", "" + flag);

    }

    @Override
    protected String doInBackground(String... params) {

        web_product = new Web_Product(getApplicationContext());
        web_product.product_insert();

        return null;

    }


}`

最佳答案

在doInBackground中,您还需要publishProgress。这样你的进度条就可以更新,就像这样

 protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

这里totalSize将帮助您计算剩余总数据量,publishProgress将公开它。

关于java - 从android中的json get方法下载数据时设置进度条百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46599223/

相关文章:

android - 无法连接到 Android 中的节点 js 服务器

ios - 使用 JSONModel 库将 jsonarray(具有不同类型)转换为模型数组

Java Singleton.getInstance() 返回空值?

java - 检查一个值是否为 0 比直接覆盖它更快吗?

java - 请求方法 'DELETE'不支持-reactjs + spring Boot

javascript - React Native如何消费Image.prefetch的结果?

java - 递归图遍历

java - 在android上下载多个非http下载的最佳方式是什么

javascript - 如何让 JSON blob 中的 HTML 正确呈现?

json - 使用newtonsoft,如何在不知道类型的情况下反序列化直到运行时?