【发布时间】:2014-12-24 18:12:48
【问题描述】:
我在一个 sqlite 表中有一个值,该值根据复选框的状态进行更新。 目前,该值确实会更新,但仅在我关闭应用程序时才会更新。 我想要的是:
- 勾选复选框
- 更新sqlite表中的值
- 更新/刷新视图以立即显示更新的值
另外,我将复选框侦听器放入适配器中。这个可以吗?如果没有,我该如何在主要活动上使用监听器?
提前感谢您的帮助。
这里是一些代码
适配器:
public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
{
db = new MyDatabase(context);
final Child child = (Child) getChild(groupPosition,childPosition);
if(convertView == null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.child_layout,null);
}
convertView.setTag(getChild(groupPosition,childPosition).toString());
TextView value = (TextView) convertView.findViewById(R.id.value);
value.setText(String.valueOf(child.getValue()));
CheckBox cb = (CheckBox) convertView.findViewById(R.id.checkBox);
if(child.getValue() == 0)
{
cb.setChecked(true);
}
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b == true)
{
String id = String.valueOf(childPosition+1);
db.updateIsChecked(id);
}
else
{
String id = String.valueOf(childPosition+1);
db.updateIsNotChecked(id);
}
}
});
return convertView;
}
数据库:
public void updateIsChecked(String id)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues newValues = new ContentValues();
newValues.put("value", 0);
db.update("table",newValues,"id =? ",new String[] {id});
db.close();
}
【问题讨论】:
-
我将复选框监听器放在适配器中。这个可以吗? >>> 是的,没关系
-
在 setOnCheckedChangeListener 中调用
adapter.notifyDataSetChanged();。