0

Всем привет,имеется такой класс для загрузки Mysql в SQL, раньше было FBD в SQL, все загружается ровно,но пропало окно с диалогом прогресса загрузки.В логах процент считается.Подскажите пожалуйста как починить?

public class LoadDataService extends AsyncTask<Void, Integer, Void> {
    private Context context;
    ProgressDialog pd;
    public LoadDataService(Context context) {
        this.context = context;
    }

    protected void onPreExecute() {
        this.pd = new ProgressDialog(context);
        this.pd.setTitle("Получение данных");
        this.pd.setMessage("Загрузка базы данных с сервера...");
        this.pd.setProgress(0);
        this.pd.setCancelable(false);
        this.pd.setMax(100);
        this.pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        this.pd.show();
    }
    int current_percent = 0;
    int count = 0;
    @Override
    protected Void doInBackground(Void... params) {
        EasiestDB easiestDB = EasiestDB.init(context, "ObjectsData", 1);
        String time = String.valueOf(new Date().getTime()/1000L);
        easiestDB.addTableColumns("Stores",
                new Column("auth_id", "text"),//1
                new Column("category_id", "text"),//2
                new Column("store_id", "text", "unique"),//3
                new Column("store_desc", "text"),//4
                new Column("store_name", "text"),//5
                new Column("keywords", "text"),//6
                new Column("telephone", "text"),//7
                new Column("latitude", "text"),//8
                new Column("longitude", "text")//9
        )
                .addTableColumns("Photos",
                        new Column("store_id", "text"),
                        new Column("photo_url", "text")
                )
                .addTableColumns("Service",
                        new Column("update_time", "text")
                )
                .addTableColumns("News",
                        new Column("text", "text"),
                        new Column("title", "text"),
                        new Column("photo", "text"),
                        new Column("descr", "text"),
                        new Column("auth", "text"),
                        new Column("time", "text"),
                        new Column("removed", "integer"),
                        new Column("news_id", "text", "unique")
                )
                .addTableColumns("Chat",
                        new Column("auth", "text"),
                        new Column("message", "text"),
                        new Column("date", "text"),
                        new Column("ava", "text"),
                        new Column("sid", "text"),
                        new Column("rank", "text"),
                        new Column("mid", "text", "unique")
                )
                .doneAddingTables();
        Queries q = App.getQueriesInstance(context);
        q.insertTime();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://XXX.ru/api/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        PostInterface service = retrofit.create(PostInterface.class);
        Call<List<MapData>> call = service.getMap("full");
        call.enqueue(new Callback<List<MapData>>() {
            @Override
            public void onResponse(Call<List<MapData>> call, Response<List<MapData>> response) {
                List<MapData> newData = response.body();
                String max = String.valueOf(newData.size());
                for (int i = 0; i < newData.size(); i++) {
                    String auth_id = "XXX";
                    if (newData.get(i).getAuth().length() > 1) {
                        auth_id = newData.get(i).getAuth();
                    }
                    String store_id = newData.get(i).getStore_id();
                    String keywords = newData.get(i).getKey();
                    String telephone = newData.get(i).getTel();
                    String latitude = newData.get(i).getLat();
                    String longitude = newData.get(i).getLon();
                    String store_desc = newData.get(i).getStore_desc();
                    String store_name = newData.get(i).getStore_name();
                    String category_id = String.valueOf(newData.get(i).getCategory());
                    if (!category_id.equals("15")) {
                        easiestDB.addDataInTable(0,
                                new Datum("store_id", store_id),
                                new Datum("keywords", keywords),
                                new Datum("telephone", telephone),
                                new Datum("latitude", latitude),
                                new Datum("longitude", longitude),
                                new Datum("store_desc", store_desc),
                                new Datum("store_name", store_name),
                                new Datum("category_id", category_id),
                                new Datum("auth_id", auth_id)
                        );
                        List<Value> url = newData.get(i).getPhotos();
                        for (Value test : url) {
                            String data = test.getPhoto_url();
                            easiestDB.addDataInTable(1,
                                    new Datum("store_id", store_id),
                                    new Datum("photo_url", data)
                            );
                        }
                    }
                    count++;
                    current_percent = (100 * count / Integer.parseInt(max));
                    Log.e("test", ""+current_percent);
                    publishProgress(current_percent);
                }
            }

            @Override
            public void onFailure(Call<List<MapData>> call, Throwable t) {

            }
        });
        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        pd.setMessage("Загрузка базы данных с сервера...");
        pd.setProgress(values[0]);
        Log.e("test","values = "+values[0]);
    }

    @Override
    protected void onPostExecute(Void result) {
        SharedPreferences sharedPreferences = context.getSharedPreferences("App", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean("firstLogin", false);
        editor.apply();
        if (pd != null && pd.isShowing()) {
            pd.dismiss();
        }
    }

}

1 ответ 1

1

Могу предположить только то, что context != activity

this.pd = new ProgressDialog(context);

Для вывода ProgressDialog необходимо передавать контекст Activity.

Но если в AsyncTask передать контекст активити то нужно следить за утечкой памяти..

1
  • new LoadDataService(MainActivity.this).execute(); запускаю таким образом,так что вроде контекст идет. Код выполняется чисто для загрузки данных с MYSQL после чего идет сокрытие диалога и все,больше он не вызывается.Только на первом запуске
    – Urban Side
    8 июл 2020 в 12:21

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.