0
checkUpdate(last_update, SplashActivity.this);
Intent l = new Intent(SplashActivity.this, MainActivity.class);
startActivity(l);

here's the code inside checkUpdate method

private void checkUpdate(String last_update, final Context context) {

    mydb = new DatabaseHelper(context);

    Cursor res = mydb.get_options();
    res.moveToFirst();
    if (((res != null) && (res.getCount() > 0))) {
        String dbLastUpdate = res.getString(0);
        if (!last_update.equals(dbLastUpdate)) {
            // Toast.makeText(context, "Database will be updated ", Toast.LENGTH_SHORT).show();
            db_Request(context);
        } else {
            Intent l = new Intent(SplashActivity.this, MainActivity.class);
            startActivity(l);
        }
    } else {
        //Toast.makeText(context, "Database", Toast.LENGTH_SHORT).show();
        db_Request(context);

    }

    return;
}

private void db_Request(final Context context) {

    dialog = CustomProgressDialog.showProgressDialog(context, "Loading...");
    mydb = new DatabaseHelper(context);
    apiInterface = ApiClient.getClient().create(ApiInterface.class);
    Call<DatabaseModel> call = apiInterface.providers();
    call.enqueue(new Callback<DatabaseModel>() {
        @Override
        public void onResponse(Call<DatabaseModel> call, Response<DatabaseModel> response) {


            DatabaseModel result = response.body();
            if (result != null) {

                Boolean status = response.body().isStatus();
                String msg = response.body().getMsg();
                if (status.equals(true)) {

                    mydb.delete();
                    DatabaseModel.Data data = response.body().getData();
                    List<DatabaseModel.Service_parameters> params = data.getService_parameters();
                    for (int i = 0; i < params.size(); i++) {
                        int id = params.get(i).getId();
                        String service_type = params.get(i).getService_type();
                        int external_system_id = params.get(i).getExternal_system_id();
                        int payment_service_id = params.get(i).getPayment_service_id();
                        String name_ar = params.get(i).getName_ar();
                        String name_en = params.get(i).getName_en();
                        int position = params.get(i).getPosition();
                        String visible = params.get(i).getVisible();
                        String required = params.get(i).getRequired();
                        String type = params.get(i).getType();
                        String is_client_id = params.get(i).getIs_client_id();
                        String default_value = params.get(i).getDefault_value();
                        int min_length = params.get(i).getMin_length();
                        int max_length = params.get(i).getMax_length();

                        mydb.insert_service_parameters(context, id, service_type, external_system_id, payment_service_id, name_ar, name_en,
                                position, visible, required, type, is_client_id, default_value, min_length, max_length);

                    }



                    List<DatabaseModel.Service_provider_categories> cat = data.getService_provider_categories();
                    for (int i = 0; i < cat.size(); i++) {
                        int id = cat.get(i).getId();
                        String name_ar = cat.get(i).getName_ar();
                        String name_en = cat.get(i).getName_en();
                        String description_ar = cat.get(i).getDescription_ar();
                        String description_en = cat.get(i).getDescription_en();
                        String icon = cat.get(i).getIcon();

                        mydb.insert_service_provider_categories(context, id, name_ar, name_en, description_ar, description_en, icon);


                    }


                    List<DatabaseModel.Service_providers> prov = data.getService_providers();
                    for (int i = 0; i < prov.size(); i++) {
                        int id = prov.get(i).getId();
                        int service_provider_category_id = prov.get(i).getService_provider_category_id();
                        String name_ar = prov.get(i).getName_ar();
                        String name_en = prov.get(i).getName_en();
                        String description_ar = prov.get(i).getDescription_ar();
                        String description_en = prov.get(i).getDescription_en();
                        String logo = prov.get(i).getLogo();

                        mydb.insert_service_providers(context, id, service_provider_category_id, name_ar, name_en, description_ar,
                                description_en, logo);

                    }


                    List<DatabaseModel.Services> serv = data.getServices();
                    for (int i = 0; i < serv.size(); i++) {
                        int id = serv.get(i).getId();
                        int service_provider_id = serv.get(i).getService_provider_id();
                        String name_ar = serv.get(i).getName_ar();
                        String name_en = serv.get(i).getName_en();
                        String description_ar = serv.get(i).getDescription_ar();
                        String description_en = serv.get(i).getDescription_en();
                        String icon = serv.get(i).getIcon();

                        mydb.insert_services(context, id, service_provider_id, name_ar, name_en, description_ar, description_en,
                                icon);

                    }


                    List<DatabaseModel.Options> opts = data.getOptions();

                    String name = opts.get(0).getName();
                    String value = opts.get(0).getValue();

                    mydb.insert_options(context, name, value);

                    Intent l = new Intent(SplashActivity.this, MainActivity.class);
                    startActivity(l);

                    dialog.dismiss();
                }

            } else {

                 /*   CustomAlertDialog.getInstance().showInfoDialog(context.getString(R.string.error), context.getString(R.string.errorConnectingServer),
                        context.getString(R.string.close),
                        context, 1);*/
            }

        }

        @Override
        public void onFailure(Call<DatabaseModel> call, Throwable t) {
      /*      CustomAlertDialog.getInstance().showInfoDialog(context.getString(R.string.error), context.getString(R.string.errorConnectingServer),
                    context.getString(R.string.close),
                    context, 1);*/
            dialog.dismiss();
        }
    });

}

