在我的代码中,当我打开活动并将值从Spinner加载时,我首先从数据库中读取所需的表。在我的表中,我设置了布尔值,整个表中只有一个值为true。首先,我设置一个默认值为true。如果用户想要更改它,则在打开活动并输入默认值时,将新值设置到spinner中,按保存或其他操作,并在数据库表中将布尔值从默认值更改为新值。此外,当您打开活动时,将真实值设置为Spinner中的值。
希望这可以帮助您,不要让您感到困惑:P
以下是我的代码,可能不是最好的编写代码,但它运行良好:
db.open();
Cursor c1 = db.getAllCurrencies();
currentCurrencyList = new ArrayList<String>();
if (c1.moveToFirst()) {
do {
currentCurrencyList.add(c1.getString(c1
.getColumnIndex(DBAdapter.MY_CURRENT_CURRENCY_NAMES)));
} while (c1.moveToNext());
}
db.close();
dataAdapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, currentCurrencyList);
dataAdapter1
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
currencySpinner.setAdapter(dataAdapter1);
currencySpinner.setSelection(0);
db.open();
Cursor c2 = db.getCurrentCurrency();
currentCurrencyList2 = new ArrayList<String>();
String currencySymbol = "";
if (c2.getCount() == 1) {
currencySymbol = c2.getString(c2
.getColumnIndex(DBAdapter.MY_CURRENT_CURRENCY_NAMES));
}
currentCurrency.setText(currencySymbol);
db.close();
setNewCurrencyButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String spinnerSelection = "";
spinnerSelection = currencySpinner.getSelectedItem().toString();
db.open();
db.updateOldCurrency();
db.updateCurrentCurrency(spinnerSelection);
Cursor c3 = db.getCurrentCurrency();
currentCurrencyList3 = new ArrayList<String>();
String currencySymbol2 = "";
if (c3.moveToFirst()) {
do {
currentCurrencyList3.add(c3.getString(c3
.getColumnIndex(DBAdapter.MY_CURRENT_CURRENCY_NAMES)));
} while (c3.moveToNext());
for (int i = 0; i <= currentCurrencyList3.size() - 1; i++) {
currencySymbol2 = currentCurrencyList3.get(i);
}
}
currentCurrency.setText(currencySymbol2);
db.close();
}
});
dpAdapter类
public boolean updateOldCurrency() {
ContentValues args = new ContentValues();
args.put(MY_CURRENT_CURRENCY_BOOLEAN, 0);
return db.update(MY_CURRENT_CURRENCY_TABLE, args,
MY_CURRENT_CURRENCY_BOOLEAN + "='" + 1 + "'", null) > 0;
}
public boolean updateCurrentCurrency(String rowId) {
ContentValues args = new ContentValues();
args.put(MY_CURRENT_CURRENCY_BOOLEAN, 1);
return db.update(MY_CURRENT_CURRENCY_TABLE, args,
MY_CURRENT_CURRENCY_NAMES + "='" + rowId + "'", null) > 0;
}