Android initialization with SharedPreferences - android

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

Related

How can i use SharedPreferences information register activity to login activity?

My project has 3 activities, login, register, and profile...so I want to take register information to login by SharedPreferences..how can I do this?
Save data to sharedpreferences
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putString("identifier", data)
.apply();
To retrieve data
PreferenceManager.getDefaultSharedPreferences(context).getString("identifier", "default_value");
Note that you can store and retrieve different data types, I showed an example using String, but int, double and others work similarly.
you can use this class for saving you preference for entire app,
public class AppSharedPreferences {
public static final String TAG = "AppSharedPreferences";
private static SharedPreferences sharedPref;
private String demo_string = "demo string's key"
public AppSharedPreferences() {
}
public static void init(Context context)
{
if(sharedPref == null)
sharedPref = context.getSharedPreferences(
context.getPackageName(), Activity.MODE_PRIVATE);
}
public static void setDemoString(String demoString) {
Editor prefs = sharedPref.edit();
prefs.putString(demo_string, demoString);
prefs.apply();
}
public static String getDemoString() {
return sharedPref.getString(demo_string, "");
}}
Put this wherever u want to use shared prefs:
AppSharedPreferences.init(this);
You can exchange this for activity or context, depending on where you use the code.
To set value in preference, use this code:
AppSharedPreferences.setDemoString("Some Text");
To get the value from preference:
String text = AppSharedPreferences.getDemoString();

Shared Preferences not getting right Default Value

I made one class with name session and i maintain my all shared preferences from there only like..
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
}
Now from UI application i call this session and my all variable didnt get there default value like..
public void setIsFirsTimeCall(boolean IsFirsTimeCall) {
prefs.edit().putBoolean("IsFirsTimeCall", IsFirsTimeCall).commit();
prefsCommit();
}
public boolean getIsFirsTimeCall() {
return prefs.getBoolean("IsFirsTimeCall", true);
}
so when i call for getIsFirsTimeCall() then it will give false to me
I don't know why it is doing this
But when i copy and share this project to other PC then its work fine
Have you ever seem this type of behavior
I don't know if this can help you to solve:
I think you can do something like this:
public static void setIsFirsTimeCall(Context cntx, boolean IsFirsTimeCall) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
prefs.edit().putBoolean("IsFirsTimeCall", IsFirsTimeCall).commit();
prefsCommit();
}
public static boolean getIsFirsTimeCall(Context cntx) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
return prefs.getBoolean("IsFirsTimeCall", true);
}
I've moved the declaration and definition of prefs from the constructor of Session class, inside each method that require it. Each of this methods is static, so you can call them from outside the Session class in this way: Session.getIsFirsTimeCall(yourContext) and so on.
Maybe you have to change the behavior of your code because I don't know if your method prefsCommit() can become static, otherwise you can't call it from a static method.
Hope it will help you

Retrieving SharedPreferences Data Failure

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.

Static SharedPref gives uninitialized value in Broadcast Receiver

