SharedPreferences doesn´t retrieve Int value in different Activity - java

In my app I am storing integer and string data from different Fragments.
This data is succesfully retrieved in the same Fragment.
The String data is succesfully retrieved over the whole application.
The Integer data however cannot be retrieved from different activities. In the same Fragment however it can be. If i try to get an integer from a different activity, it´s always giving me my set default value.
Here is my code. Note that i´m already using constants to retrieve data.
to save numbers:
public void saveNumberChange(String s, int data){
String help = "com.example.test2.PREFERENCE_FILE_KEY_"+username;
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(help, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(s, data);
editor.commit();
}
and get them back out:
public int getNumber(String s){
int data;
String help = "com.example.test2.PREFERENCE_FILE_KEY_"+username;
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(help, Context.MODE_PRIVATE);
data = sharedPref.getInt(s, 0);
return data;
}
The funny thing is, when i´m storing the integer as strings, they can again be retrieved in the same activity, not though from another activity. With pure strings everything is fine.
Some more code:
Save integer:
saveNumberChange(BeyouApplicationClass.AGE, valueage);
Get integer:
getNumber(BeyouApplicationClass.AGE);
Thanks for your help. I hope you can help me.

You cant access it from another activity because you are only saving it on that activity using the context of that activity.
solution:
instead of using the context.getSharedPreferences of the activity use the PreferenceManager.getDefaultSharedPreferences for your whole application to share data among its activity
example:
saveNumberChange
public void saveNumberChange(String s, int data){
Context context = getActivity();
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(s, data);
editor.commit();
}
getNumber
public int getNumber(String s){
int data;
Context context = getActivity();
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
data = sharedPref.getInt(s, 0);
return data;
}

Try getting your preferences this way:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
in all activities, and getting the editor the same way

So what i found out is following.
For everybody that has the same problem:
Saving shared preferences from inside a fragment will lead to the problem i described earlier.
Only that specific fragment will be able to get the information back out.
So always save from fragment by calling its host activity.
What i did is this:
public static void saveNumberChange(String s, int data){
String help = "com.example.test2.PREFERENCE_FILE_KEY_"+username;
SharedPreferences sharedPref = context.getSharedPreferences(help, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(s, data);
editor.commit();
}
public static int getNumber(String s){
int data;
String help = "com.example.test2.PREFERENCE_FILE_KEY_"+username;
SharedPreferences sharedPref = context.getSharedPreferences(help, Context.MODE_PRIVATE);
data = sharedPref.getInt(s, 0);
return data;
}
make your method static so it can be called from within the attached fragment and everything works fine.

Related

Custom SharedPreferences class

I am new to android and learning. I have theme changing option in my application from where the user can switch themes. I was using a global variable for saving theme number in the app but it was getting a loss when application get cleared from the background. So I have thought for use SharedPreferences for this purpose. I have found one simple and easy way to store and retrieve SharedPreference from here.
My code is like below :
public class Keystore {
private static Keystore store;
private SharedPreferences SP;
private static String filename="Keys";
public static int theme=1;
private Keystore(Context context) {
SP = context.getApplicationContext().getSharedPreferences(filename,0);
}
public static Keystore getInstance(Context context) {
if (store == null) {
store = new Keystore(context);
}
return store;
}
public void put(String key, String value) {
SharedPreferences.Editor editor;
editor = SP.edit();
editor.putString(key, value);
editor.apply();
}
public String get(String key) {
return SP.getString(key, null);
}
public int getInt(String key) {
return SP.getInt(key, 0);
}
public void putInt(String key, int num) {
SharedPreferences.Editor editor;
editor = SP.edit();
editor.putInt(key, num);
editor.apply();
}
public void clear(){
SharedPreferences.Editor editor;
editor = SP.edit();
editor.clear();
editor.apply();
}
public void remove(){
SharedPreferences.Editor editor;
editor = SP.edit();
editor.remove(filename);
editor.apply();
}
}
And as per example given in original answer, I am trying to use it in my activity class like below for getting value
int theme= store.getInt("theme");
Log.d(getClass().getName(),"theme"+theme);
But it's returning 0 instead of 1. I have also doubt that I have saved default value as 1 in that class like public static int theme=1; This is the correct way for saving default value in SharedPreferences?
Thanks
You should use commit ()
Commit your preferences changes back from this Editor to the
SharedPreferences object it is editing. This atomically performs the
requested modifications, replacing whatever is currently in the
SharedPreferences.
public void putInt(String key, int num)
{
SharedPreferences.Editor editor;
editor = SP.edit();
editor.remove("key");
editor.putString("key", num);
editor.commit(); // IF commit() showing warning then use apply() instead .
editor.apply();
}
NOTE
If you don't care about the return value and you're using this from
your application's main thread, consider using apply() instead.
If you want to fetch by default 1 value when you when you don't save data in sharepreferance then you have to change in in your method like
public int getInt(String key) {
return SP.getInt(key, 1);
}
It will work for you.
You have to first save value in shared preferences so that you can retrieve it later. To save it use the below code
store.putInt(your int value);
and retrieve it from shared preference same like you are doing
int theme= store.getInt("theme");
You can do it this way :
private void saveTheme()
{
SharedPreferences sharedpreferences = getSharedPreferences("filename here", Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putInt("theme", 1);
editor.commit();
}
private int getTheme()
{
SharedPreferences sharedpreferences = getSharedPreferences("filename here", Context.MODE_PRIVATE);
sharedpreferences.getInt("theme",0);
}
You can add them in Utility class or make a seperate PreferenceHelper class and make sharedPreference global.
Hope it Helps !!

get shared preference from another activity

this is my settings activity which has got one switch:
settings_inputs_switch = (Switch) findViewById(R.id.settings_inputs_switch);
settings_prefs = getSharedPreferences("settings_prefs", MODE_PRIVATE);
settings_inputs_switch.setChecked(settings_prefs.getBoolean("switch1_state",true ));
settings_inputs_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (settings_inputs_switch.isChecked()){
settings_prefs = getSharedPreferences("settings_prefs", MODE_PRIVATE);
SharedPreferences.Editor editor = settings_prefs.edit();
editor.putBoolean("switch1_state", true);
editor.commit();
}
else {
settings_prefs = getSharedPreferences("settings_prefs", MODE_PRIVATE);
SharedPreferences.Editor editor = settings_prefs.edit();
editor.putBoolean("switch1_state", false);
editor.commit();
}
}
});
how can i get this shared preference value in main activity to do some job based on the value??
One way to achieve this is in your MainActivity read the value of the preference in onResume(). This should get you the latest value each time you get to MainActivity from anywhere.
To read the value, you do it similarly as you write them. In your MainActivity:
#Override
protected void onResume() {
SharedPreferences prefs = getSharedPreferences("settings_prefs", Context.MODE_PRIVATE);
boolean switchState1 = prefs.getBoolean("switch1_state", false);
// Do more stuff
}
(fact: "settings_prefs" is an xml file within your app's local storage)
as stated above one trick i use is to check for changes in onResume() method
You can read preference valve like this in any activity.
SharedPreferences sharedPreference = getSharedPreferences("settings_prefs", Context.MODE_PRIVATE);
boolean value = sharedPreference.getBoolean("switch1_state",false);
SharedPreferences getSharedPreferences (String name, int mode)
Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and modify its values. Only one instance of the SharedPreferences object is returned to any callers for the same name, meaning they will see each other's edits as soon as they are made.
SharedPreferences sharedPreference = getSharedPreferences("settings_prefs",Context.MODE_PRIVATE);
boolean switchState= sharedPreference.getBoolean("switch1_state",false);

How to get SharedPreference from non activity class for non activity

In my Activity class I store some data in a Sharedpreference. My non Activity class has getter and setter to read the Sharedpreference data. I want use this Data in an another Activity class. But I get always a Nullpointer exception.
This is a Code snippet from my Activity class.
SharedPreferences prefs;
prefs = getActivity().getSharedPreferences(KEY_NAME_FOR_PREF, 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("name", name.getText().toString());
editor.commit();
This is my first non Activity class
private String name;
private Context mContext;
public PdfConsultantContacts(Context context){
mContext = context;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
And this is my second non Activity class.
Context mContext;
PdfConsultantContacts contact = new PdfConsultantContacts(mContext);
void initContact() {
SharedPreferences prefs = mContext.getApplicationContext().
getSharedPreferences("app_prefs", 0);
contact.setName(prefs.getString("name", null));
}
When I try to contact.getName(); I get always a Nullpointer exception, but I know that the SharedPreference are saved correctly.
Create a class with two static methods and use this throughout your application to store and retrieve data from SharedPreferences.
public class Utils {
public static void putStringInPreferences(Context context, String value, String key, String pKey) {
SharedPreferences sharedPreferences = context.getSharedPreferences(pKey, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
public static String getStringFromPreferences(Context context,String defaultValue, String key, String pKey) {
SharedPreferences sharedPreferences = context.getSharedPreferences(pKey, Context.MODE_PRIVATE);
String temp = sharedPreferences.getString(key, defaultValue);
return temp;
}
}
Make sure "Code snippet" from your Activity is really executed, you can verify it by print some log.
Make sure the KEY_NAME_FOR_PREF equals "app_prefs".

Saving permanent data using shared preferences?

I am making a Highscore script for my game using Shared Preferences. I want this data to be only held for the phone it is installed on obviously. I have done the following, and the highscore shows and updates, but when I close out of the app and re open it, it resets.
if(finalScore > SharedPrefManager.getHighScore())
SharedPrefManager.SetHighScore(finalScore);
SharedPrefManager.StoreToPref();
SharedPrefManager.java:
package com.divergent.thumbler;
import android.content.Context;
import android.content.SharedPreferences;
// all methods are static , so we can call from any where in the code
//all member variables are private, so that we can save load with our own fun only
public class SharedPrefManager {
//this is your shared preference file name, in which we will save data
public static final String MY_EMP_PREFS = "MySharedPref";
//saving the context, so that we can call all
//shared pref methods from non activity classes.
//because getSharedPreferences required the context.
//but in activity class we can call without this context
private static Context mContext;
// will get user input in below variables, then will store in to shared pref
private static int HighScore = 0;
public static void Init(Context context)
{
mContext = context;
}
public static void LoadFromPref()
{
SharedPreferences settings = mContext.getSharedPreferences(MY_EMP_PREFS, 0);
// Note here the 2nd parameter 0 is the default parameter for private access,
//Operating mode. Use 0 or MODE_PRIVATE for the default operation,
HighScore = settings.getInt("HighScore", HighScore);
}
public static void StoreToPref()
{
// get the existing preference file
SharedPreferences settings = mContext.getSharedPreferences(MY_EMP_PREFS, 0);
//need an editor to edit and save values
SharedPreferences.Editor editor = settings.edit();
editor.putInt("HighScore", HighScore); // Age is the key and mAge is holding the value
//final step to commit (save)the changes in to the shared pref
editor.commit();
}
public static void DeleteSingleEntryFromPref(String keyName)
{
SharedPreferences settings = mContext.getSharedPreferences(MY_EMP_PREFS, 0);
//need an editor to edit and save values
SharedPreferences.Editor editor = settings.edit();
editor.remove(keyName);
editor.commit();
}
public static void DeleteAllEntriesFromPref()
{
SharedPreferences settings = mContext.getSharedPreferences(MY_EMP_PREFS, 0);
//need an editor to edit and save values
SharedPreferences.Editor editor = settings.edit();
editor.clear();
editor.commit();
}
public static void SetHighScore(int score)
{
HighScore = score;
}
public static int getHighScore()
{
return HighScore ;
}
}
Better don't store sensitive information in sharedpreference. All the users that have root permission can see and easily edit your sharedpreference(If it is not encrypted). So dont forget to encrypt all data.
Here is the chunk of code you need to store in sharedpreference
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("finalScore", yourscore);
editor.commit();
UPDATE
You are setting as
editor.putInt("HighScore", HighScore);
and getting as
HighScore = settings.getInt("Age",0);
You should use the same tag
UPDATE
Change
HighScore = settings.getInt("HighScore", HighScore);
to
settings.getInt("HighScore", HighScore);

Save little information as setting in android (like first time that app is run)

I want to save a flag for recognizing that my app is run for the first time or not. For this simple job I don't want to create database..
Is there a simple option to do this? I want to save and read little pieces of information only.
Use sharedPreference or files to save the data but better option is sharedPreference.
For Retrieving
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
For Saving
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", true);
editor.commit();
Use SharedPreferences.
SharedPreferences preferences = getSharedPreferences("prefName", MODE_PRIVATE);
SharedPreferences.Editor edit= preferences.edit();
edit.putBoolean("isFirstRun", false);
edit.commit();
A proper way to do this is by using the Android class SharedPreferences which is used for things like this.
Storing Settings
SharedPreferences settings = getSharedPreferences(NAME_OF_PREFERENCES, MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("appPreviouslyStarted", true);
editor.apply();
Don't forget to apply or your mutations to the settings won't be saved!
You can create multiple settings by using different NAME_OF_PREFERENCES. The settings are stored on the device so will be available after closing the application.
When you try to retrieve NAME_OF_PREFERENCES that is not already created, you create a new one. See more behavior like this here.
apply() versus commit()
You can use editor.apply() as well as editor.commit(), the only difference is that apply() does not return a boolean value with if the edit was successful or not. editor.apply() is therefor faster and more commonly used.
What is MODE_PRIVATE
You can see all about the different modes here. For your case MODE_PRIVATE is fine.
Retrieving settings
SharedPreferences settings = getSharedPreferences(NAME_OF_PREFERENCES, MODE_PRIVATE);
boolean silent = settings.getBoolean("silentMode", false);
When retrieving a settings from a SharedPreferences object you always have to specify a default value which will be returned when the setting was not found. In this case that's false.
I suggest you to go for SharedPreference persistent storage. Its very easy and fast storing/retrival for small amount of information.
See the code to get the value from SharedPreference
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
and to Store value in SharedPreference
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
You can do one class for example:
(like a object for instance)
import android.content.Context;
import android.content.SharedPreferences;
public class SettingsMain {
Context context;
SharedPreferences preferences;
SharedPreferences.Editor editor;
private static final String PREFER_NAME = "settingsMain";
public static final String KEY_VIBRATE = "switchVibrate";
public SettingsMain(Context context) {
this.context = context;
setPreferences();
}
private void setPreferences(){
preferences = context.getSharedPreferences(PREFER_NAME, context.MODE_PRIVATE);
editor = preferences.edit();
}
public void cleanPreferences(){
editor.clear();
editor.commit();
}
public void setStatusVibrate(Boolean status){
editor.putBoolean(KEY_VIBRATE, status);
editor.commit();
}
public Boolean getstatusVibrate(){
return preferences.getBoolean(KEY_VIBRATE, true);
}
}
On your activity call:
public class Home extends AppCompatActivity {
private SettingsMain settings;
private SwitchCompat switchVibrate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.master);
setResources();
getSettings();
}
private void setResources(){
switchVibrate = (SwitchCompat) findViewById(R.id.master_main_body_vibrate_switch);
switchVibrate.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
settings.setStatusVibrate(isChecked);
}
});
}
private void getSettings(){
settings = new SettingsMain(this);
switchVibrate.setChecked(settings.getstatusVibrate());
}
}
What about using static variables globally?
You can do this as given in this tutorial. I know handling Content providers are unnecessary just to keep some flags.
Else you can check out Shared Preferences provided by Android. Here's a good example to get started.
This would be my recommendation.

Categories