RecyclerView получает IndexOutOfBoundsException при прокрутке (Retrofit2 + раздел библиотеки RecyclerView) - PullRequest
0 голосов
/ 27 декабря 2018

Я хочу сделать раздел переработчика для отображения 4 данных из базы данных mysql.Я использую библиотеку из нескольких ссылок, которые я получаю, когда данные являются фиктивными, у них нет проблем, но когда я изменяю их на данные, взятые из базы данных, я получаю исключение IndexOutOfBoundsException: Index: 5, Size: 5 Isесть решение для меня?

Вот исключение:

2018-12-28 03:00:51.988 7929-7929/rifafauzi6.id.sectionrecyclerview E/AndroidRuntime: FATAL EXCEPTION: main
Process: rifafauzi6.id.sectionrecyclerview, PID: 7929
java.lang.IndexOutOfBoundsException: Index: 5, Size: 5
    at java.util.ArrayList.set(ArrayList.java:427)
    at rifafauzi6.id.sectionrecyclerview.adapter.QuestionAdapter.onBindItemViewHolder(QuestionAdapter.java:76)
    at io.github.luizgrp.sectionedrecyclerviewadapter.Section.onBindContentViewHolder(Section.java:295)
    at io.github.luizgrp.sectionedrecyclerviewadapter.SectionedRecyclerViewAdapter.onBindViewHolder(SectionedRecyclerViewAdapter.java:293)
    at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6673)
    at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6714)
    at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5647)
    at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5913)
    at android.support.v7.widget.GapWorker.prefetchPositionWithDeadline(GapWorker.java:285)
    at android.support.v7.widget.GapWorker.flushTaskWithDeadline(GapWorker.java:342)
    at android.support.v7.widget.GapWorker.flushTasksWithDeadline(GapWorker.java:358)
    at android.support.v7.widget.GapWorker.prefetch(GapWorker.java:365)
    at android.support.v7.widget.GapWorker.run(GapWorker.java:396)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Вот код QuestionAdapter.java:

public class QuestionAdapter extends StatelessSection {

private String title;
private List<Question> listQuestion;
private Context context;

private LayoutInflater inflter;
public static ArrayList<String> kdPertanyaan;
public static ArrayList<String> kdKuesioner;
public static ArrayList<String> selectedAnswers;

public QuestionAdapter(Context context, String title, List<Question> listQuestion) {
    super(SectionParameters.builder()
            .itemResourceId(R.layout.list_pertanyaan)
            .headerResourceId(R.layout.list_title)
            .build());
    this.context = context;
    this.title = title;
    this.listQuestion = listQuestion;
    kdPertanyaan = new ArrayList<>();
    for (int i = 0; i < listQuestion.size(); i++) {
        kdPertanyaan.add("Nilai tidak boleh kosong");
    }
    kdKuesioner = new ArrayList<>();
    for (int i = 0; i < listQuestion.size(); i++) {
        kdKuesioner.add("Nilai tidak boleh kosong");
    }
    selectedAnswers = new ArrayList<>();
    for (int i = 0; i < listQuestion.size(); i++) {
        selectedAnswers.add("Jawaban tidak boleh kosong");
    }

    inflter = (LayoutInflater.from(context));
}

public void setListQuestion(List<Question> listQuestion) {
    this.listQuestion = listQuestion;
}

@Override
public int getContentItemsTotal() {
    return listQuestion.size();
}

@Override
public RecyclerView.ViewHolder getItemViewHolder(View view) {
    return new ItemViewHolder(view);
}

@Override
public void onBindItemViewHolder(RecyclerView.ViewHolder holder, final int position) {
    final ItemViewHolder itemHolder = (ItemViewHolder) holder;
    Question question = listQuestion.get(position);
    itemHolder.txtKdPertanyaan.setText(kdPertanyaan.set(position, question.getKd_pertanyaan()));
    itemHolder.txtKdKuesioner.setText(kdKuesioner.set(position, question.getKd_kuesioner()));
    itemHolder.txtNo.setText(question.getNo());
    itemHolder.txtPertanyaan.setText(question.getPertanyaan());
    itemHolder.question = question;
    itemHolder.rb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // set Yes values in ArrayList if RadioButton is checked
            if (isChecked)
                selectedAnswers.set(position, "1");
        }
    });

    itemHolder.rb3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // set Yes values in ArrayList if RadioButton is checked
            if (isChecked)
                selectedAnswers.set(position, "3");
        }
    });

    itemHolder.rb5.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // set Yes values in ArrayList if RadioButton is checked
            if (isChecked)
                selectedAnswers.set(position, "5");
        }
    });

    itemHolder.rb7.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // set Yes values in ArrayList if RadioButton is checked
            if (isChecked)
                selectedAnswers.set(position, "7");
        }
    });

}

@Override
public RecyclerView.ViewHolder getHeaderViewHolder(View view) {
    return new HeaderViewHolder(view);
}

@Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) {
    HeaderViewHolder headerHolder = (HeaderViewHolder) holder;

    headerHolder.tvTitle.setText(title);
}

class HeaderViewHolder extends RecyclerView.ViewHolder {

    @BindView(R.id.tvTitle) TextView tvTitle;

    HeaderViewHolder(View view) {
        super(view);
        ButterKnife.bind(this, view);
    }
}

class ItemViewHolder extends RecyclerView.ViewHolder {

    @BindView(R.id.kd_pertanyaan) TextView txtKdPertanyaan;
    @BindView(R.id.kd_kuesioner) TextView txtKdKuesioner;
    @BindView(R.id.no) TextView txtNo;
    @BindView(R.id.question) TextView txtPertanyaan;
    @BindView(R.id.rbValueOf1) RadioButton rb1;
    @BindView(R.id.rbValueOf3) RadioButton rb3;
    @BindView(R.id.rbValueOf5) RadioButton rb5;
    @BindView(R.id.rbValueOf7) RadioButton rb7;

    Question question;
    ItemViewHolder(View view) {
        super(view);
        ButterKnife.bind(this, view);
    }
}

}

Вот код для отображения данных:

public class MainActivity extends AppCompatActivity {

@BindView(R.id.rv_pertanyaan) RecyclerView rvPertanyaan;
ProgressDialog loading;

private SectionedRecyclerViewAdapter sectionAdapter;

String KS01 = "KS01";
String KS02 = "KS02";
String KS03 = "KS03";
String KS04 = "KS04";

String titleA = "A. Kompetensi Pedagogik : kemampuan mengelola proses pembelajaran mahasiswa.";
String titleB = "B. Kompetensi Profesional : kemampuan penguasaan materi pelajaran secara luas dan mendalam.";
String titleC = "C. Kompetensi Kepribadian : kemampuan kepribadian yang mantap, berakhlak mulia, arif, dan berwibawa serta menjadi teladan mahasiswa.";
String titleD = "D. Kompetensi Sosial : kemampuan berkomunikasi dan berinteraksi secara efektif dan efisien dengan mahasiswa, sesama dosen, orangtua/wali, dan masyarakat sekitar";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    sectionAdapter = new SectionedRecyclerViewAdapter();

    loading = new ProgressDialog(this);
    ButterKnife.bind(this);

    callQuestion1(KS01);
    callQuestion2(KS02);
    callQuestion3(KS03);
    callQuestion4(KS04);

    rvPertanyaan.setLayoutManager(new LinearLayoutManager(this));
    rvPertanyaan.setHasFixedSize(true);
    rvPertanyaan.setAdapter(sectionAdapter);

}