I've kept a static shared preference to access the values from multiple activities.
Now, I've set an alarm to go off at a certain time. Now in that Broadcast Receiver, I'm trying to access the shared pref variable.
It has already been initialized in another activity and returns the proper value there.
But in this Broadcast Receiver it doesn't give the actual value. It gives the uninitialized value.
Since it is static shouldn't the value remain same?
Here is the shared preference class.
package com.footballalarm.invincibles;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
public class SessionManagement {
// Shared Preferences
public static SharedPreferences pref;
// Editor for Shared preferences
public static Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Shared pref file name
private static final String PREF_NAME = "invincibles_alarm";
// All Shared Preferences Key
public static final String PREF_MATCH = "match";
// Constructor
public SessionManagement(Context context){
this._context = context;
pref = _context.getSharedPreferences(getPrefName(), PRIVATE_MODE);
editor = pref.edit();
editor.commit();
Log.e("Pref Match Value-constructor for pref", getValueMatch());
}
public static void fillValues(String match){
try{// Storing login value as TRUE
editor.putString(PREF_MATCH, match);
// commit changes
editor.commit();
Log.e("Pref Match Value-in fill values", getValueMatch());
}
catch(Exception e)
{Log.e("fillValues", e.toString());}
}
public static String getValueMatch(){
return pref.getString(PREF_MATCH, "Loading Match");
}
public static String getPrefName() {
return PREF_NAME;
}
}
I tried to log the output in other activities and it returns properly.
When I run the app and then close it before the alarm takes place, the program crashes with null-pointer exception since the Broadcast Receiver cannot access the shared pref.
I have tried this solution - SharedPreferences in BroadcastReceiver seems to not update? but I'm only using name in the manifest for the recievers.
This only happens if I close my app in ICS via the minimize menu.
Check this link:
Static variable loses value
Maybe static variables are loosing its value in your case .
static variables can loose value in the following cases:
1) Class is unloaded.
2) JVM shuts down.
3) The process dies.
Instead of using static variables and functions , try using a public class instead.
Hope it helps
EDIT 1:
Example code of using a public class for preferences instead of static methods
public class PreferenceForApp {
Context context;
SharedPreferences prefs;
public PreferenceForApp(Context context) {
this.context = context;
prefs = context.getSharedPreferences(AllConstants.PREFS_NAME, 0);
}
public Boolean getIsDeviceValidated() {
return prefs.getBoolean("Validated", false);
}
public void setIsDeviceValidated(Boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("Validated", value);
editor.commit();
}
}
In your code add:
PreferenceForApp myPref = new PreferenceForApp(contxt);
myPref.getIsDeviceValidated();
Useful related links:
Android static object lifecycle
Why are static variables considered evil?
Android : Static variable null on low memory
EDIT 2
TEST when is your static variable loosing value :
You can test this with a few lines of code:
print the uninitialized static in onCreate of your activity -> should print null
initialize the static. print it -> value would be non null
Hit the back button and go to home screen. Note: Home screen is another activity.
Launch your activity again -> the static variable will be non-null
Kill your application process from DDMS(stop button in the devices window).
Restart your activity -> the static will have null value.
I referred to this link Android static object lifecycle

How to use shared preference data in different classes in android?

Using shared preferences I saved data in one of the activity Now I want to use that data in another activity how to do that?
Create a sharedPreference where you want to add shared data. A little example of code like this:
SharedPreferences prefs = this.getSharedPreferences("CONSTANT_FILE_NAME",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("isPaid", true);
editor.commit();
And to retrieve that shared data use this code:
SharedPreferences prefs = this.getSharedPreferences("CONSTANT_FILE_NAME",
Context.MODE_PRIVATE);
prefs.getBoolean("isPaid",false);
Read this from developer site: click here
PREFS_NAME is the value you stored in shared preference.
public static final String PREFS_NAME = "MyPrefsFile";
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false)
Look at Restoring preferences
Edited:To use it among all classes i.e. setter getter method.Perfect use of OOPS.You can call the value from any class thats 1-line job
Make a normal class name as ReturningClass.
public class ReturningClass {
private static String MY_STRING_PREF = "mystringpref";
private static String MY_INT_PREF = "shareduserid";
public static SharedPreferences getPrefs(Context context) {
return context.getSharedPreferences("UserNameAcrossApplication", context.MODE_PRIVATE);
}
public static String getMyStringPref(Context context) {
return getPrefs(context).getString(MY_STRING_PREF, "default");
}
public static int getMyIntPref(Context context) {
return getPrefs(context).getInt(MY_INT_PREF, 0);
}
public static void setMyStringPref(Context context, String value) {
// perform validation etc..
getPrefs(context).edit().putString(MY_STRING_PREF, value).commit();
}
public static void setMyIntPref(Context context, int value) {
// perform validation etc..
getPrefs(context).edit().putInt(MY_INT_PREF, value).commit();
}
Set your value by calling
ReturningClass.setMyIntPref(mContext,22);
Once You have set your sharedPreference.Then just call this method.Just pass the context.from your class
int usersharedpreference=ReturningClass.getMyIntPref(mContext);
This link can help you.
Unable to use shared preference values in class A extends BroadcastReceiver , Android
also
http://saigeethamn.blogspot.in/2009/10/shared-preferences-android-developer.html
//decleration
SharedPreferences saveWord;
//onCreate
saveWord=PreferenceManager.getDefaultSharedPreferences(ActivityName.this);
String word=saveWord.getBoolean(PREFS_NAME, false);

Categories

Resources