gpt4 book ai didi

java - SharedPreferences 可以通过但不保存

转载 作者:行者123 更新时间:2023-11-30 00:19:56 26 4
gpt4 key购买 nike

我可以通过 SharedPreferences 将数据从第一个 Activity 传递到第二个 Activity 。有用。但是,当我关闭并打开模拟器中的项目时,它不保存它。

(第二个 Activity 中还有其他代码,但我不想混淆你的想法。我认为问题与它们无关,因为我没有得到任何错误。不过,你想要它们,我可以立即分享。 )

第一个 Activity :

private float difference;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_myMain);
sharedPreferences=getSharedPreferences("MyData", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
}

@Override
public void onClick(View v) {
if (v.getId() == button1.getId()){
editor.putFloat("float1", difference);
editor.commit();}
if(v.getId() == set.getId()){
editor.putFloat("float2", difference);
editor.commit();}
if(v.getId() == sleepB.getId()){
editor.putFloat("float3", difference);
editor.commit();}
}

第二个 Activity :

Float intValue, intValue2, intValue3;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily);
sharedPreferences=getSharedPreferences("MyData", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
}

private Object[] createItem(long timestamp) {
data = new ArrayList<>();
s= getIntent().getStringExtra("date");
if(s != null) {
formatter = new SimpleDateFormat("yyyy/MM/dd");
try {
date2 = formatter.parse(s);
timeStampDate = new Timestamp((date2.getTime()));
myTime = timeStampDate.getTime();
editor.putLong("long1",myTime);
editor.commit();
} catch (ParseException e) {
e.printStackTrace();
}
otherMyTime = sharedPreferences.getLong("long1",0);
intValue = sharedPreferences.getFloat("float1", (float) 0.0);
intValue2 = sharedPreferences.getFloat("float2", (float)0.0);
intValue3 = sharedPreferences.getFloat("float3",(float) 0.0);

item = new Object[COLUMN_NAMES.length];
item[0] = otherMyTime;
item[1] = intValue;
item[2] = intValue2;
item[3] = intValue3;
data.add(item);
}

item = new Object[COLUMN_NAMES.length];
item[0] = timestamp;
item[1] = 0;
item[2] = 0;
item[3] = 0;
data.add(item);

cursor.addAll(data);
return item; }

最佳答案

如果你想在共享首选项中保存浮点值,你需要像这样添加。

SharedPreferences prefs = getSharedPreferences(PREFERENCE_NAME, 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putFloat("floatname", 1.5f);
editor.commit();

然后从共享首选项中检索 float 是这样的

float someFloat = prefs.getFloat("floatname", 0.0f);

在浮点值末尾添加f

关于java - SharedPreferences 可以通过但不保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46506717/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com