Saya mengalami masalah saat memperbarui objek siswa yang benar di database saya dari viewpager2. Viewpager2 saya memiliki kemampuan untuk menampilkan siswa menurut abjad atau berdasarkan kelas, siswa tidak ditampilkan dalam urutan yang sama dengan yang ada di database.

Saya mencoba mendapatkan ID dari @Override onBindViewHolder dan mengatur hasilnya ke int global di adaptor tetapi nomor itu tidak cocok dengan ID database siswa.

private int mDbId;

//Constructor
ViewPagerAdapter(Context context, List<StudentEntity data) {
    this.mContext = context;
    this.mInflater = LayoutInflater.from(context);
    this.mData = data;

}

@Override 
public void onBindViewHolder(ViewHolder holder, int position) {
    StudentEntity student = mdata.get(position);
    mDBId = student.getId();
    mFirstName = student.getFirstName();
    mLastName = student.getLastName();
    mGrade = student.getGrade();

    holder.inputFirstName.setText(mFirstName);
    ...
}

public class ViewHolder extends RecyclerView.ViewHolder {
    private Button btnSave;
    private TextInputEditText editFirstName;
    ...

    ViewHolder(View itemView) {
        super(itemView);

        editFirst = itemView.findViewById(R.id.edit_text_first_name);
        ...

        btnSave.setOnClickListener(view -> {
            Intent saveIntent = new Intent();

            // the mDbId is where I'm having issues. 
            saveIntent.putExtra("EXTRA_DB_id", mDbId;
            saveIntent.putExtra("EXTRA_FIRST_NAME", editFirstName.getText().toString();     

            ((Activity mContext).setResult(RESULT_OK, saveIntent);

            // .finish() works as intented
            ((Activity mContext).finish();

        }
    }
}
0
Shawn 20 September 2019, 06:13

1 menjawab

Jawaban Terbaik

ClickListener btnSave Anda harus berada di onBindViewHolder.

@Override 
public void onBindViewHolder(ViewHolder holder, int position) {
    StudentEntity student = mdata.get(holder.getAdapterPosition());
    int studentId = student.getId();
    mFirstName = student.getFirstName();
    mLastName = student.getLastName();
    mGrade = student.getGrade();

    holder.inputFirstName.setText(mFirstName);
    btnSave.setOnClickListener(view -> {
        Intent saveIntent = new Intent();
        saveIntent.putExtra("EXTRA_DB_id", studentId);
        saveIntent.putExtra("EXTRA_FIRST_NAME", editFirstName.getText().toString();     
        ((Activity mContext).setResult(RESULT_OK, saveIntent);
        ((Activity mContext).finish();

    }
}
1
DarShan 20 September 2019, 06:22