列表视图中的每个项目都由用户可以编辑的EditTexts
组成。目标是,当用户从特定编辑文本中聚焦时,他插入的值将保存在Realm
数据库中。
将空项添加到列表中效果很好,但实际保存数据是我所挣扎的。
我做了什么:
在适配器中,我为每个edittexts添加了onFocusChangeListener
。但是,我似乎无法保存此特定行或对象的数据
我从适配器获得了该项目的位置,但我无法通过该位置访问RealmObject
。
我的代码:
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.row_exercise, parent, false);
viewHolder = new ViewHolder();
viewHolder.etName = (EditText) convertView.findViewById(R.id.etName);
viewHolder.etWorkload = (EditText) convertView.findViewById(R.id.etWorkload);
viewHolder.etWeight = (EditText) convertView.findViewById(R.id.etWeight);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// assigning values
Exercise e = adapterData.get(position);
viewHolder.etName.setText(e.getName());
viewHolder.etWorkload.setText(e.getWorkload());
viewHolder.etWeight.setText(String.valueOf(e.getWeight()));
// updating information
viewHolder.etName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
Log.v(TAG, "saving ex. name: " + viewHolder.etName.getText());
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
// THIS IS THE PROBLEM
// realm.where(Exercise.class).
}
});
}
}
});
// ...
// a listener for every edittext
感谢。
答案 0 :(得分:1)
只需按ID查询并创建一个可以在匿名类中访问的最终变量。
public class MyAdapter extends RealmBaseAdapter { // RealmRecyclerViewAdapter is better for htis
// ...
final Exercise e = adapterData.get(position);
final long eId = e.getId();
// updating information
viewHolder.etName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
Log.v(TAG, "saving ex. name: " + viewHolder.etName.getText());
realm.executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
Exercise _e = realm.where(Exercise.class)
.equalTo(ExerciseFields.ID, eId)
.findFirst();
if(_e != null) {
// ...
}
}
});
}
}
});