显示ProgressDialog,同时通过改造获取数据并向realm db添加数据

时间:2016-07-30 06:08:52

标签: android retrofit progressdialog

我的ProgressDialog在调用改造入队方法并向领域添加数据时停止。唯一的问题是progressdialog循环停止并且没有错误。这是我的代码。

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) {

        }
    });

}

问题的数量超过400.尽管我使用了处理程序,但是当所有数据都添加到领域时,progressdialog仍会停止循环并解除。我需要解决什么?提前谢谢。

1 个答案:

答案 0 :(得分:0)

您正在使用领域调用阻止您的UI线程。您需要将onResponse方法中的代码移动到新线程。

最简单的解决方案Realm.getDefaultInstance()。executeTransactionAsync(/ * realm insertions here!* /);

最佳解决方案:RxJava!