0

I am saving "long" in Sharedpreferences as below :

SharedPreferences preferences = context.getSharedPreferences("STARTTIME", android.content.Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putLong("startTime", startTime);
    editor.commit();

and Retreiving "long" from Sharedpreference as below :

preferences = context.getSharedPreferences("STARTTIME", android.content.Context.MODE_PRIVATE);
long getstartTime = preferences.getLong(startTime, 0);

But I am getting value "0" while retreiving.....Any guess where am i making mistake ?

user1223035
  • 241
  • 2
  • 21

2 Answers2

1

This:

long getstartTime = preferences.getLong(startTime, 0);

should be

long getstartTime = preferences.getLong("startTime", 0);

Android interpreted the startTime as a resource id, and because it didn't find it, you get the default value, that you passed in, as returnvalue.

Devolus
  • 21,661
  • 13
  • 66
  • 113
  • Aah...Yes, thanks...I was wondering too...I didn't get compile error, earlier I was trying the same but then it would give error to change "getLong" to "getString" which was strange... – user1223035 Jun 17 '13 at 10:10
  • 1
    At first I also expected oyu to get a compile error, but then I remembered that you can load Strings by resource ids so I put the explanation. :) You should mark an answer as accepted in order for other users also to identify solutions similar problems. – Devolus Jun 17 '13 at 10:13
  • Thanks Devolus, can u tell me where to accept. I never tried it. I am sure that will be really helpful for other developers – user1223035 Jun 17 '13 at 10:55
  • 1
    On the left of the answer are small up and down arrows. here you can vote if an answer or a question was good or not. If you get an answer to your own question you also see a chechmark below these arrows. Here you can accept an answer. You should read these links as they will answer those questions in more detail: http://stackoverflow.com/help/answering and http://stackoverflow.com/help/reputation – Devolus Jun 17 '13 at 11:16
  • Thanks Devolus...I did it :) – user1223035 Jun 17 '13 at 11:24
0

You should pass the same key to the getLong() method i.e. literal "startTime" .

long getstartTime = preferences.getLong("startTime", 0);
AllTooSir
  • 48,828
  • 16
  • 130
  • 164