private void callQuestion1(String kd_pertanyaan){
    loading.setMessage("Loading ...");
    loading.setCancelable(false);
    loading.show();
    BaseApiService apiService = Server.getUrl().create(BaseApiService.class);
    Call<ResponsModelQuestion> getdata = apiService.getPertanyaan(kd_pertanyaan);
    getdata.enqueue(new Callback<ResponsModelQuestion>() {
        @Override
        public void onResponse(@NonNull Call<ResponsModelQuestion> call, @NonNull Response<ResponsModelQuestion> response) {
            if (response.isSuccessful()){
                loading.dismiss();
                Log.d("onResponse", "Message : " + Objects.requireNonNull(response.body()).getKode());
                List<Question> listPertanyaan = response.body().getResult();

                QuestionAdapter adapter = new QuestionAdapter(getApplicationContext(), titleA, listPertanyaan);
                adapter.setListQuestion(listPertanyaan);
                sectionAdapter.addSection(adapter);
                rvPertanyaan.setAdapter(sectionAdapter);
            }
            else {
                loading.dismiss();
                Toast.makeText(getApplicationContext(), "Gagal Mengambil Data Kuesioner !", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(@NonNull Call<ResponsModelQuestion> call, @NonNull Throwable t) {
            loading.dismiss();
            Log.e("onFailure : ","Message : "+String.valueOf(t.getMessage()));
            Toast.makeText(getApplicationContext(), "Gagal Menghubungkan Internet !", Toast.LENGTH_SHORT).show();
        }
    });
}

private void callQuestion2(String kd_pertanyaan){
    loading.setMessage("Loading ...");
    loading.setCancelable(false);
    loading.show();
    BaseApiService apiService = Server.getUrl().create(BaseApiService.class);
    Call<ResponsModelQuestion> getdata = apiService.getPertanyaan(kd_pertanyaan);
    getdata.enqueue(new Callback<ResponsModelQuestion>() {
        @Override
        public void onResponse(@NonNull Call<ResponsModelQuestion> call, @NonNull Response<ResponsModelQuestion> response) {
            if (response.isSuccessful()){
                loading.dismiss();
                Log.d("onResponse", "Message : " + Objects.requireNonNull(response.body()).getKode());
                List<Question> listPertanyaan = response.body().getResult();

                QuestionAdapter adapter = new QuestionAdapter(getApplicationContext(), titleB, listPertanyaan);
                adapter.setListQuestion(listPertanyaan);
                sectionAdapter.addSection(adapter);
                rvPertanyaan.setAdapter(sectionAdapter);
            }
            else {
                loading.dismiss();
                Toast.makeText(getApplicationContext(), "Gagal Mengambil Data Kuesioner !", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(@NonNull Call<ResponsModelQuestion> call, @NonNull Throwable t) {
            loading.dismiss();
            Log.e("onFailure : ","Message : "+String.valueOf(t.getMessage()));
            Toast.makeText(getApplicationContext(), "Gagal Menghubungkan Internet !", Toast.LENGTH_SHORT).show();
        }
    });
}

private void callQuestion3(String kd_pertanyaan){
    loading.setMessage("Loading ...");
    loading.setCancelable(false);
    loading.show();
    BaseApiService apiService = Server.getUrl().create(BaseApiService.class);
    Call<ResponsModelQuestion> getdata = apiService.getPertanyaan(kd_pertanyaan);
    getdata.enqueue(new Callback<ResponsModelQuestion>() {
        @Override
        public void onResponse(@NonNull Call<ResponsModelQuestion> call, @NonNull Response<ResponsModelQuestion> response) {
            if (response.isSuccessful()){
                loading.dismiss();
                Log.d("onResponse", "Message : " + Objects.requireNonNull(response.body()).getKode());
                List<Question> listPertanyaan = response.body().getResult();

                QuestionAdapter adapter = new QuestionAdapter(getApplicationContext(), titleC, listPertanyaan);
                adapter.setListQuestion(listPertanyaan);
                sectionAdapter.addSection(adapter);
                rvPertanyaan.setAdapter(sectionAdapter);
            }
            else {
                loading.dismiss();
                Toast.makeText(getApplicationContext(), "Gagal Mengambil Data Kuesioner !", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(@NonNull Call<ResponsModelQuestion> call, @NonNull Throwable t) {
            loading.dismiss();
            Log.e("onFailure : ","Message : "+String.valueOf(t.getMessage()));
            Toast.makeText(getApplicationContext(), "Gagal Menghubungkan Internet !", Toast.LENGTH_SHORT).show();
        }
    });
}

private void callQuestion4(String kd_pertanyaan){
    loading.setMessage("Loading ...");
    loading.setCancelable(false);
    loading.show();
    BaseApiService apiService = Server.getUrl().create(BaseApiService.class);
    Call<ResponsModelQuestion> getdata = apiService.getPertanyaan(kd_pertanyaan);
    getdata.enqueue(new Callback<ResponsModelQuestion>() {
        @Override
        public void onResponse(@NonNull Call<ResponsModelQuestion> call, @NonNull Response<ResponsModelQuestion> response) {
            if (response.isSuccessful()){
                loading.dismiss();
                Log.d("onResponse", "Message : " + Objects.requireNonNull(response.body()).getKode());
                List<Question> listPertanyaan = response.body().getResult();

                QuestionAdapter adapter = new QuestionAdapter(getApplicationContext(), titleD, listPertanyaan);
                adapter.setListQuestion(listPertanyaan);
                sectionAdapter.addSection(adapter);
                rvPertanyaan.setAdapter(sectionAdapter);
            }
            else {
                loading.dismiss();
                Toast.makeText(getApplicationContext(), "Gagal Mengambil Data Kuesioner !", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(@NonNull Call<ResponsModelQuestion> call, @NonNull Throwable t) {
            loading.dismiss();
            Log.e("onFailure : ","Message : "+String.valueOf(t.getMessage()));
            Toast.makeText(getApplicationContext(), "Gagal Menghubungkan Internet !", Toast.LENGTH_SHORT).show();
        }
    });
}

}

1 Ответ

0 голосов
/ 28 декабря 2018

Следующий фрагмент кода вызывает исключение:

rvPertanyaan.setAdapter(sectionAdapter)

Устранение этого должно исправить проблему, и код не будет служить цели.Причина в том, что этот адаптер устанавливается в конце каждой функции callQuestion, если он получает успешный ответ.Наряду с этим вы также можете переместить местоположение

rvPertanyaan.setLayoutManager(new LinearLayoutManager(this));

выше функции callQuestion1();, поскольку важно убедиться, что менеджер компоновки установлен перед настройкой адаптера.

Одна вещь, которую вы должны заметить об исключении IndexOutOfBoundsException, это Index и Size.Размер списка начинается с 1;тогда как индекс начинается с 0. Когда вы пытаетесь получить доступ к индексу, размер которого превышает размер, это приведет к исключению IndexOutOfBoundsException.

...