如何在Android Studio上使用SharedPreferences保存一些数据,如布尔值?
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME,MODE_PRIVATE).edit();
editor.putBoolean("firststart",false);
editor.apply();
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME,MODE_PRIVATE);
boolean firstStart= prefs.getBoolean("firststart",false);
if (!firstStart) {
Intent intent12 = new Intent(getApplicationContext(),FirstStart.class);
startActivity(intent12);
prefs.getBoolean("firststart",true);
}
else if (firstStart) {
}
如果我每次创建活动时都使用此代码,则布尔值返回false,然后返回true。 如何解决此问题并且不会丢失数据?
答案 0 :(得分:1)
您不需要每次都将false
保存为值,只要没有值,就会false
prefs.getBoolean("firststart",false)
true
否则 SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME,MODE_PRIVATE).edit();
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME,MODE_PRIVATE);
boolean firstStart= prefs.getBoolean("firststart",false);
if (!firstStart) {
// save true during first time initialization
Intent intent12 = new Intent(getApplicationContext(),FirstStart.class);
startActivity(intent12);
editor.putBoolean("firststart",true);
editor.apply();
} // for second run, when you get true
else if (firstStart) {
}
作为您的保存值
string query = "SELECT :p0, :p0 FROM DUMMY";
IDbCommand dbCommand = hanaConnection.CreateCommand();
dbCommand.CommandText = query;
IDataParameter param = dbCommand.CreateParameter();
param.Value = "A";
param.ParameterName = ":p0";
dbCommand.Parameters.Add(param);
hanaConnection.Open();
IDataReader dataReader = dbCommand.ExecuteReader();
while (dataReader.Read())
{
ReadSingleRow((IDataRecord)dataReader);
}
答案 1 :(得分:0)
实际上你的代码在每个onCreate上重置自己,所以你需要做的就是这样的
public class MyActivity extends Activity {
SharedPreferences prefs = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
}
@Override
protected void onResume() {
super.onResume();
if (prefs.getBoolean("firststart", true)) {
// Do first run stuff here then set 'firstrun' as false
// using the following line to edit/commit prefs
prefs.edit().putBoolean("firststart", false).commit();
}
}
}
希望这会有所帮助