0

The background or thread operation of downloading and inserting JSON data into database works fine but as I also want to update my ProgressBar when the data insertion operation keeps updating. My problem is, it starts with Zero percent and dismisses when the whole operation is completed without any update in percentage value.

Downloading view seems like this

Sync Fragment:

String value; //defined globally

private class JsonParse extends AsyncTask<String, String, String> {

    Context mcontext;
    private ProgressDialog progressDialog;

    public JsonParse(Context context) {
        this.mcontext = context;
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        progressDialog = new ProgressDialog(mcontext);

        progressDialog.setTitle("Downloading"); // Setting Title
        progressDialog.setMessage("Please wait"); // Setting Message
        progressDialog.setIndeterminate(false);
        progressDialog.setMax(100);
        progressDialog.setCancelable(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, mcontext.getString(R.string.cancel_btn), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        progressDialog.show();
    }

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

        String choice = params[0];
        final String url = BASE_URL + "" + VERSION + "" + METHOD + "";

        StringRequest request = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        Log.i("response", url + "response:" + response);

                        try {
                            JSONObject object = new JSONObject(response);
                            JSONArray jsonArray = object.getJSONArray(METHOD + "");

                            long counter = 0;
                            int size = jsonArray.length();

                            for (int i = 0; i <= size; i++) {

                                final JSONObject jsonObject = jsonArray.getJSONObject(i);

                                counter++;
                                int percent = (int) ((counter * 100) / size);
                                value = percent + "";

                                onProgressUpdate(value);

                                Log.i("view_", "size: " + size + " " + "counter: " + counter + " " + "percent: " + percent + "%");

                                switch (choice) {

                                    case "deaths":

                                        String id_d = jsonObject.getString("id");
                                        String family_id = jsonObject.getString("family_id");
                                        String death_one_year = jsonObject.getString("death_one_year");
                                        String no_of_deaths = jsonObject.getString("no_of_death");
                                        String cause = jsonObject.getString("cause");
                                        String cause_other = jsonObject.getString("cause_other");
                                        String ward_id_d = jsonObject.getString("ward_id");
                                        String has_error_d = jsonObject.getString("has_error");
                                        String updated_by_d = jsonObject.getString("updated_by");
                                        String updated_at_d = jsonObject.getString("updated_at");
                                        String created_at = jsonObject.getString("created_at");
                                        String uuid_d = jsonObject.getString("uuid");

                                        dbHelper.SyncDeath(Integer.parseInt(id_d), family_id, death_one_year, no_of_deaths, cause, cause_other,
                                                ward_id_d, has_error_d, updated_by_d, updated_at_d, created_at, uuid_d);

                                        death_txt.setTextColor(getResources().getColor(R.color.colorPrimary));
                                        death_txt.setText(R.string.synced);

                                        break;
                                }
                            }
                            return;

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        progressDialog.dismiss();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                Toast.makeText(getContext(), "Server Error, Please Try Again!!", Toast.LENGTH_SHORT).show();
            }
        });

        requestQueue.add(request);

        publishProgress(value);

        Log.i("view_percent_value", value); // Getting null value

        /*for (int i = 0; i <= 100; i++){
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            publishProgress(String.valueOf(i));
        }*/

        return null;
    }

    @Override
    protected void onProgressUpdate(String... values) {

        progressDialog.setProgress(Integer.parseInt(values[0]));
        value = values[0]; // Tried to update this "value" i.e. set globally but can't update

        Log.i("view_values", values[0] + "");
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {

    }
}

The above-commented code:

 /*for (int i = 0; i <= 100; i++){
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            publishProgress(String.valueOf(i));
        }*/

helps me update ProgressBar but it is not updating in Realtime. In my case, the parameter passed in publishprogress(); i.e. "value" which is defined globally is not getting updated value from the loop. As I guess, it may be the case using for-loop inside try-catch but I can't find the way how to pass that value to publishprogress(); method.

The Log view:

Log.i("view_", "size: " + size + " " + "counter: " + counter + " " + "percent: " + percent + "%");

is updating the percentage value in real-time. Like this: Log view of updating percentage value

Please help me to figure out this problem. I'm stuck with this problem from couple of weeks. Thank you in advance!!

Ayush Katuwal
  • 139
  • 1
  • 2
  • 11

2 Answers2

1

First, according to android documents never call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually. (you are calling onProgressUpdate in doInBackground manually)

Second, move publishProgress(value); to for loop inside try block.

Alireza Pir
  • 878
  • 1
  • 16
  • 41
  • Thank you, #Alireza.pir for your response. I tried already both of your suggestions, removing method call " onProgressUpdate(); " manually inside doInBackground and also moving publishProgress(value); inside the loop, both conditions failed in my case. – Ayush Katuwal May 29 '19 at 06:02
  • Suggest me, if there are any other alternate solutions. – Ayush Katuwal May 29 '19 at 06:03
  • @AyushKatuwal what do you mean by failed? you have error or null pointer? – Alireza Pir May 29 '19 at 06:05
  • @AyushKatuwal and also remove that super.onProgressUpdate(...) line. – Alireza Pir May 29 '19 at 06:06
  • @AyushKatuwal and also there is no need to define ``value`` globally. remove that too. so just call ``publishProgress(percent+"")``; – Alireza Pir May 29 '19 at 06:10
  • Sorry, I mean to say that it's not working. The log value gets updated like the screenshot I've posted but the progressbar is not updating – Ayush Katuwal May 29 '19 at 06:12
  • @AyushKatuwal I'm waiting here to see if it works :) – Alireza Pir May 29 '19 at 06:14
  • No man, still the same... I don't know why the publishProgress method is not working in my case...Is there something I need to be alert with? – Ayush Katuwal May 29 '19 at 06:17
  • put a Log in ```publishProgress```, and see if its called, let me know after doing this. – Alireza Pir May 29 '19 at 06:18
  • I've done all the things as you mentioned, removed globally declared String value, removed super.onProgressUpdate from onProgressUpdate(String ....) method. But the publishProgress() works outside the loop where I've commented in my question. Is try-catch affecting publishProgress(); method? Because once I tried sending random value like publishProgress(20+"") inside for-loop it doesn't even update bar into 20% but works fine as I do so outside the for-loop or the commented part of my question. Hope my this comment helps to figure out the actual problem. – Ayush Katuwal May 29 '19 at 06:27
  • Yes, the log gets updated inside that for-loop but no any updates for progressbar. – Ayush Katuwal May 29 '19 at 06:29
  • @AyushKatuwal also move ```progressDialog.dismiss();``` to ```onPostExecute()``` – Alireza Pir May 29 '19 at 06:37
  • No man, If I moved progressDialog.dismiss(); to PostExecute() then the dialogbox will dismiss after the data gets download but in my case I've to show the bar till the data gets insert into database. – Ayush Katuwal May 29 '19 at 06:43
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/194116/discussion-between-alireza-pir-and-ayush-katuwal). – Alireza Pir May 29 '19 at 12:29
0

Trying setting value of your progress in onProgressUpdate() function.

Follow this link for reference: android how to work with asynctasks progressdialog

Sujin Shrestha
  • 1,203
  • 2
  • 13
  • 23
  • Thank you #SujinShrestha for quick response, I'll try to figure out my problem from this similar case. Hope I'll find out some solutions from here. – Ayush Katuwal May 29 '19 at 05:50