I can pass data with SharedPreferences to second activity from first activity. It works. However, When I close and open the project in the emulator, It doesn't save it.
(There are other codes in second activity but I don't want to confuse your mind. I think problem is not related to them because I don't get any error. Nevertheless, you want them, I can instantly share.)
First 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();}
}
Second 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; }
If you want to save float value in the shared preference you need to add like this.
SharedPreferences prefs = getSharedPreferences(PREFERENCE_NAME, 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putFloat("floatname", 1.5f);
editor.commit();
and then retrieve the float from shared preference is like this
float someFloat = prefs.getFloat("floatname", 0.0f);
add f at the end of the float value
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.