我可以将带有SharedPreferences的数据传递给第一个活动的第二个活动。有用。但是,当我在模拟器中关闭并打开项目时,它不会保存。
(第二项活动还有其他代码,但我不想混淆你的想法。我认为问题与他们无关,因为我没有得到任何错误。但是,你想要他们,我可以立即分享。)
第一项活动:
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();}
}
第二项活动:
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; }
答案 0 :(得分:1)
如果要在共享首选项中保存浮点值,则需要像这样添加。
SharedPreferences prefs = getSharedPreferences(PREFERENCE_NAME, 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putFloat("floatname", 1.5f);
editor.commit();
然后从共享首选项中检索浮点数就像这样
float someFloat = prefs.getFloat("floatname", 0.0f);
在浮点值
的末尾添加f