How To Load SharedPreferences - android

I want to load the user preferences when I start the application. The preferences are correctly stored, because when I start the PreferenceActivity from the main activity it will load the saved value. The problem is that in the main activity I'm not able to load the preferences with this method:
private void updateFromPreferences() {
Context context = getApplicationContext();
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
depAdd = prefs.getString(Preferences.PREF_DEP_ADD, "");
arrAdd = prefs.getString(Preferences.PREF_ARR_ADD, "");
}
Is there something wrong?

Use a public static final String so you will always access the right/same file
public static final String PREFS_FILE = "MyPrefs";
Create new SharedPreferences object
SharedPreferences sharedpreferences = getSharedPreferences(PREFS_FILE, 0);
Get whatever value you want from the preferences file
depAdd = sharedpreferences.getString(Preferences.PREF_DEP_ADD, "");

The problem was in depAdd and arrAdd that were not initializate.

Related

Not able to clear shred preferences

This is in my main activity class, I can pass and retrieve data in my other class through shared preferences but I cant clear the shared preferences in my other class. Also tell me how to check that my shared preferences are cleared.
SharedPreferences sharedPreferences;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "userKey";
public static final String Pass = "passKey";
sharedPreferences=getApplicationContext().getSharedPreferences(MyPREFERENCES,MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Name,userName);
editor.putString(Pass,password);
editor.commit();
this is in my other class
SharedPreferences sharedPreferences;
sharedPreferences=getApplicationContext().getSharedPreferences(SignUPActivity.MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
editor.commit();
Hi if you want just pass value from one Activity to Another or One Fragment to other than I suggest you to use INTENT to pass data
Look at this example how to pass -http://startandroid.ru/en/lessons/241-lesson-28-extras-passing-data-using-intent.html
Also -https://stackoverflow.com/a/30166602/4741746
sharedPreferences is used when data used for all activity which is permanatly stored in application you also can clear data
Remove given String from shearedPrefrance
public static void removeFromSharedPreferences(Context mContext, String key) {
if (mContext != null) {
SharedPreferences mSharedPreferences = mContext.getSharedPreferences(Constants.SHARED_PREFERENCES_NAME, 0);
if (mSharedPreferences != null)
mSharedPreferences.edit().remove(key).commit();
}
}
Remove All value from SharedPrefrance
public static void removeSharedPreferences(Context mContext) {
if (mContext != null) {
SharedPreferences preferences = mContext.getSharedPreferences("PREFERENCE", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
}
}
And why your code is not working is you have to passs Context.MODE_PRIVATE insted MODE_PRIVATE jsut confirm both should have same value
Put this code in both the classes
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(context);
Possible Reason is you are not using the same preferences.
In your first activity you are using:
sharedPreferences = getApplicationContext()
.getSharedPreferences(MyPREFERENCES,MODE_PRIVATE);
And in the other activity you should also use it.
Try to read these
http://developer.android.com/reference/android/app/Activity.html
also from the docs
Retrieve a SharedPreferences object for accessing preferences that are
private to this activity. This simply calls the underlying
getSharedPreferences(String, int) method by passing in this activity's
class name as the preferences name.

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

How to use Shared Preferences?

I am new to android..and I'm developing an application using Json. I want to pass a string value from my main activity to another class without starting the activity class. I heard there is some way using shared preferences. I just tried.. but didn't worked..i got null point exception.. here is my code...
confirm = check.AuthenticateUser(name, passwd);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name",confirm);
editor.commit();
here is the place i want to send the value of "confirm" (string variable)
and below code shows where i want to get that preference..actually that class named "ShortList".
here is the code where i trying to get the value
public class ShortList extends Activity {
//ArrayList<HashMap<String, String>> arl;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String cargivr = preferences.getString("Name","");
please some one help me..
public static String CREDENTIALS_FILENAME = "com.myapp.credentials";
public static String PIN = "pin";
public static void writeCredentials(Context c,String pin) {
SharedPreferences credentialsPref = c.getSharedPreferences(CREDENTIALS_FILENAME, 0);
SharedPreferences.Editor editor = credentialsPref.edit();
editor.putString(PIN, pin);
editor.commit();
}
public static String readCredentials(Context c,String pin) {
SharedPreferences credentialsPref = c.getSharedPreferences(CREDENTIALS_FILENAME, 0);
SharedPreferences.Editor editor = credentialsPref.edit();
return credentialsPref.getString(PIN, "default value");
}
MainActivity.java
SharedPreferences pref = getApplicationContext().getSharedPreferences("New",Context.MODE_PRIVATE);
Editor edit = pref.edit();
edit.putString("SomeKey", "SomeValue");
edit.commit();
SecondActivity.java
SharedPreferences prefs = getApplicationContext().getSharedPreferences("New",Context.MODE_PRIVATE);
String value = prefs.getString("SomeKey","DefaultValue");
Also make sure that you have added the second activity details in your android manifest file -
<activity
android:name="com.example.projectName.SecondActivity"
android:parentActivityName="com.example.sharedpref.MainActivity">
</activity>
public class ShortList extends Activity {
//ArrayList<HashMap<String, String>> arl;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String cargivr = preferences.getString("Name","");
Here it seems you're initializing member variables.
You cannot use an Activity as a Context until onCreate() in the activity lifecycle. Member variable initialization is too early and will usually lead to NPE in getBaseContext().
Move the initialization of preferences and cargivr to onCreate() or later.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ShortList.this);
String cargivr = preferences.getString("Name","");

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

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

Categories

Resources