Retrieving SharedPreferences Data Failure - android

I am trying to use SharedPreferences, but I keep encountering the following problem.
In the class where I create the file & add information to it I do the following:
private SharedPreferences prefs = null;
private SharedPreferences.Editor editor = null;
public void setStuff (String info, boolean save, Context appCT) {
if (prefs == null && editor == null) {
prefs = appCT.getSharedPreferences("preferences", Context.MODE_PRIVATE);
editor = prefs.edit();
}
editor.putString("Custom", info);
editor.commit();
}
Which, to my knowledge, runs perfectly. However, when I attempt to access that information I stored in 'preferences' from another other class:
private static SharedPreferences prefs = null;
private static String custom = null;
public static void getStuff(Context appCT) {
if (prefs == null) {
prefs = appCT.getSharedPreferences("preferences", Context.MODE_PRIVATE);
custom = prefs.getString("Custom", null);
}
}
The value of custom is always null, as if I never stored the String. Can anyone tell me why this is?
I have searched for an answer; I am using a context for getSharedPreferences, I have following all of the instructions & tutorials I have found with no varying results.
NOTE: The classes are not in the same application. Is this a problem? Can I not access the preferences of another application?
Thank you.

getStuff() only sets custom if prefs is null. So, the method will do nothing after the first time it is called. Or, if prefs is set before this method is ever called, then the method will never do anything.
The method should look like this, instead:
public static void getStuff(Context appCT) {
if (prefs == null) {
prefs = appCT.getSharedPreferences("preferences", Context.MODE_PRIVATE);
}
custom = prefs.getString("Custom", null);
}
Also, if the 2 classes are in different applications, Context.MODE_PRIVATE will prevent them from sharing the SharedPreferences. You can use Context.MODE_WORLD_READABLE or Context.MODE_WORLD_WRITEABLE instead, but that is very unsafe and deprecated in API level 17. See the information at the above links to see what is recommended instead.

I think you need do to a prefs = PreferenceManager.getDefaultSharedPreferences(yourcontext); first.

Related

SharedPreferences saves state between android activities but not upon restarting the app

I'm running to a really weird behavior with SharedPreferences. I'm wondering if I'm running into a synchronization issue.
It seems like the app can remember the preference changes in between activities but not when I restart the app. The state always returns back to the very first instance I created a preference. I've followed several examples, tutorials, and android documentation that all suggest similar code layout. I also watched how the preference.xml file changed while interacting with my code using the debugger and I confirmed it looked like the key value pair updated.
Could I be experiencing a synchronization issue with my emulator? I tried using both the editor.apply() method and editor.commit() method with the same results.
The only thing I've found that fixes my problem is using the editor.clear() method, but this feels a bit hacky...
note: please forgive the variable names, I'm making a pokedex...
public class SecondActivity extends AppCompatActivity {
private boolean caught;
private Set<String> pokemonCaught;
private String pokemonName;
public SharedPreferences sharedPreferences;
public static final String SHARED_PREFERENCES = "shared_preferences";
public static final String PREF_KEY = "inCaughtState";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
/*SKIPPING THE VIEW SETUP*/
/*SKIPPING BUTTON VIEW ATTRIBUTES*/
//variables required for changing button state
pokemonName = (String) nameTextView.getText();
caught = false;
//Loading in sharedPreferences
sharedPreferences =
getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
pokemonCaught = sharedPreferences.getStringSet(PREF_KEY, new HashSet<String>());
if (pokemonCaught.contains(pokemonName)) {
toggleCatch(catchButton);
}
}
public void toggleCatch (View view) {
//Editing and updating preferences
sharedPreferences =
getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
if (caught == true) {
/*SKIPPING BUTTON ATTRIBUTES*/
caught = false;
pokemonCaught.remove(pokemonName);
}
else {
/*SKIPPING BUTTON ATTRIBUTES*/
caught = true;
pokemonCaught.add(pokemonName);
}
editor.clear(); //This is my hacky solution...
editor.putStringSet(PREF_KEY, pokemonCaught);
editor.apply();
}
}
Try to use SharedPreferences this way:
To save data
SharedPreferences.Editor editor = getSharedPreferences("PREFS", MODE_PRIVATE).edit();
editor.putString("stringName", "stringValue");
editor.apply();
To retrieve data
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PREFS", MODE_PRIVATE);
String name = preferences.getString("stringName", "none"));
Note that this "none" is in case to string "stringName" be null.

Shared Preferences is not working, android?

