简体   繁体   中英

showing ProgressDialog while getting data with retrofit and adding data to realm db

My ProgressDialog becomes stop while calling retrofit enqueue method and adding data to realm. The only problem is progressdialog cycle comes stop and there is no errors. Here is my code.

private void DownloadQuestions(final String chapterId){

    final Call<Questions> questionCall = MainApi.createService(MainService.class).
            getQuestionsByChapterId(chapterId);
    Log.d("Package_Name", getApplicationContext().getPackageName());
    pDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
    pDialog.getProgressHelper().setBarColor(Color.parseColor("#272E3E"));
    pDialog.setTitleText("Downloading");
    pDialog.show();

    questionCall.enqueue(new Callback<Questions>() {
        @Override
        public void onResponse(Call<Questions> call, Response<Questions> response) {
            questions.addAll(response.body().getQuestions());
            for (Question ques : questions) {
                realm.beginTransaction();

                QuestionRealm questionRealm = realm.createObject(QuestionRealm.class);
                questionRealm.setChapter_id(ques.getChapter_id());
                questionRealm.setQuestion_type_id(ques.getQuestion_type_id());
                questionRealm.setQuestion(ques.getQuestion());
                questionRealm.setHint1(ques.getHint1());
                questionRealm.setHint2(ques.getHint2());
                questionRealm.setHint3(ques.getHint3());
                questionRealm.setHint4(ques.getHint4());
                questionRealm.setAnswer(ques.getAnswer());
                questionRealm.setYear(ques.getYear());
                realm.commitTransaction();
            }
            pDialog.dismissWithAnimation();
            Toast.makeText(getApplicationContext(), " Questions downloaded", Toast.LENGTH_SHORT).show();
            quesDownload.setVisibility(View.GONE);
            chapCheckBox.setVisibility(View.VISIBLE);

        }

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

        }
    });

}

The number of questions is above 400. Though I use handler, that progressdialog still comes stop cycling and dismiss when all data is added to realm. What do I need to solve? Thanks in advance.

You are blocking your UI thread with the realm calls. You need to move the code inside the onResponse method to a new thread.

Easiest solution Realm.getDefaultInstance().executeTransactionAsync(/* realm insertions here! */);

Best Solution: RxJava!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM