我今天刚开始学习android,到目前为止我做得很好,但是在动态更改切换视图的状态时遇到了问题。我在设置中提供了一个选项来检查更新,以便用户可以根据自己的选择打开或关闭它..
我正在尝试根据存储在数据库中的用户最后选择的选项将切换视图的状态设置为选中或未选中,代码是:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
sw = (Switch) findViewById(R.id.switchupdates);
taskkeeperdb = new DbHelper(this, "taskkeeper", null, 1);
db = taskkeeperdb.getReadableDatabase();
Cursor result = db.rawQuery("select * from tblsettings", null);
System.out.println("Cursore Created");
if (result != null) {
System.out.println("While Block");
while (result.moveToNext()) {
System.out.println("inside while block");
String name = result.getString(result.getColumnIndex("title"));
String value = result.getString(result.getColumnIndex("value"));
System.out.println("values are in variable");
switch (name) {
case "check_updates":
System.out.println("check updae case");
if (value == "YES") {
//sw.setText("Check for Updates: On");
sw.setChecked(true);
System.out.println("YESYESYESYESYESYESYESYESY");
} else {
//sw.setText("Check for Updates: Off");
sw.setChecked(false);
System.out.println("NONONONONONONONONON");
}
break;
default:
break;
}
}
System.out.println("ending the if block.....");
}
if (!result.isClosed()) {
result.close();
}
sw.setOnCheckedChangeListener(this);
}
当用户与切换视图切换交互时更新表.....
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
db = taskkeeperdb.getWritableDatabase();
ContentValues cv = new ContentValues();
if (isChecked) {
cv.put("value", "YES");
db.update("tblsettings", cv, "title='check_updates'", null);
sw.setText("Check for Updates: On");
cv.clear();
} else {
cv.put("value", "NO");
db.update("tblsettings", cv, "title='check_updates'", null);
sw.setText("Check for Updates: Off");
cv.clear();
}
}
现在,当我打开设置视图时,它不会反映更改.. 在我的控制台中,system.out.println
唯一显示的是:
12-12 13:11:59.810: I/System.out(23320): Cursore Created
12-12 13:11:59.810: I/System.out(23320): While Block
12-12 13:11:59.820: I/System.out(23320): ending the if block.....
我的 DbHelper 代码:
public DbHelper(Context context, String databaseName,
CursorFactory factory, int version) {
super(context, DATABASE_NAME, null, 1);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table if not exists tblsettings (id integer primary key autoincrement, title text, value text);");
Cursor result = db.rawQuery("select * from tblsettings", null);
//when no rows then insert fresh rows..
if (result.getCount() == 0) {
ContentValues contentValues = new ContentValues();
contentValues.put("title", "check_updates");
contentValues.put("value", "NO");
db.insert("tblsettings", null, contentValues);
}
if (!result.isClosed()) {
result.close();
}
}
因为我是新手,所以我无法理解真正的原因..请提前帮助谢谢