The following method was working, but now it is not writing my integer into file.
public void writeChpNum(int num) {
SharedPreferences prefs = context.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
prefs.edit().putInt("chapter", num).apply();
}
and this is how I get from Main class:
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
chapterNum = prefs.getInt("chapter", 1);
Method did not work in this situation:
writeChpNum(1);
writeLastLine("0");
boolean deleted = file.delete();
boolean deleted2 = file2.delete();
boolean deleted3 = file3.delete();
boolean deleted4 = last.delete();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
Here, I want to restart everything and exit, so I am removing files, but for chapters I just have to write "1"-chapter. However, it did not write.
Is this because I am exiting the app?
Context object will not be available in other Activities when you access it like that. Try passing it context in method as well if you want to write this method to only one class. make method static so you don't need to create activity object.
Edit
Based on your new code for exiting app you need commit() instead of apply()
Ref: https://developer.android.com/reference/android/content/SharedPreferences.Editor.html#apply()
public static void writeChpNum(Context c, int num) {
SharedPreferences prefs = c.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
prefs.edit().putInt("chapter", num).commit() ;
}

Shared Preferences not persistent after app restart

I found all answers here and tried all solutions, still my shared prefs are not persistent.
Here's my code:
public static void setActivated(boolean activated) {
SharedPreferences sp = Utils.getContext().getSharedPreferences(
USER_PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean(ASD, activated);
editor.commit();
}
public static boolean isActivated() {
SharedPreferences sp = Utils.getContext().getSharedPreferences(USER_PREFS, Context.MODE_PRIVATE);
return sp.getBoolean(ASD, true);
}
I've tried also:
editor.clear();
editor.put ..
editor.commit();
I've also tried with
editor.apply();
I even tried with both .apply() and .commit() and no luck.
Another idea was to try using a different mode for the files:
...getSharedPreferences(USER_PREFS, Context.MODE_MULTI_PROCESS);
The problem is that the values saved are not persistent. If I close the app and then re-open it the values are all wrong.
Does anyone have any ideas? I would also mention that the problem is only on some devices, for example HTC One S, Samsung Galaxy S3 (I tested on a different S3 and it worked perfectly).
EDIT: I call the save on a button click listener and I call isActivated when I load the fragment (after onViewCreated()).
Thanks!
Hi I think it should work. If clearing does not work, you could try the second option as detailed in my solution:
You have 2 options:
Get shared preference value during the life-cycle of the activity.
Call .clear before .commit
See my answer:
Android Persistent Checkable Menu in Custom Widget After Reboot Android
public abstract SharedPreferences.Editor clear()
Added in API level 1 Mark in the editor to remove all values from the
preferences. Once commit is called, the only remaining preferences
will be any that you have defined in this editor. Note that when
committing back to the preferences, the clear is done first,
regardless of whether you called clear before or after put methods on
this editor.
Returns Returns a reference to the same Editor object, so you can
chain put calls together.
In my user preferences class I was getting a null value on some other strings and my code was something like this:
SharedPreferences sp = Utils.getContext()
.getSharedPreferences(USER_PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
if (session != null && !"".equals(session)) {
sessionId = session;
editor.putString(SESSION, sessionId).commit();
} else {
sessionId = null;
editor.clear().commit();
}
The editor.clear() was resetting all my other commits!
I don't know why, but it is working by just putting your prefs code inside the async task:
prefss = getSharedPreferences(ACCOUNT_PREFS_NAME, MODE_MULTI_PROCESS);
new AsyncSave(favNamesList).execute();
private static class AsyncSave extends AsyncTask<Void, Void, Boolean> {
String favNamesList;
AsyncSave(String favNamesList) {
this.favNamesList = favNamesList;
}
#Override
protected Boolean doInBackground(Void... params) {
prefss.edit().putString("favNamesList", strings).apply();
return null;
}
}

How do I set up a global variable to share among views in Android?

In one of my views the user makes a selection. I want to store that selection in a variable I can use across all views so it can be used for further database queries such as "bookId".
How can I make "bookId" a global variable that is set on one view and can be accessed across the other views when needed?
----- Edit: What I'm attempting to do based on comments and answers -----
On my main activity where the SharedPreference is stored I have this before the onCreate:
public static final String PREFS_NAME = "myPrefs";
SharedPreferences settings;
Integer bookId;
In my onCreate I've done this:
settings = getSharedPreferences(PREFS_NAME, 0);
bookId = settings.getInt("bookId", 0);
After the button press I'm storing a custom attribute and attempting to set bookId in the SharedPreference:
SharedPreferences.Editor editor = settings.edit();
editor.putInt("bookId",bookKey);
editor.commit();
In another view I'm attempting to get the bookId from the SharedPreference and, for testing purposes, I'm trying to set the stored value to a textView just to make sure it stored and carried over correctly.
Before the onCreate on the second view:
public static final String PREFS_NAME = "myPrefs";
SharedPreferences settings;
Inside the onCreate:
settings = getSharedPreferences(PREFS_NAME, 0);
Integer bookId = settings.getInt("bookId", (Integer) null);
tempBookTextView = (TextView) findViewById(R.id.tempBookTextView);
tempBookTextView.setText(bookId);
I have a two questions, how does this look so far? Any ideas why the app crashes when I use
Integer bookId = settings.getInt("bookId", (Integer) null);
Instead of using global variable to access variable value through out the app try using SharedPreferences.
sample activity:
public class Book extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
String mBookId = null;
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
mBookId = settings.getString("book_id", null);
// use book_id;
}
#Override
protected void onStop(){
super.onStop();
// 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.putString("book_id", mBookId);
// Commit the edits!
editor.commit();
}
}
Preferences are typically created private and can be accessed via all over the application components. Sharing data with other application with world readable or writable preference file is rarely used, as the external component would need to know the exact filename and location of the file.
To kill the spirit of encapsulation,
public class Globals {
public static int x;
public static int y;
}
and later
if (Globals.x == 0) { ... }
But please don't do exactly that, any class can contain static variables, find a class responsible for the value you want to store.
OTOH, android processes may be restarted when you don't expect it, in which case all the variables will be reset. So it's better to use shared preferences and if they don't work as expected (which I have seen in at least one release of Android), store the instance of shared preferences in a static variable.
You can use Shared Preferences
Saved at once !
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(ProjectAct.this).edit();
editor.putInteger(StaticVariable.BOOKID, "1");
p.get("contract_no"));
editor.commit();
Then call from anywhere like that
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
int book_id = prefs.getInteger(StaticVariable.BOOKID,null);
See more at How to use SharedPreferences in Android to store, fetch and edit values

