How to use shared preference data in different classes in android? - 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);

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();

Android to-do list app with shared preferences

I have a text field for entering the to-do, a spinner where the user chooses if it's work, personal, or other and I have a date/time picker. I need to save all those using shared preferences and then populate them in a table view on the main page. I am having trouble figuring out how to save them all and send them to the different columns on the main screen.
Use the below code to save the value in SharedPreferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Editor editor = pref.edit();
editor.putString("id", "iddata");
editor.commit();
Use below code retrive value from SharedPreferences
String id=pref.getString("id", null);
first of all u need to create a java class that handles your session data and use get and set methods in order to set and get data using shared preference.
public class SessionManager
{
// LogCat tag
private static String TAG = SessionManager.class.getSimpleName();
SharedPreferences pref;
Editor editor;
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "yourprefname";
private static final String KEY_IS_NAME = "isname";
private static final String KEY_IS_DATE="isdate";
private static final String KEY_IS_TIME="istime";
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setTime(String time)
{
editor.putString(KEY_IS_TIME,time);
editor.commit();
}
public String getTime()
{
return pref.getString(KEY_IS_TIME,null);
}
}
after that u need to use sessionManager class by creating object in any activity like
SessionManager session = new SessionManager(this);
//to set the values , use set method
session.setTime(time);
//to get the values, use get method
String time=Session.getTime();

Android:implementing shared preference

I am making an app in which i have to save some string in shared preference and show it on another page means that i want to save name of user in shared preference in one activity and want to show the name of user on other activity.Any help regarding this will be appreciated.
Thanks
All you need to do is this (all the code is part of an acticity or Service (i.e. Context):
Get a SharedPreferences object:
static final String PREFS_NAME = "MyPrefs";
static final String USER_KEY = "user";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
To store a string:
String username = ...
SharedPreferences.Editor editor = settings.edit();
editor.putString(USER_KEY, username);
editor.commit();
To read:
String username = settings.getString(USER_KEY,null); // 2nd param is default value, used if prefs value is undefined
Here are more details: http://developer.android.com/guide/topics/data/data-storage.html
To achieve that first create one class, in that class you need to write all the function regarding get and set value in the sharedpreference . Please look at this below Code.
public class SaveSharedPreference
{
static final String PREF_USER_NAME= "username";
static SharedPreferences getSharedPreferences(Context ctx) {
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public static void setUserName(Context ctx, String userName)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putBoolean(PREF_USER_NAME, userName);
editor.commit();
}
public static boolean getUserName(Context ctx)
{
return getSharedPreferences(ctx).getString(PREF_USER_NAME, "");
}
}
Now you can first set the value of username from a prticular activity and get the value of user name from any activity.
You might wanna see this library. It's Secure and Easy to use.
https://prashantsolanki3.github.io/Secure-Pref-Manager/
Sample Code:
SecurePrefManager.with(this)
.set("user_name")
.value("LoremIpsum")
.go();

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

Static SharedPreferences

I have two methods in an activity
private void save(String tag, final boolean isChecked)
{
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(tag, isChecked);
editor.commit();
}
private boolean load(String tag) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
return sharedPreferences.getBoolean(tag, false);
}
and I wan't to make the load static for the purposes of retrieving the values of load from another static method within the same activity. However, when I try to make the load method static, I of course get an error because of a non-static reference. How can I make this work?
I tried this Accessing SharedPreferences through static methods with no luck.
Any help would be much appreciated!
You could save and load from Application-wide shared preferences instead of prefs private to the Activity:
private static boolean load(String tag) {
SharedPreferences sharedPreferences = Context.getApplicationContext().getSharedPreferences("namespace", Context.MODE_PRIVATE);
return sharedPreferences.getBoolean(tag, false);
}
If you do this, make sure you are also storing the preferences in the same way (by using Context.getApplicationContext().getSharedPreferences)

Categories

Resources