滚动时RecyclerView获取IndexOutOfBoundsException(Retrofit2 +库部分RecyclerView)

时间:2018-12-27 20:25:46

标签: java android android-recyclerview retrofit2 indexoutofboundsexception

我想让recyclerview部分显示mysql数据库中的4个数据。我使用了一个包含多个引用的库,当数据为伪数据时,它没有问题,但是当我将其更改为从数据库获取的数据时,我得到了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 :(得分:0)

以下代码段导致了异常:

rvPertanyaan.setAdapter(sectionAdapter)

删除此错误将纠正此问题,并且代码没有任何作用。原因是因为如果它获得成功的响应,则在每个callQuestion函数的末尾设置此适配器。除此之外,您还可以移动

的位置
rvPertanyaan.setLayoutManager(new LinearLayoutManager(this));

callQuestion1();函数之上,因为在设置适配器之前确保已设置布局管理器很重要。

关于IndexOutOfBoundsException,您必须注意的一件事是索引和大小。列表的大小从1开始;相反,索引从0开始。当您尝试访问大于该大小的索引时,将导致IndexOutOfBoundsException。