How do I getLong() from the SharedPreference in a preference setting

android, android-preferences, xml

Solution

You can use:

 SharedPreferences shared = getSharedPreferences("file_pref", MODE_PRIVATE);
 to get a object of SharedPreferences

To get Long values from SharedPreferences: you should use putLong("key","value") from Editor of SharedPreferences class and getLong("key","default_value") to get values which you want. E.x:

//Creating:

SharedPreferences shared = getSharedPreferences("file_pref", MODE_PRIVATE);
Editor edit = shared.edit();
shared.putLong("key1","value1");

//Using:

SharedPreferences shared = getSharedPreferences("file_pref", MODE_PRIVATE);
Long value_long = shared.getLong("key1",0);
//with 0 - default value

You can see this link to understand how to use SharedPreferences class to save simple information in Android clearly and easily:

Save values before close the app?

Hope it will be useful for you.

Problem

I have the following code to get long values from my xml preference file, ``` SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); long longBreak = Integer.parseInt(getPrefs.getString("breakTime", "8000")); long shortBreak = Integer.parseInt(getPrefs.getString("breakTime", "5000")); long workTime = Integer.parseInt(getPrefs.getString("workTime", "10000")); ``` For some reason my LogCat show's an error on the line for "SharedPreference getPrefs=...." and my android application breaks before it loads the long values.... I have my preference xml as follows, ``` <ListPreference android:entries="@array/workList" android:entryValues="@array/workTimes" android:key="workTime" android:summary="Choose Work Time" android:title="Work Time" /> <ListPreference android:entries="@array/breakList" android:entryValues="@array/breakTimes" android:key="breakTime" android:summary="Choose Break Time" android:title="Break Time" /> ``` and my array values as follows, ``` <string-array name="workList"> <item>25 Minutes</item> <item>10 Seconds</item> </string-array> <string-array name="breakList"> <item>15 Minutes</item> <item> 5 Minutes</item> <item>8 Secs</item> <item>5 Secs</item> </string-array> <string-array name="workTimes"> <item>1500000</item> <item>10000</item> </string-array> <string-array name="breakTimes"> <item>900000</item> <item>300000</item> <item>8000</item> <item>5000</item> </string-array> ``` I have tested this same code in a diff app and it works fine.... any help? thanks in advance...

Original source