Storing 1000+ data on SQLite resulting UI Hang

Issue

I need to insert big data on our SQLiteDatabase from our server’s response. But until now I’m still confuse on AsyncTask() and I want some clarifications on it. Here is my complete code on using AsyncTask(). I use AndroidNetworking library for an HTTP Request

class ProgressAsync extends AsyncTask<String, String, Boolean> {

    boolean result  false;
    ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                loadingDialog  new LoadingDialog();
                //dialogLoading.setTargetFragment(this, 1);
                FragmentManager fragmentManager  getSupportFragmentManager();
                loadingDialog.show(fragmentManager, "Dialog_Loading");
            }
        });

        super.onPreExecute();
    }

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

        try 
            JSONObject JSONparams  new JSONObject();
            try {
                JSONparams.put("a", "1");
                JSONparams.put("b", "1");
                JSONparams.put("c", "1");
                JSONparams.put("d", "1");

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


            OkHttpClient okHttpClient  new OkHttpClient().newBuilder().connectTimeout(15, TimeUnit.SECONDS).readTimeout(15, TimeUnit.SECONDS).writeTimeout(15, TimeUnit.SECONDS).build();

            AndroidNetworking.initialize(getApplicationContext(), okHttpClient);

            AndroidNetworking.get(url)
                    .setPriority(Priority.HIGH).build()
                    .getAsJSONArray(new JSONArrayRequestListener() {
                        @Override
                        public void onResponse(JSONArray response) {
                            Log.e("Response", String.valueOf(response));

                            try {

                                for (int i  0; i < response.length(); i++) {
                                    JSONObject objUsers  response.getJSONObject(i);

                                    final String user_id  objUsers.getString("id");
                                    final String issued_company_id  objUsers.getString("subcompany_id");
                                    final String position  objUsers.getString("route_id");
                                    final String card_id  objUsers.getString("route_name");


                                            KMpost kmpost  new KMpost();
                                            kmpost.setId(user_id);
                                            kmpost.setSubcompany_id(issued_company_id);
                                            kmpost.setRoute_id(position);
                                            kmpost.setRoute_name(card_id);

                                            MainActivity.appDatabase.dao2().insertAllkm(kmpost);

                                }

                                if (MainActivity.appDatabase.isOpen()){
                                    MainActivity.appDatabase.close();
                                }

                                result  true;

                                Log.e("Status", String.valueOf(a));


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

                        }

                        @Override
                        public void onError(ANError anError) {
                            Log.e("anError", String.valueOf(anError.getErrorCode()));
                            a  false;
                        }
                    });

        } catch (Throwable throwable) {
            throwable.printStackTrace();

        }

        return false;
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);

        Log.e("Logsssssssssss", "LOgssssssssss");

        Thread thread  new Thread() {
            @Override
            public void run() {
             try {
                 while (!result) {
                  //Thread.sleep(1000);
                  }
                 loadingDialog.dismiss();

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

        thread.start();
    }
}

Question 1: Is why does the log on onPostExecute() shows first even the doInBackground() is not yet finish? And how can I fix this?

Question 2: Does while() loop really helps? Or it is just a band-aid solution?.

Question 3: How can I avoid lag/hang in loading animation of ProgressDialog?

[by Taboola](https://popup.taboola.com/en/?templatecolorbox&utmsourceangularfix&utmmediumreferral&utmcontentthumbnails-mid:Mid Article Thumbnails:)[by Taboola](https://popup.taboola.com/en/?templatecolorbox&utmsourceangularfix&utmmediumreferral&utmcontentthumbnails-mid:Mid Article Thumbnails:)

[Sponsored Links](https://popup.taboola.com/en/?templatecolorbox&utmsourceangularfix&utmmediumreferral&utmcontentthumbnails-mid:Mid Article Thumbnails:)[Sponsored Links](https://popup.taboola.com/en/?templatecolorbox&utmsourceangularfix&utmmediumreferral&utmcontentthumbnails-mid:Mid Article Thumbnails:)

[Promoted Links](https://popup.taboola.com/en/?templatecolorbox&utmsourceangularfix&utmmediumreferral&utmcontentthumbnails-mid:Mid Article Thumbnails:)[Promoted Links](https://popup.taboola.com/en/?templatecolorbox&utmsourceangularfix&utmmediumreferral&utmcontentthumbnails-mid:Mid Article Thumbnails:)

You May Like

[

CNA Insight

](https://www.channelnewsasia.com/watch/insight-20222023/natuna-dispute-2626381?cidtaboolainsight-fy2223-idpaid17052022cnamkt-vodangularfix&tblciGiCyu-3eetpfqXFavMqYA8AXMjOsh5NCt0UvXq7Kt4cjkSDesFQo5bi8sq7KudU#tblciGiCyu-3eetpfqXFavMqYA8AXMjOsh5NCt0UvXq7Kt4cjkSDesFQo5bi8sq7K_udU “The Natuna Dispute: Can Indonesia Afford To Go Up Against China In South China Sea?”)The Natuna Dispute: Can Indonesia Afford To Go Up Against China In South China Sea?CNA Insight

[

CNA

](https://www.channelnewsasia.com/singapore/tradenation-luxury-goods-scam-timeline-couple-pi-jiapeng-siriwipa-pansuk-police-interpol-2841536?cidtaboolaidpaid25042022cnamkt-newsangularfix&tblciGiCyu-3eetpfqXFavMqYA8AXMjOsh5NCt0UvXq7Kt4cjkSDsklIoiI2E198ft#tblciGiCyu-3eetpfqXFavMqYA8AXMjOsh5NCt0UvXq7Kt4cjkSDsklIoiI2E198ft_ “Timeline: How a couple fled Singapore after millions were lost in Tradenation luxury goods scam”)Timeline: How a couple fled Singapore after millions were lost in Tradenation luxury goods scamCNA

[

Tip Parents

](https://rfvtgb.tiparents.com/worldwide/athlte-ta?utmmediumtaboola&utmsourcetaboola&utmcampaignta-tp-athlte-nc1-mac-0w-mm-25082d&utmtermangularfix&utmbidmt4SQ5NOik2ZVTx83QIwZBfNNq0xSLgGedkoDpmusY&utmkGiCyu-3eetpfqXFavMqYA8AXMjOsh5NCt0UvXq7Kt4cjkSDYuFko0YePlajH3-XIAQ&tblciGiCyu-3eetpfqXFavMqYA8AXMjOsh5NCt0UvXq7Kt4cjkSDYuFko0YePlajH3-XIAQ#tblciGiCyu-3eetpfqXFavMqYA8AXMjOsh5NCt0UvXq7Kt4cjkSDYuFko0YePlajH3-XIAQ “Pole Vaulter Crossed The Line In Front Of Fans”)Pole Vaulter Crossed The Line In Front Of FansTip Parents

Solution

I Solve it.I think that the insertion of data in SQLiteDatabase is the cause for making the UI lag. And since the AndroidNetworking uses a seperate Thread and making onPostExecute() runs first without waiting for the runInBackground(), So I came up a solution separating the insertion of data on a new Thread(). and it works :).

Full code:

class ProgressAsync extends AsyncTask<String, String, Boolean> {

    boolean result  false;
    ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                loadingDialog  new LoadingDialog();
                //dialogLoading.setTargetFragment(this, 1);
                FragmentManager fragmentManager  getSupportFragmentManager();
                loadingDialog.show(fragmentManager, "Dialog_Loading");
            }
        });

        super.onPreExecute();
    }

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

        try
        JSONObject JSONparams  new JSONObject();
        try {
            JSONparams.put("a", "1");
            JSONparams.put("b", "1");
            JSONparams.put("c", "1");
            JSONparams.put("d", "1");

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


        OkHttpClient okHttpClient  new OkHttpClient().newBuilder().connectTimeout(15, TimeUnit.SECONDS).readTimeout(15, TimeUnit.SECONDS).writeTimeout(15, TimeUnit.SECONDS).build();

        AndroidNetworking.initialize(getApplicationContext(), okHttpClient);

        AndroidNetworking.get(url)
                .setPriority(Priority.HIGH).build()
                .getAsJSONArray(new JSONArrayRequestListener() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.e("Response", String.valueOf(response));

                        try {

                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    for (int i  0; i < response.length(); i++) {
                                        JSONObject objUsers  response.getJSONObject(i);

                                        final String user_id  objUsers.getString("id");
                                        final String issued_company_id  objUsers.getString("subcompany_id");
                                        final String position  objUsers.getString("route_id");
                                        final String card_id  objUsers.getString("route_name");


                                        KMpost kmpost  new KMpost();
                                        kmpost.setId(user_id);
                                        kmpost.setSubcompany_id(issued_company_id);
                                        kmpost.setRoute_id(position);
                                        kmpost.setRoute_name(card_id);

                                        MainActivity.appDatabase.dao2().insertAllkm(kmpost);
                                    }

                                    if (MainActivity.appDatabase.isOpen()){
                                        MainActivity.appDatabase.close();
                                    }

                                    //adding the code for dismiss dialog
                                    loadingDialog.dismiss();

                                }
                            }).start();

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

                    }

                    @Override
                    public void onError(ANError anError) {
                        Log.e("anError", String.valueOf(anError.getErrorCode()));
                    }
                });

    } catch (Throwable throwable) {
        throwable.printStackTrace();

    }

    return false;
}

@Override
protected void onPostExecute(Boolean aBoolean) {
    super.onPostExecute(aBoolean);
}

Answered By – Rubick

Leave a Comment