在Android中存储布尔选择可以通过使用SharedPreferences或SQLite数据库来实现。
SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("isChoiceSelected", true); // 存储布尔值
editor.apply(); // 提交更改
boolean isChoiceSelected = sharedPreferences.getBoolean("isChoiceSelected", false); // 默认值为false
editor.remove("isChoiceSelected");
editor.apply();
public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "my_database";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "my_table";
private static final String COLUMN_NAME_CHOICE = "choice";
public MyDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String createTableQuery = "CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_NAME_CHOICE + " INTEGER)";
db.execSQL(createTableQuery);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 升级数据库时的操作
}
}
MyDatabaseHelper dbHelper = new MyDatabaseHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("choice", 1); // 存储布尔值
db.insert(TABLE_NAME, null, values);
db.close();
MyDatabaseHelper dbHelper = new MyDatabaseHelper(context);
SQLiteDatabase db = dbHelper.getReadableDatabase();
String[] projection = {COLUMN_NAME_CHOICE};
Cursor cursor = db.query(TABLE_NAME, projection, null, null, null, null, null);
boolean isChoiceSelected = false;
if (cursor.moveToFirst()) {
int choiceIndex = cursor.getColumnIndex(COLUMN_NAME_CHOICE);
int choiceValue = cursor.getInt(choiceIndex);
isChoiceSelected = choiceValue == 1;
}
cursor.close();
db.close();
MyDatabaseHelper dbHelper = new MyDatabaseHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.delete(TABLE_NAME, null, null);
db.close();
以上是在Android中存储布尔选择的两种常见方法。根据具体需求和场景选择合适的方法进行存储和读取。
领取专属 10元无门槛券
手把手带您无忧上云