0

我在从 viewpager2 更新数据库中正确的学生对象时遇到问题。我的 viewpager2 能够按字母顺序或按年级显示学生,但学生的显示顺序与他们在数据库中的顺序不同。

我尝试从@Override onBindViewHolder 获取 ID 并将结果设置为适配器中的全局 int,但该数字与学生的数据库 ID 不匹配。

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();

        }
    }
}
4

1 回答 1

1

您的btnSaveclickListener 需要位于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();

    }
}
于 2019-09-20T06:22:12.093 回答