as you can see I use the Retrofit library to send requests to a server inside checkUpdate method, according to the Retrofit library it is done in a background thread. but the problem is main thread is still running and it reaches the startActivity method before the checkUpdate method running in background task has finished.

How can I force my main thread to wait for the background task to finish ?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Michael
  • 411
  • 2
  • 6
  • 15
  • by using sync call ... of course it will lead to NetworkOnMainThreadException – Selvin Dec 04 '17 at 11:37
  • 1
    That's why it is a background task, why you want to wait? – Murtaza Khursheed Hussain Dec 04 '17 at 11:38
  • @Selvin how can I use it, can you show me please – Michael Dec 04 '17 at 11:38
  • @Selvin Not the best idea to use a sync call in the main thread. – Xavier Rubio Jansana Dec 04 '17 at 11:39
  • 1
    @XavierRubioJansana yeah, i know ... That's what i'm trying to show him – Selvin Dec 04 '17 at 11:39
  • 1
    Quick-and-dirty solution: Move the startActivity() call to your the background thread callback and then use a Activity#runOnUiThread() to wrap startActivity() call. – Xavier Rubio Jansana Dec 04 '17 at 11:40
  • A complete explanation of the why's and how's is in Android Documentation. See https://developer.android.com/guide/components/processes-and-threads.html – Xavier Rubio Jansana Dec 04 '17 at 11:43
  • Use a call back (interface) to notify the main thread – Zacharias Manuel Dec 04 '17 at 11:44
  • @XavierRubioJansana unfortunately I can't apply ur answer on my code coz I should transfer the checkUpdate method to a separated class – Michael Dec 04 '17 at 11:44
  • Why? Notice that while you strictly don't need an `Activity` to run code on the UI thread, in that case you probably want it, in order to launch next activity. See this related answer https://stackoverflow.com/questions/39917308/how-to-post-toast-from-non-ui-widget-thread/39917437#39917437 – Xavier Rubio Jansana Dec 04 '17 at 11:49
  • There is many question how to wait for async tasks on main thread (mostly asking such question doesn't make sens) Why? ... 1. You have to ask why you used async api there .. 2. Prolly "to avoid NetworkOnMainThreadException" you will say... 3. Then normal answer is then why you just don't disable this error? 4. Because you don't want to build application which is not responding ... 5. **Then you should also know that any waiting for result of background thread on main thread will lead to the same situation as you would not use async api at all** – Selvin Dec 04 '17 at 11:51
  • @Selvin I hope my team leader will be convinced after reading ur comment – Michael Dec 04 '17 at 11:54

0 Answers0