Android initialization with SharedPreferences

I have a problem with SharedPrefences and initializations.
My application has a login where you insert an user, and for that user, you have a specific preferences... so, I need to save preferences according to the user to load it later.
I though that SharedPrefences would be the solution, and it really is I think, but I have a problem to initialize they: I have an Activity class called Options. It has static functions that returns the value of the options... but I have a problem, I call that functions before I have create that activity (intent), so I think that the functions are returning the last value that the last user has selected on the options...
How can I load the options before that calls?
I though to use first of all an Intent sending extra data with the user and in onCreate() of the Options, initialize they, but if I make an intent, then the Options will appear (xml will load).
Any help pls?
Try something like this.... adding methods for each variable you want to save.
public class PreferenceManager {
private static PreferenceManager self;
private SharedPreferences preferences = null;
private SharedPreferences.Editor editor = null;
private boolean isInitialised = false;
private static final String MY_PREFERENCE = "mypreferencekey";
private String myPreference = null;
public void initialise(Context context) {
if (!isInitialised) {
preferences = context.getSharedPreferences("MyPreferencePlace", Context.MODE_PRIVATE);
editor = preferences.edit();
loadPreferences();
isInitialised = true;
}
}
public static PreferenceManager getInstance() {
if (self == null) {
self = new PreferenceManager();
}
return self;
}
private PreferenceManager() {
}
public void setPreference(String newPreferenceValue) {
this.myPreference = newPreferenceValue;
savePreferences();
}
public String getPreference(){
return myPreference;
}
private void savePreferences() {
editor.putString(MY_PREFERENCE, myPreference);
editor.commit();
}
private void loadPreferences() {
myPreference = preferences.getString(MY_PREFERENCE, null);
}
}
All the SharedPreferences need is a context and it can be initialized. As your application always opens an Activity to start with, you always have a context to work with.
I would advise you to wrap the SharedPreferences in a Singleton class and just pass a context as parameter at the getInstance method. You should be able to access your shared preferences at all Activities this way.
I work on the dependency injector for android, and content of shared preferences is already injectable into annotated fields ( see: https://github.com/ko5tik/andject , PreferenceInjector). Patches and improvements are welcome. Saving of preferences comes soon

Categories

Resources