Store value to Shared Preferences in a service class FirebaseInstanceIDService - android

I'm trying to store type of user string in Shared Preferences in an Activity, but when i try to getString from Shared Preferences in a service class in this case myFirebaseInstanceIDService it keeps giving me a Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference error.
Here is where i am putting the value
btNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterTutorActivity.this, ChooseSub.class));
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
sharedPref.edit().putString("Type", "Tutor").apply();
signUpTutor();
}
});
and in myFirebaseInstanceIDService
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private FirebaseAuth mAuth = FirebaseAuth.getInstance();
private String type;
SharedPreferences sharedPref;
#Override
public void onTokenRefresh() {
super.onTokenRefresh();
if(mAuth.getCurrentUser() != null)
{
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
sendRegistrationToServer(refreshedToken);
}
}
public void sendRegistrationToServer(String refreshedToken)
{
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
type = sharedPref.getString("Type", "");
FirebaseDatabase.getInstance().getReference().child("Users").child(type).child(mAuth.getCurrentUser().getUid())
.child("tokenID").setValue(refreshedToken);
}
}
I don't really now what i'm doing wrong with the Shared Preferences?

You can store the token in Shared Preferences until you app is ready to consume it:
SharedPreferences sharedPref = getSharedPreferences( getPackageName() + "_preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.edit().putString("Type", "Tutor");
editor.commit();
signUpTutor();
You can request for the token like this:
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("Type", Context.MODE_PRIVATE);
String type = sharedPref.getString("Type", null);

I made a class to make SharedPreferences operations easy. i am sharing it here hope it will help you out.
public class PreferenceUtils {
private SharedPreferences pref;
private SharedPreferences.Editor editor;
public PreferenceUtils(Context context) {
pref = PreferenceManager.getDefaultSharedPreferences(context);
}
public void setPrefrences(String key, String value) {
editor = pref.edit();
editor.putString(key, value);
editor.apply();
}
public void setPrefrences(String key, int value) {
editor = pref.edit();
editor.putInt(key, value);
editor.apply();
}
public void setPrefrences(String key, boolean value) {
editor = pref.edit();
editor.putBoolean(key, value);
editor.apply();
}
public String getPrefrence(String key, String Default) {
return pref.getString(key, Default);
}
public int getPrefrence(String key, int Default) {
return pref.getInt(key, Default);
}
public boolean getPrefrence(String key, boolean Default) {
return pref.getBoolean(key, Default);
}
public void deletePref(String[] key) {
editor = pref.edit();
for (int i = 0; i < key.length; i++)
editor.remove(key[i]);
editor.apply();
}
public void deletePref(String key) {
editor = pref.edit();
editor.remove(key);
editor.apply();
}
}
now where ever you want to use SharedPreferences, just initialize this class there.
for Activity,
PreferenceUtils utils = new PreferenceUtils(classname.this);
for Fragment,
PreferenceUtils utils = new PreferenceUtils(getActivity());
for service,
PreferenceUtils utils = new PreferenceUtils(getApplicationContext());
now for saving values you simply have to use object of PreferenceUtils class,
for example in your case,
utils.setPrefrences("Type", "Tutor");
and you can easily get value with that object too,
utils.getPrefrence("Type", null);
Happy Coding.

Ok So i figured out my problem thanks to everyone. I created a MyApplication class that extends Application and created a getContext method. And now it works. Thank you for helping me.

While Writing data in shared preferences use commit() instead of apply()
sharedPref.edit().putString("Type", "Tutor").commit();

Related

Why isnt my SharedPreferences working? [duplicate]

Closed. This question needs to be more focused. It is not currently accepting answers.
Closed 4 years ago.
This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
I want to store a time value and need to retrieve and edit it. How can I use SharedPreferences to do this?
To obtain shared preferences, use the following method
In your activity:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
To read preferences:
String dateTimeKey = "com.example.app.datetime";
// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime());
To edit and save preferences
Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();
The android sdk's sample directory contains an example of retrieving and storing shared preferences. Its located in the:
<android-sdk-home>/samples/android-<platformversion>/ApiDemos directory
Edit==>
I noticed, it is important to write difference between commit() and apply() here as well.
commit() return true if value saved successfully otherwise false. It save values to SharedPreferences synchronously.
apply() was added in 2.3 and doesn't return any value either on success or failure. It saves values to SharedPreferences immediately but starts an asynchronous commit.
More detail is here.
To store values in shared preferences:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name","Harneet");
editor.apply();
To retrieve values from shared preferences:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name", "");
if(!name.equalsIgnoreCase(""))
{
name = name + " Sethi"; /* Edit the value here*/
}
To edit data from sharedpreference
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("text", mSaved.getText().toString());
editor.putInt("selection-start", mSaved.getSelectionStart());
editor.putInt("selection-end", mSaved.getSelectionEnd());
editor.apply();
To retrieve data from sharedpreference
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null)
{
//mSaved.setText(restoredText, TextView.BufferType.EDITABLE);
int selectionStart = prefs.getInt("selection-start", -1);
int selectionEnd = prefs.getInt("selection-end", -1);
/*if (selectionStart != -1 && selectionEnd != -1)
{
mSaved.setSelection(selectionStart, selectionEnd);
}*/
}
Edit
I took this snippet from API Demo sample. It had an EditText box there . In this context it is not required.I am commenting the same .
To Write :
SharedPreferences preferences = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Authentication_Id",userid.getText().toString());
editor.putString("Authentication_Password",password.getText().toString());
editor.putString("Authentication_Status","true");
editor.apply();
To Read :
SharedPreferences prfs = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
String Astatus = prfs.getString("Authentication_Status", "");
Easiest way:
To save:
getPreferences(MODE_PRIVATE).edit().putString("Name of variable",value).commit();
To retrieve:
your_variable = getPreferences(MODE_PRIVATE).getString("Name of variable",default value);
Singleton Shared Preferences Class. it may help for others in future.
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
public class SharedPref
{
private static SharedPreferences mSharedPref;
public static final String NAME = "NAME";
public static final String AGE = "AGE";
public static final String IS_SELECT = "IS_SELECT";
private SharedPref()
{
}
public static void init(Context context)
{
if(mSharedPref == null)
mSharedPref = context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
}
public static String read(String key, String defValue) {
return mSharedPref.getString(key, defValue);
}
public static void write(String key, String value) {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.putString(key, value);
prefsEditor.commit();
}
public static boolean read(String key, boolean defValue) {
return mSharedPref.getBoolean(key, defValue);
}
public static void write(String key, boolean value) {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.putBoolean(key, value);
prefsEditor.commit();
}
public static Integer read(String key, int defValue) {
return mSharedPref.getInt(key, defValue);
}
public static void write(String key, Integer value) {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.putInt(key, value).commit();
}
}
Simply call SharedPref.init() on MainActivity once
SharedPref.init(getApplicationContext());
To Write data
SharedPref.write(SharedPref.NAME, "XXXX");//save string in shared preference.
SharedPref.write(SharedPref.AGE, 25);//save int in shared preference.
SharedPref.write(SharedPref.IS_SELECT, true);//save boolean in shared preference.
To Read Data
String name = SharedPref.read(SharedPref.NAME, null);//read string in shared preference.
int age = SharedPref.read(SharedPref.AGE, 0);//read int in shared preference.
boolean isSelect = SharedPref.read(SharedPref.IS_SELECT, false);//read boolean in shared preference.
To store information
SharedPreferences preferences = getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("username", username.getText().toString());
editor.putString("password", password.getText().toString());
editor.putString("logged", "logged");
editor.commit();
To reset your preferences
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
If you are making a large application with other developers in your team and intend to have everything well organized without scattered code or different SharedPreferences instances, you may do something like this:
//SharedPreferences manager class
public class SharedPrefs {
//SharedPreferences file name
private static String SHARED_PREFS_FILE_NAME = "my_app_shared_prefs";
//here you can centralize all your shared prefs keys
public static String KEY_MY_SHARED_BOOLEAN = "my_shared_boolean";
public static String KEY_MY_SHARED_FOO = "my_shared_foo";
//get the SharedPreferences object instance
//create SharedPreferences file if not present
private static SharedPreferences getPrefs(Context context) {
return context.getSharedPreferences(SHARED_PREFS_FILE_NAME, Context.MODE_PRIVATE);
}
//Save Booleans
public static void savePref(Context context, String key, boolean value) {
getPrefs(context).edit().putBoolean(key, value).commit();
}
//Get Booleans
public static boolean getBoolean(Context context, String key) {
return getPrefs(context).getBoolean(key, false);
}
//Get Booleans if not found return a predefined default value
public static boolean getBoolean(Context context, String key, boolean defaultValue) {
return getPrefs(context).getBoolean(key, defaultValue);
}
//Strings
public static void save(Context context, String key, String value) {
getPrefs(context).edit().putString(key, value).commit();
}
public static String getString(Context context, String key) {
return getPrefs(context).getString(key, "");
}
public static String getString(Context context, String key, String defaultValue) {
return getPrefs(context).getString(key, defaultValue);
}
//Integers
public static void save(Context context, String key, int value) {
getPrefs(context).edit().putInt(key, value).commit();
}
public static int getInt(Context context, String key) {
return getPrefs(context).getInt(key, 0);
}
public static int getInt(Context context, String key, int defaultValue) {
return getPrefs(context).getInt(key, defaultValue);
}
//Floats
public static void save(Context context, String key, float value) {
getPrefs(context).edit().putFloat(key, value).commit();
}
public static float getFloat(Context context, String key) {
return getPrefs(context).getFloat(key, 0);
}
public static float getFloat(Context context, String key, float defaultValue) {
return getPrefs(context).getFloat(key, defaultValue);
}
//Longs
public static void save(Context context, String key, long value) {
getPrefs(context).edit().putLong(key, value).commit();
}
public static long getLong(Context context, String key) {
return getPrefs(context).getLong(key, 0);
}
public static long getLong(Context context, String key, long defaultValue) {
return getPrefs(context).getLong(key, defaultValue);
}
//StringSets
public static void save(Context context, String key, Set<String> value) {
getPrefs(context).edit().putStringSet(key, value).commit();
}
public static Set<String> getStringSet(Context context, String key) {
return getPrefs(context).getStringSet(key, null);
}
public static Set<String> getStringSet(Context context, String key, Set<String> defaultValue) {
return getPrefs(context).getStringSet(key, defaultValue);
}
}
In your activity you may save SharedPreferences this way
//saving a boolean into prefs
SharedPrefs.savePref(this, SharedPrefs.KEY_MY_SHARED_BOOLEAN, booleanVar);
and you may retrieve your SharedPreferences this way
//getting a boolean from prefs
booleanVar = SharedPrefs.getBoolean(this, SharedPrefs.KEY_MY_SHARED_BOOLEAN);
In any application, there are default preferences that can accessed through the PreferenceManager instance and its related method getDefaultSharedPreferences(Context) .
With the SharedPreference instance one can retrieve the int value of the any preference with the getInt(String key, int defVal). The preference we are interested in this case is counter .
In our case, we can modify the SharedPreference instance in our case using the edit() and use the putInt(String key, int newVal) We increased the count for our application that presist beyond the application and displayed accordingly.
To further demo this, restart and you application again, you will notice that the count will increase each time you restart the application.
PreferencesDemo.java
Code:
package org.example.preferences;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.TextView;
public class PreferencesDemo extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the app's shared preferences
SharedPreferences app_preferences =
PreferenceManager.getDefaultSharedPreferences(this);
// Get the value for the run counter
int counter = app_preferences.getInt("counter", 0);
// Update the TextView
TextView text = (TextView) findViewById(R.id.text);
text.setText("This app has been started " + counter + " times.");
// Increment the counter
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("counter", ++counter);
editor.commit(); // Very important
}
}
main.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
</LinearLayout>
To store values in shared preferences:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Name","Jayesh");
editor.commit();
To retrieve values from shared preferences:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString("Name", ""); // Second parameter is the default value.
Simple solution of how to store login value in by SharedPreferences.
You can extend the MainActivity class or other class where you will store the "value of something you want to keep". Put this into writer and reader classes:
public static final String GAME_PREFERENCES_LOGIN = "Login";
Here InputClass is input and OutputClass is output class, respectively.
// This is a storage, put this in a class which you can extend or in both classes:
//(input and output)
public static final String GAME_PREFERENCES_LOGIN = "Login";
// String from the text input (can be from anywhere)
String login = inputLogin.getText().toString();
// then to add a value in InputCalss "SAVE",
SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0);
Editor editor = example.edit();
editor.putString("value", login);
editor.commit();
Now you can use it somewhere else, like other class. The following is OutputClass.
SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0);
String userString = example.getString("value", "defValue");
// the following will print it out in console
Logger.getLogger("Name of a OutputClass".class.getName()).log(Level.INFO, userString);
Store in SharedPreferences
SharedPreferences preferences = getSharedPreferences("temp", getApplicationContext().MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putString("name", name);
editor.commit();
Fetch in SharedPreferences
SharedPreferences preferences=getSharedPreferences("temp", getApplicationContext().MODE_PRIVATE);
String name=preferences.getString("name",null);
Note: "temp" is sharedpreferences name and "name" is input value. if value does't exit then return null
Edit
SharedPreferences pref = getSharedPreferences("YourPref", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("yourValue", value);
editor.commit();
Read
SharedPreferences pref = getSharedPreferences("YourPref", MODE_PRIVATE);
value= pref.getString("yourValue", "");
editor.putString("text", mSaved.getText().toString());
Here, mSaved can be any TextView or EditText from where we can extract a string. you can simply specify a string. Here text will be the key which hold the value obtained from the mSaved (TextView or EditText).
SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
Also there is no need to save the preference file using the package name i.e., "com.example.app". You can mention your own preferred name. Hope this helps !
Basic idea of SharedPreferences is to store things on XML file.
Declare your xml file path.(if you don't have this file, Android will create it. If you have this file, Android will access it.)
SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
Write value to Shared Preferences
prefs.edit().putLong("preference_file_key", 1010101).apply();
the preference_file_key is the name of shared preference files. And the 1010101 is the value you need to store.
apply() at last is to save the changes. If you get error from apply(), change it to commit(). So this alternative sentence is
prefs.edit().putLong("preference_file_key", 1010101).commit();
Read from Shared Preferences
SharedPreferences sp = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
long lsp = sp.getLong("preference_file_key", -1);
lsp will be -1 if preference_file_key has no value. If 'preference_file_key' has a value, it will return the value of this.
The whole code for writing is
SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE); // Declare xml file
prefs.edit().putLong("preference_file_key", 1010101).apply(); // Write the value to key.
The code for reading is
SharedPreferences sf = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE); // Declare xml file
long lsp = sp.getLong("preference_file_key", -1); // Read the key and store in lsp
You can save value using this method:
public void savePreferencesForReasonCode(Context context,
String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
And using this method you can get value from SharedPreferences:
public String getPreferences(Context context, String prefKey) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
return sharedPreferences.getString(prefKey, "");
}
Here prefKey is the key that you used to saved the specific value. Thanks.
to save
PreferenceManager.getDefaultSharedPreferences(this).edit().putString("VarName","your value").apply();
to retreive :
String name = PreferenceManager.getDefaultSharedPreferences(this).getString("VarName","defaultValue");
default value is : Values to return if this preference does not exist.
you can change "this" with getActivity() or getApplicationContext() in
some cases
There are many ways people recommend how to use SharedPreferences. I have made a demo project here. Key point in sample is to use ApplicationContext & single sharedpreferences object. This demonstrates how to use SharedPreferences with following features:-
Using singelton class to access/update SharedPreferences
No need to pass context always for read/write SharedPreferences
It uses apply() instead of commit()
apply() is asynchronus save, doesn't return anything, it update value in memory first & changes are written to disk later
asynchronusly.
commit() is synchronus save, it return true/false based on outcome. Changes are written to disk synchronusly
works on android 2.3+ versions
Usage example as below:-
MyAppPreference.getInstance().setSampleStringKey("some_value");
String value= MyAppPreference.getInstance().getSampleStringKey();
Get source code here
& Detailed API's can be found here on developer.android.com
Best practice ever
Create Interface named with PreferenceManager:
// Interface to save values in shared preferences and also for retrieve values from shared preferences
public interface PreferenceManager {
SharedPreferences getPreferences();
Editor editPreferences();
void setString(String key, String value);
String getString(String key);
void setBoolean(String key, boolean value);
boolean getBoolean(String key);
void setInteger(String key, int value);
int getInteger(String key);
void setFloat(String key, float value);
float getFloat(String key);
}
How to use with Activity / Fragment:
public class HomeActivity extends AppCompatActivity implements PreferenceManager{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout_activity_home);
}
#Override
public SharedPreferences getPreferences(){
return getSharedPreferences("SP_TITLE", Context.MODE_PRIVATE);
}
#Override
public SharedPreferences.Editor editPreferences(){
return getPreferences().edit();
}
#Override
public void setString(String key, String value) {
editPreferences().putString(key, value).commit();
}
#Override
public String getString(String key) {
return getPreferences().getString(key, "");
}
#Override
public void setBoolean(String key, boolean value) {
editPreferences().putBoolean(key, value).commit();
}
#Override
public boolean getBoolean(String key) {
return getPreferences().getBoolean(key, false);
}
#Override
public void setInteger(String key, int value) {
editPreferences().putInt(key, value).commit();
}
#Override
public int getInteger(String key) {
return getPreferences().getInt(key, 0);
}
#Override
public void setFloat(String key, float value) {
editPreferences().putFloat(key, value).commit();
}
#Override
public float getFloat(String key) {
return getPreferences().getFloat(key, 0);
}
}
Note: Replace your key of SharedPreference with SP_TITLE.
Examples:
Store string in shareperence:
setString("my_key", "my_value");
Get string from shareperence:
String strValue = getString("my_key");
Hope this will help you.
I write a helper class for sharedpreferences:
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by mete_ on 23.12.2016.
*/
public class HelperSharedPref {
Context mContext;
public HelperSharedPref(Context mContext) {
this.mContext = mContext;
}
/**
*
* #param key Constant RC
* #param value Only String, Integer, Long, Float, Boolean types
*/
public void saveToSharedPref(String key, Object value) throws Exception {
SharedPreferences.Editor editor = mContext.getSharedPreferences(key, Context.MODE_PRIVATE).edit();
if (value instanceof String) {
editor.putString(key, (String) value);
} else if (value instanceof Integer) {
editor.putInt(key, (Integer) value);
} else if (value instanceof Long) {
editor.putLong(key, (Long) value);
} else if (value instanceof Float) {
editor.putFloat(key, (Float) value);
} else if (value instanceof Boolean) {
editor.putBoolean(key, (Boolean) value);
} else {
throw new Exception("Unacceptable object type");
}
editor.commit();
}
/**
* Return String
* #param key
* #return null default is null
*/
public String loadStringFromSharedPref(String key) throws Exception {
SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
String restoredText = prefs.getString(key, null);
return restoredText;
}
/**
* Return int
* #param key
* #return null default is -1
*/
public Integer loadIntegerFromSharedPref(String key) throws Exception {
SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
Integer restoredText = prefs.getInt(key, -1);
return restoredText;
}
/**
* Return float
* #param key
* #return null default is -1
*/
public Float loadFloatFromSharedPref(String key) throws Exception {
SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
Float restoredText = prefs.getFloat(key, -1);
return restoredText;
}
/**
* Return long
* #param key
* #return null default is -1
*/
public Long loadLongFromSharedPref(String key) throws Exception {
SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
Long restoredText = prefs.getLong(key, -1);
return restoredText;
}
/**
* Return boolean
* #param key
* #return null default is false
*/
public Boolean loadBooleanFromSharedPref(String key) throws Exception {
SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
Boolean restoredText = prefs.getBoolean(key, false);
return restoredText;
}
}
To store values in shared preferences:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Name","Jayesh");
editor.commit();
To retrieve values from shared preferences:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString("Name", "");
Use used this example simple and clear and checked
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
public class MainActivity extends AppCompatActivity {
EditText ed1,ed2,ed3;
Button b1;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
public static final String Email = "emailKey";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);
b1=(Button)findViewById(R.id.button);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String n = ed1.getText().toString();
String ph = ed2.getText().toString();
String e = ed3.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.commit();
Toast.makeText(MainActivity.this,"Thanks",Toast.LENGTH_LONG).show();
}
});
}
}
Using this simple library, here is how you make the calls to SharedPreferences..
TinyDB tinydb = new TinyDB(context);
tinydb.putInt("clickCount", 2);
tinydb.putString("userName", "john");
tinydb.putBoolean("isUserMale", true);
tinydb.putList("MyUsers", mUsersArray);
tinydb.putImagePNG("DropBox/WorkImages", "MeAtlunch.png", lunchBitmap);
//These plus the corresponding get methods are all Included
I wanted to add here that most of the snippets for this question will have something like MODE_PRIVATE when using SharedPreferences. Well, MODE_PRIVATE means that whatever you write into this shared preference can only be read by your application only.
Whatever key you pass to getSharedPreferences() method, android creates a file with that name and stores the preference data into it.
Also remember that getSharedPreferences() is supposed to be used when you intend to have multiple preference files for your application. If you intend to use single preference file and store all key-value pairs into it then use the getSharedPreference() method. Its weird why everyone (including myself) simply uses getSharedPreferences() flavor without even understanding the difference between the above two.
The following video tutorial should help
https://www.youtube.com/watch?v=2PcAQ1NBy98
Simple and hassle-free :: "Android-SharedPreferences-Helper" library
Better late than never: I created the "Android-SharedPreferences-Helper" library to help reduce the complexity and effort of using SharedPreferences. It also provides some extended functionality. Few things that it offers are as follows:
One line initialization and setup
Easily selecting whether to use default preferences or a custom preference file
Predefined (data type defaults) and customizable (what you may choose) default values for each datatype
Ability to set different default value for single use with just an additional param
You can register and unregister OnSharedPreferenceChangeListener as you do for default class
dependencies {
...
...
compile(group: 'com.viralypatel.sharedpreferenceshelper', name: 'library', version: '1.1.0', ext: 'aar')
}
Declaration of SharedPreferencesHelper object: (recommended at class
level)
SharedPreferencesHelper sph;
Instantiation of the SharedPreferencesHelper object: (recommended in
onCreate() method)
// use one of the following ways to instantiate
sph = new SharedPreferencesHelper(this); //this will use default shared preferences
sph = new SharedPreferencesHelper(this, "myappprefs"); // this will create a named shared preference file
sph = new SharedPreferencesHelper(this, "myappprefs", 0); // this will allow you to specify a mode
Putting values into shared preferences
Fairly simple! Unlike the default way (when using the SharedPreferences class) you'll NOT need to call .edit() and .commit() ever time.
sph.putBoolean("boolKey", true);
sph.putInt("intKey", 123);
sph.putString("stringKey", "string value");
sph.putLong("longKey", 456876451);
sph.putFloat("floatKey", 1.51f);
// putStringSet is supported only for android versions above HONEYCOMB
Set name = new HashSet();
name.add("Viral");
name.add("Patel");
sph.putStringSet("name", name);
That's it! Your values are stored in the shared preferences.
Getting values from shared preferences
Again, just one simple method call with the key name.
sph.getBoolean("boolKey");
sph.getInt("intKey");
sph.getString("stringKey");
sph.getLong("longKey");
sph.getFloat("floatKey");
// getStringSet is supported only for android versions above HONEYCOMB
sph.getStringSet("name");
It has a lot of other extended functionality
Check the details of extended functionality, usage and installation instructions etc on the GitHub Repository Page.
I have created a Helper class to make my Life easy. This is a generic class and has a-lot of methods those are commonly used in Apps like Shared Preferences, Email Validity, Date Time Format. Copy this class in your code and access it's methods wherever you need.
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.support.v4.app.FragmentActivity;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* Created by Zohaib Hassan on 3/4/2016.
*/
public class Helper {
private static ProgressDialog pd;
public static void saveData(String key, String value, Context context) {
SharedPreferences sp = context.getApplicationContext()
.getSharedPreferences("appData", 0);
SharedPreferences.Editor editor;
editor = sp.edit();
editor.putString(key, value);
editor.commit();
}
public static void deleteData(String key, Context context){
SharedPreferences sp = context.getApplicationContext()
.getSharedPreferences("appData", 0);
SharedPreferences.Editor editor;
editor = sp.edit();
editor.remove(key);
editor.commit();
}
public static String getSaveData(String key, Context context) {
SharedPreferences sp = context.getApplicationContext()
.getSharedPreferences("appData", 0);
String data = sp.getString(key, "");
return data;
}
public static long dateToUnix(String dt, String format) {
SimpleDateFormat formatter;
Date date = null;
long unixtime;
formatter = new SimpleDateFormat(format);
try {
date = formatter.parse(dt);
} catch (Exception ex) {
ex.printStackTrace();
}
unixtime = date.getTime();
return unixtime;
}
public static String getData(long unixTime, String formate) {
long unixSeconds = unixTime;
Date date = new Date(unixSeconds);
SimpleDateFormat sdf = new SimpleDateFormat(formate);
String formattedDate = sdf.format(date);
return formattedDate;
}
public static String getFormattedDate(String date, String currentFormat,
String desiredFormat) {
return getData(dateToUnix(date, currentFormat), desiredFormat);
}
public static double distance(double lat1, double lon1, double lat2,
double lon2, char unit) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2))
+ Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2))
* Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
if (unit == 'K') {
dist = dist * 1.609344;
} else if (unit == 'N') {
dist = dist * 0.8684;
}
return (dist);
}
/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
/* :: This function converts decimal degrees to radians : */
/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
private static double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
/* :: This function converts radians to decimal degrees : */
/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
private static double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
public static int getRendNumber() {
Random r = new Random();
return r.nextInt(360);
}
public static void hideKeyboard(Context context, EditText editText) {
InputMethodManager imm = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
public static void showLoder(Context context, String message) {
pd = new ProgressDialog(context);
pd.setCancelable(false);
pd.setMessage(message);
pd.show();
}
public static void showLoderImage(Context context, String message) {
pd = new ProgressDialog(context);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setCancelable(false);
pd.setMessage(message);
pd.show();
}
public static void dismissLoder() {
pd.dismiss();
}
public static void toast(Context context, String text) {
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}
/*
public static Boolean connection(Context context) {
ConnectionDetector connection = new ConnectionDetector(context);
if (!connection.isConnectingToInternet()) {
Helper.showAlert(context, "No Internet access...!");
//Helper.toast(context, "No internet access..!");
return false;
} else
return true;
}*/
public static void removeMapFrgment(FragmentActivity fa, int id) {
android.support.v4.app.Fragment fragment;
android.support.v4.app.FragmentManager fm;
android.support.v4.app.FragmentTransaction ft;
fm = fa.getSupportFragmentManager();
fragment = fm.findFragmentById(id);
ft = fa.getSupportFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
}
public static AlertDialog showDialog(Context context, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// TODO Auto-generated method stub
}
});
return builder.create();
}
public static void showAlert(Context context, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Alert");
builder.setMessage(message)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
}).show();
}
public static boolean isURL(String url) {
if (url == null)
return false;
boolean foundMatch = false;
try {
Pattern regex = Pattern
.compile(
"\\b(?:(https?|ftp|file)://|www\\.)?[-A-Z0-9+&#/%?=~_|$!:,.;]*[A-Z0-9+&##/%=~_|$]\\.[-A-Z0-9+&##/%?=~_|$!:,.;]*[A-Z0-9+&##/%=~_|$]",
Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher regexMatcher = regex.matcher(url);
foundMatch = regexMatcher.matches();
return foundMatch;
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
return false;
}
}
public static boolean atLeastOneChr(String string) {
if (string == null)
return false;
boolean foundMatch = false;
try {
Pattern regex = Pattern.compile("[a-zA-Z0-9]",
Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher regexMatcher = regex.matcher(string);
foundMatch = regexMatcher.matches();
return foundMatch;
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
return false;
}
}
public static boolean isValidEmail(String email, Context context) {
String expression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
return true;
} else {
// Helper.toast(context, "Email is not valid..!");
return false;
}
}
public static boolean isValidUserName(String email, Context context) {
String expression = "^[0-9a-zA-Z]+$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
return true;
} else {
Helper.toast(context, "Username is not valid..!");
return false;
}
}
public static boolean isValidDateSlash(String inDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
dateFormat.setLenient(false);
try {
dateFormat.parse(inDate.trim());
} catch (ParseException pe) {
return false;
}
return true;
}
public static boolean isValidDateDash(String inDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy");
dateFormat.setLenient(false);
try {
dateFormat.parse(inDate.trim());
} catch (ParseException pe) {
return false;
}
return true;
}
public static boolean isValidDateDot(String inDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.mm.yyyy");
dateFormat.setLenient(false);
try {
dateFormat.parse(inDate.trim());
} catch (ParseException pe) {
return false;
}
return true;
}
}
SharedPreferences.Editor editor = getSharedPreferences("identifier",
MODE_PRIVATE).edit();
//identifier is the unique to fetch data from your SharedPreference.
editor.putInt("keyword", 0);
// saved value place with 0.
//use this "keyword" to fetch saved value again.
editor.commit();//important line without this line your value is not stored in preference
// fetch the stored data using ....
SharedPreferences prefs = getSharedPreferences("identifier", MODE_PRIVATE);
// here both identifier will same
int fetchvalue = prefs.getInt("keyword", 0);
// here keyword will same as used above.
// 0 is default value when you nothing save in preference that time fetch value is 0.
you need to use SharedPreferences in AdapterClass or any other.
that time just use this declaration and use same ass above.
SharedPreferences.Editor editor = context.getSharedPreferences("idetifier",
Context.MODE_PRIVATE).edit();
SharedPreferences prefs = context.getSharedPreferences("identifier", Context.MODE_PRIVATE);
//here context is your application context
for string or boolean value
editor.putString("stringkeyword", "your string");
editor.putBoolean("booleankeyword","your boolean value");
editor.commit();
fetch data same as above
String fetchvalue = prefs.getString("keyword", "");
Boolean fetchvalue = prefs.getBoolean("keyword", "");
2.for Storing in shared prefrence
SharedPreferences.Editor editor =
getSharedPreferences("DeviceToken",MODE_PRIVATE).edit();
editor.putString("DeviceTokenkey","ABABABABABABABB12345");
editor.apply();
2.for retrieving the same use
SharedPreferences prefs = getSharedPreferences("DeviceToken",
MODE_PRIVATE);
String deviceToken = prefs.getString("DeviceTokenkey", null);
Here i have created an Helper class to use preferences in android.
This is the helper class:
public class PrefsUtil {
public static SharedPreferences getPreference() {
return PreferenceManager.getDefaultSharedPreferences(Applicatoin.getAppContext());
}
public static void putBoolean(String key, boolean value) {
getPreference().edit().putBoolean(key, value)
.apply();
}
public static boolean getBoolean(String key) {
return getPreference().getBoolean(key, false);
}
public static void putInt(String key, int value) {
getPreference().edit().putInt(key, value).apply();
}
public static void delKey(String key) {
getPreference().edit().remove(key).apply();
}
}
To store and retrieve global variables in a function way.
To test, make sure you have Textview items on your page, uncomment the two lines in the code and run. Then comment the two lines again, and run.
Here the id of the TextView is username and password.
In every Class where you want to use it, add these two routines at the end.
I would like this routine to be global routines, but do not know how. This works.
The variabels are available everywhere.
It stores the variables in "MyFile". You may change it your way.
You call it using
storeSession("username","frans");
storeSession("password","!2#4%");***
the variable username will be filled with "frans" and the password with "!2#4%". Even after a restart they are available.
and you retrieve it using
password.setText(getSession(("password")));
usernames.setText(getSession(("username")));
below the entire code of my grid.java
package nl.yentel.yenteldb2;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class Grid extends AppCompatActivity {
private TextView usernames;
private TextView password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
***// storeSession("username","frans.eilering#gmail.com");
//storeSession("password","mijn wachtwoord");***
password = (TextView) findViewById(R.id.password);
password.setText(getSession(("password")));
usernames=(TextView) findViewById(R.id.username);
usernames.setText(getSession(("username")));
}
public void storeSession(String key, String waarde) {
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyFile", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(key, waarde);
editor.commit();
}
public String getSession(String key) {
//http://androidexample.com/Android_SharedPreferences_Basics/index.php?view=article_discription&aid=126&aaid=146
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyFile", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
String output = pref.getString(key, null);
return output;
}
}
below you find the textview items
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="usernames"
android:id="#+id/username"
android:layout_below="#+id/textView"
android:layout_alignParentStart="true"
android:layout_marginTop="39dp"
android:hint="hier komt de username" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="password"
android:id="#+id/password"
android:layout_below="#+id/user"
android:layout_alignParentStart="true"
android:hint="hier komt het wachtwoord" />

Get a java.lang.ClassCastException during using SharedPreferences

I use SharedPreferences in my app to save small Integer data . But I get ClassCastException in this line .
int number = mySharedPref.getInt("numberOne",0);
Here is my code .
To store data .
mySharedPref=getSharedPreferences("MyPref",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mySharedPref.edit();
editor.putInt("numberOne",myInteger);
To get data
mySharedPref = getSharedPreferences("MyPref",Context.MODE_PRIVATE);
int number= mySharedPref.getInt("numberOne",0);
display(number);
I think the problem is that you have not committed the data stored in SharedPreferences.
So you should do a
editor.commit();
while storing the data.
Try this
To Store data
public static void setInteger(Context context, String key, Integer Value) {
sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
SharedPreferences.Editor sEdit = sharedPreferences.edit();
sEdit.putInt(key, Value);
sEdit.commit();
}
To get data
public static Integer getInteger(Context context, String key) {
sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
Integer value = sharedPreferences.getInt(key, 0);
return value;
}
You have to call commit() method to save data changes in SharedPreferences.
Here is the get data method
private void showData() {
SharedPreferences sharedPreferences = getSharedPreferences("MyFile", Context.MODE_PRIVATE);
int number = sharedPreferences.getInt("numberOne", 0);
display(number);
}
Here is get savemethod
private void saveData(int value) {
SharedPreferences sharedPreferences = getSharedPreferences("MyFile", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("numberOne", value);
editor.commit();
}

SharedPreferences always returning null

I have an ActivityA that saves an user name to a SharedPreference and an ActivityB that is attempting to access the preference. However, it always returns null
Here's my ActivityA: (using MODE_WORLD_READABLE for testing)
// I know un is not null
String un = data.getExtras().getString("username");
Log.d("un value", un);
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor editor = myPrefs.edit();
editor.putString("username", un);
editor.apply();
Here's ActivityB: (Log shows null value)
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String username = myPrefs.getString("username","");
Log.d("Username", "username from store: " + username);
After looking at many SO examples of using this class, I'm not sure what the issue is. Can anyone please help?
Check this :
This will help in maintaining separate class for preference. Use PreferencesUtil.class to deal with values.
Application extended class
public class MyApplication extends Application {
/**
* The constant mApplication.
*/
public static MyApplication mApplication;
public static final String PREFERENCE_NAME = "PREFRENCE_FILE_NAME_1.0";
public static final int PREFERENCE_MODE = 0; //private mode
#Override
public void onCreate() {
super.onCreate();
mApplication = this;
}
/**
* Gets application.
*
* #return the application
*/
public static MyApplication getApplication() {
return mApplication;
}
public static SharedPreferences getSharedPreference() {
return getApplication().getSharedPreferences(PREFERENCE_NAME, PREFERENCE_MODE);
}
}
PreferenceUtil.class
public class PreferencesUtil {
private SharedPreferences mSharedPreferences = MyApplication.getSharedPreference();
private int DEFAULT_INT= 0;
public PreferencesUtil() {
}
/**
* Shared Preference.
**/
// Save strings in preference
public void savePreferences(String key, String value) {
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
// Save boolean values in preference
public void savePreferencesBoolean(String key, boolean value) {
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
// Save boolean values in preference
public void savePreferencesLong(String key, long value) {
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putLong(key, value);
editor.commit();
}
// Save int values in preference
public void savePreferencesInt(String key, int value) {
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
// Get string values from preference
public String getPreferences(String key,String defaultValue) {
return mSharedPreferences.getString(key, defaultValue);
}
// Get boolean values from preference
public boolean getPreferencesBoolean(String key) {
return mSharedPreferences.getBoolean(key, false); //false is default value
}
// Get Long values from preference
public long getPreferencesLong(String key) {
return mSharedPreferences.getLong(key, DEFAULT_INT); //false is default value
}
// Get int values from preference
public int getPreferencesInt(String key) {
return mSharedPreferences.getInt(key, DEFAULT_INT); //false is default value
}
}
I think the issue is the MODE_WORLD_READABLE while putting data into the preference try using any other Mode Like MODE_PRIVATE
Save your preference like this.
String un = data.getExtras().getString("username");
SharedPreferences myPrefs = getSharedPreferences("myPrefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = myPrefs.edit();
editor.putString("username", un);
editor.commit();
And retrieve the preference value like this.
SharedPreferences myPrefs = getSharedPreferences("myPrefs", Activity.MODE_PRIVATE);
String username = myPrefs.getString("username","");
Log.d("Username", "username from store: " + username);

Use Shared preferences from another class in Broadcast Receiver

I am new to android. I am using a SessionHandler class where i save the username from LoginActivity in shared preferences. I want to access this username from shared preferences in a class of broadcast receiver
Here is the code for SessionHandler class.
public SharedPreferences getLoginPreferences() {
// This sample app persists the registration ID in shared preferences,
// but
// how you store the regID in your app is up to you.
return context.getSharedPreferences(
LoginActivity.class.getSimpleName(), Context.MODE_PRIVATE);
}
public void storeLoginSession(String str_Name) {
final SharedPreferences prefs = getLoginPreferences();
SharedPreferences.Editor editor = prefs.edit();
editor.putString("name", str_Name);
editor.commit();
}
I want to access this name name here in startService().
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
startService();
}
}
private void startService() {
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
strDate = sdf.format(c.getTime());
}
How can I get this value? I tried using context but not working. Can anyone please help me.
Best way to use SharedPreference is to wrap inside your custom Preference class like :
public class YourPreference {
private static YourPreference yourPreference;
private SharedPreferences sharedPreferences;
public static YourPreference getInstance(Context context) {
if (yourPreference == null) {
yourPreference = new YourPreference(context);
}
return yourPreference;
}
private YourPreference(Context context) {
sharedPreferences = context.getSharedPreferences("YourCustomNamedPreference",Context.MODE_PRIVATE);
}
public void storeLoginSession(String str_Name) {
SharedPreferences.Editor prefsEditor = sharedPreferences.edit();
editor.putString("name", str_Name);
prefsEditor.commit();
}
}
Then you can get YourPrefrence instance from any class where contet is available using
YourPreference yourPrefrence = YourPreference.getInstance(context);
yourPreference.storeLoginSession(YOUR_STRING);
You can create global functions for sharedPreferences:
public static void setSharedPrefString(Context context, String key, String value) {
SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preference.edit();
editor.putString(key, value);
editor.commit();
}
public static String getSharedPrefString(Context context, String key) {
SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(context);
if (preference != null) {
return preference.getString(key, "");
}
return "";
}
call "getSharedPrefString" from onReceive of BroadcastReceiver.
Let me know if you find it useful.
Create a class called AppPreference.class
public class AppPreference {
private SharedPreferences mSharedPreferences;
public static final String KEY_LOGIN= "KEY_LOGIN";
public AppPreference(Context context) {
super();
mSharedPreferences = context.getSharedPreferences(context.getString(R.string.app_name), Context.MODE_PRIVATE);
}
public void setLoginStatus(String value) {
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString(KEY_POSTCODE_LOGIN, value);
editor.commit();
}
public String getLoginStatus() {
return mSharedPreferences.getString(KEY_POSTCODE_LOGIN,"");
}
}
You can save in value by calling
AppPreference appPreference = new AppPreference(context);
appPreference .setLoginStatus("value you want to save");
getvalue call
AppPreference appPreference = new AppPreference(context);
appPreference .getLoginStatus();
Hi please use this sample code
public class PreferenceHandler
{
public static boolean storeNameToPrefernce(Context context,
String key, String getDetailsString) {
// TODO Auto-generated method stub
SharedPreferences mySharedPreferences;
try{
mySharedPreferences=context.getSharedPreferences(MyConstants.PREFERENCE_NAME,0);
SharedPreferences.Editor editor=mySharedPreferences.edit();
editor.putString(key,getDetailsString);
editor.commit();
}
catch(Exception e){
System.out.println(e);
return false;
}
return true;
}
public static String getNameFromPreference(Context context,String key)
{
String value;
SharedPreferences mySharedPreferences;
try{
mySharedPreferences = context.getSharedPreferences(MyConstants.PREFERENCE_NAME,0);
value = mySharedPreferences.getString(key, "NONE");
}catch(Exception e){
return "NONE";
}
return value;
}
}
Getting string from Preference class:
In SampleActvity class.
String name =PreferenceHandler.getNameFromPreference(sampleActivity.this,key);
I do it in this simply way:
main class:
public class SWP extends Activity implements LocationListener
{ ....
public static final String MY_PREFERENCES = "SWP_Preferences";
public static SharedPreferences preferencesSwp;
public static SharedPreferences.Editor preferencesEditorSwp;
...
#Override
protected void onCreate(Bundle savedInstanceState)
{ ....
preferencesSwp = getSharedPreferences(MY_PREFERENCES, Activity.MODE_PRIVATE);
preferencesEditorSwp = preferencesSwp.edit();
....
}
....
}
in any other, read
value1 = SWP.preferencesSwp.getString("PREF_value1", "init_text");
and write
SWP.preferencesEditorSwp.putString("PREF_value1", value1 );
SWP.preferencesEditorSwp.commit();

How to use SharedPreferences in Android to store, fetch and edit values [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Closed 4 years ago.
This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
I want to store a time value and need to retrieve and edit it. How can I use SharedPreferences to do this?
To obtain shared preferences, use the following method
In your activity:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
To read preferences:
String dateTimeKey = "com.example.app.datetime";
// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime());
To edit and save preferences
Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();
The android sdk's sample directory contains an example of retrieving and storing shared preferences. Its located in the:
<android-sdk-home>/samples/android-<platformversion>/ApiDemos directory
Edit==>
I noticed, it is important to write difference between commit() and apply() here as well.
commit() return true if value saved successfully otherwise false. It save values to SharedPreferences synchronously.
apply() was added in 2.3 and doesn't return any value either on success or failure. It saves values to SharedPreferences immediately but starts an asynchronous commit.
More detail is here.
To store values in shared preferences:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name","Harneet");
editor.apply();
To retrieve values from shared preferences:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name", "");
if(!name.equalsIgnoreCase(""))
{
name = name + " Sethi"; /* Edit the value here*/
}
To edit data from sharedpreference
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("text", mSaved.getText().toString());
editor.putInt("selection-start", mSaved.getSelectionStart());
editor.putInt("selection-end", mSaved.getSelectionEnd());
editor.apply();
To retrieve data from sharedpreference
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null)
{
//mSaved.setText(restoredText, TextView.BufferType.EDITABLE);
int selectionStart = prefs.getInt("selection-start", -1);
int selectionEnd = prefs.getInt("selection-end", -1);
/*if (selectionStart != -1 && selectionEnd != -1)
{
mSaved.setSelection(selectionStart, selectionEnd);
}*/
}
Edit
I took this snippet from API Demo sample. It had an EditText box there . In this context it is not required.I am commenting the same .
To Write :
SharedPreferences preferences = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Authentication_Id",userid.getText().toString());
editor.putString("Authentication_Password",password.getText().toString());
editor.putString("Authentication_Status","true");
editor.apply();
To Read :
SharedPreferences prfs = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
String Astatus = prfs.getString("Authentication_Status", "");
Easiest way:
To save:
getPreferences(MODE_PRIVATE).edit().putString("Name of variable",value).commit();
To retrieve:
your_variable = getPreferences(MODE_PRIVATE).getString("Name of variable",default value);
Singleton Shared Preferences Class. it may help for others in future.
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
public class SharedPref
{
private static SharedPreferences mSharedPref;
public static final String NAME = "NAME";
public static final String AGE = "AGE";
public static final String IS_SELECT = "IS_SELECT";
private SharedPref()
{
}
public static void init(Context context)
{
if(mSharedPref == null)
mSharedPref = context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
}
public static String read(String key, String defValue) {
return mSharedPref.getString(key, defValue);
}
public static void write(String key, String value) {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.putString(key, value);
prefsEditor.commit();
}
public static boolean read(String key, boolean defValue) {
return mSharedPref.getBoolean(key, defValue);
}
public static void write(String key, boolean value) {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.putBoolean(key, value);
prefsEditor.commit();
}
public static Integer read(String key, int defValue) {
return mSharedPref.getInt(key, defValue);
}
public static void write(String key, Integer value) {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.putInt(key, value).commit();
}
}
Simply call SharedPref.init() on MainActivity once
SharedPref.init(getApplicationContext());
To Write data
SharedPref.write(SharedPref.NAME, "XXXX");//save string in shared preference.
SharedPref.write(SharedPref.AGE, 25);//save int in shared preference.
SharedPref.write(SharedPref.IS_SELECT, true);//save boolean in shared preference.
To Read Data
String name = SharedPref.read(SharedPref.NAME, null);//read string in shared preference.
int age = SharedPref.read(SharedPref.AGE, 0);//read int in shared preference.
boolean isSelect = SharedPref.read(SharedPref.IS_SELECT, false);//read boolean in shared preference.
To store information
SharedPreferences preferences = getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("username", username.getText().toString());
editor.putString("password", password.getText().toString());
editor.putString("logged", "logged");
editor.commit();
To reset your preferences
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
If you are making a large application with other developers in your team and intend to have everything well organized without scattered code or different SharedPreferences instances, you may do something like this:
//SharedPreferences manager class
public class SharedPrefs {
//SharedPreferences file name
private static String SHARED_PREFS_FILE_NAME = "my_app_shared_prefs";
//here you can centralize all your shared prefs keys
public static String KEY_MY_SHARED_BOOLEAN = "my_shared_boolean";
public static String KEY_MY_SHARED_FOO = "my_shared_foo";
//get the SharedPreferences object instance
//create SharedPreferences file if not present
private static SharedPreferences getPrefs(Context context) {
return context.getSharedPreferences(SHARED_PREFS_FILE_NAME, Context.MODE_PRIVATE);
}
//Save Booleans
public static void savePref(Context context, String key, boolean value) {
getPrefs(context).edit().putBoolean(key, value).commit();
}
//Get Booleans
public static boolean getBoolean(Context context, String key) {
return getPrefs(context).getBoolean(key, false);
}
//Get Booleans if not found return a predefined default value
public static boolean getBoolean(Context context, String key, boolean defaultValue) {
return getPrefs(context).getBoolean(key, defaultValue);
}
//Strings
public static void save(Context context, String key, String value) {
getPrefs(context).edit().putString(key, value).commit();
}
public static String getString(Context context, String key) {
return getPrefs(context).getString(key, "");
}
public static String getString(Context context, String key, String defaultValue) {
return getPrefs(context).getString(key, defaultValue);
}
//Integers
public static void save(Context context, String key, int value) {
getPrefs(context).edit().putInt(key, value).commit();
}
public static int getInt(Context context, String key) {
return getPrefs(context).getInt(key, 0);
}
public static int getInt(Context context, String key, int defaultValue) {
return getPrefs(context).getInt(key, defaultValue);
}
//Floats
public static void save(Context context, String key, float value) {
getPrefs(context).edit().putFloat(key, value).commit();
}
public static float getFloat(Context context, String key) {
return getPrefs(context).getFloat(key, 0);
}
public static float getFloat(Context context, String key, float defaultValue) {
return getPrefs(context).getFloat(key, defaultValue);
}
//Longs
public static void save(Context context, String key, long value) {
getPrefs(context).edit().putLong(key, value).commit();
}
public static long getLong(Context context, String key) {
return getPrefs(context).getLong(key, 0);
}
public static long getLong(Context context, String key, long defaultValue) {
return getPrefs(context).getLong(key, defaultValue);
}
//StringSets
public static void save(Context context, String key, Set<String> value) {
getPrefs(context).edit().putStringSet(key, value).commit();
}
public static Set<String> getStringSet(Context context, String key) {
return getPrefs(context).getStringSet(key, null);
}
public static Set<String> getStringSet(Context context, String key, Set<String> defaultValue) {
return getPrefs(context).getStringSet(key, defaultValue);
}
}
In your activity you may save SharedPreferences this way
//saving a boolean into prefs
SharedPrefs.savePref(this, SharedPrefs.KEY_MY_SHARED_BOOLEAN, booleanVar);
and you may retrieve your SharedPreferences this way
//getting a boolean from prefs
booleanVar = SharedPrefs.getBoolean(this, SharedPrefs.KEY_MY_SHARED_BOOLEAN);
In any application, there are default preferences that can accessed through the PreferenceManager instance and its related method getDefaultSharedPreferences(Context) .
With the SharedPreference instance one can retrieve the int value of the any preference with the getInt(String key, int defVal). The preference we are interested in this case is counter .
In our case, we can modify the SharedPreference instance in our case using the edit() and use the putInt(String key, int newVal) We increased the count for our application that presist beyond the application and displayed accordingly.
To further demo this, restart and you application again, you will notice that the count will increase each time you restart the application.
PreferencesDemo.java
Code:
package org.example.preferences;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.TextView;
public class PreferencesDemo extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the app's shared preferences
SharedPreferences app_preferences =
PreferenceManager.getDefaultSharedPreferences(this);
// Get the value for the run counter
int counter = app_preferences.getInt("counter", 0);
// Update the TextView
TextView text = (TextView) findViewById(R.id.text);
text.setText("This app has been started " + counter + " times.");
// Increment the counter
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("counter", ++counter);
editor.commit(); // Very important
}
}
main.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
</LinearLayout>
To store values in shared preferences:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Name","Jayesh");
editor.commit();
To retrieve values from shared preferences:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString("Name", ""); // Second parameter is the default value.
Simple solution of how to store login value in by SharedPreferences.
You can extend the MainActivity class or other class where you will store the "value of something you want to keep". Put this into writer and reader classes:
public static final String GAME_PREFERENCES_LOGIN = "Login";
Here InputClass is input and OutputClass is output class, respectively.
// This is a storage, put this in a class which you can extend or in both classes:
//(input and output)
public static final String GAME_PREFERENCES_LOGIN = "Login";
// String from the text input (can be from anywhere)
String login = inputLogin.getText().toString();
// then to add a value in InputCalss "SAVE",
SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0);
Editor editor = example.edit();
editor.putString("value", login);
editor.commit();
Now you can use it somewhere else, like other class. The following is OutputClass.
SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0);
String userString = example.getString("value", "defValue");
// the following will print it out in console
Logger.getLogger("Name of a OutputClass".class.getName()).log(Level.INFO, userString);
Store in SharedPreferences
SharedPreferences preferences = getSharedPreferences("temp", getApplicationContext().MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putString("name", name);
editor.commit();
Fetch in SharedPreferences
SharedPreferences preferences=getSharedPreferences("temp", getApplicationContext().MODE_PRIVATE);
String name=preferences.getString("name",null);
Note: "temp" is sharedpreferences name and "name" is input value. if value does't exit then return null
Edit
SharedPreferences pref = getSharedPreferences("YourPref", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("yourValue", value);
editor.commit();
Read
SharedPreferences pref = getSharedPreferences("YourPref", MODE_PRIVATE);
value= pref.getString("yourValue", "");
editor.putString("text", mSaved.getText().toString());
Here, mSaved can be any TextView or EditText from where we can extract a string. you can simply specify a string. Here text will be the key which hold the value obtained from the mSaved (TextView or EditText).
SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
Also there is no need to save the preference file using the package name i.e., "com.example.app". You can mention your own preferred name. Hope this helps !
Basic idea of SharedPreferences is to store things on XML file.
Declare your xml file path.(if you don't have this file, Android will create it. If you have this file, Android will access it.)
SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
Write value to Shared Preferences
prefs.edit().putLong("preference_file_key", 1010101).apply();
the preference_file_key is the name of shared preference files. And the 1010101 is the value you need to store.
apply() at last is to save the changes. If you get error from apply(), change it to commit(). So this alternative sentence is
prefs.edit().putLong("preference_file_key", 1010101).commit();
Read from Shared Preferences
SharedPreferences sp = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
long lsp = sp.getLong("preference_file_key", -1);
lsp will be -1 if preference_file_key has no value. If 'preference_file_key' has a value, it will return the value of this.
The whole code for writing is
SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE); // Declare xml file
prefs.edit().putLong("preference_file_key", 1010101).apply(); // Write the value to key.
The code for reading is
SharedPreferences sf = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE); // Declare xml file
long lsp = sp.getLong("preference_file_key", -1); // Read the key and store in lsp
You can save value using this method:
public void savePreferencesForReasonCode(Context context,
String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
And using this method you can get value from SharedPreferences:
public String getPreferences(Context context, String prefKey) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
return sharedPreferences.getString(prefKey, "");
}
Here prefKey is the key that you used to saved the specific value. Thanks.
to save
PreferenceManager.getDefaultSharedPreferences(this).edit().putString("VarName","your value").apply();
to retreive :
String name = PreferenceManager.getDefaultSharedPreferences(this).getString("VarName","defaultValue");
default value is : Values to return if this preference does not exist.
you can change "this" with getActivity() or getApplicationContext() in
some cases
There are many ways people recommend how to use SharedPreferences. I have made a demo project here. Key point in sample is to use ApplicationContext & single sharedpreferences object. This demonstrates how to use SharedPreferences with following features:-
Using singelton class to access/update SharedPreferences
No need to pass context always for read/write SharedPreferences
It uses apply() instead of commit()
apply() is asynchronus save, doesn't return anything, it update value in memory first & changes are written to disk later
asynchronusly.
commit() is synchronus save, it return true/false based on outcome. Changes are written to disk synchronusly
works on android 2.3+ versions
Usage example as below:-
MyAppPreference.getInstance().setSampleStringKey("some_value");
String value= MyAppPreference.getInstance().getSampleStringKey();
Get source code here
& Detailed API's can be found here on developer.android.com
Best practice ever
Create Interface named with PreferenceManager:
// Interface to save values in shared preferences and also for retrieve values from shared preferences
public interface PreferenceManager {
SharedPreferences getPreferences();
Editor editPreferences();
void setString(String key, String value);
String getString(String key);
void setBoolean(String key, boolean value);
boolean getBoolean(String key);
void setInteger(String key, int value);
int getInteger(String key);
void setFloat(String key, float value);
float getFloat(String key);
}
How to use with Activity / Fragment:
public class HomeActivity extends AppCompatActivity implements PreferenceManager{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout_activity_home);
}
#Override
public SharedPreferences getPreferences(){
return getSharedPreferences("SP_TITLE", Context.MODE_PRIVATE);
}
#Override
public SharedPreferences.Editor editPreferences(){
return getPreferences().edit();
}
#Override
public void setString(String key, String value) {
editPreferences().putString(key, value).commit();
}
#Override
public String getString(String key) {
return getPreferences().getString(key, "");
}
#Override
public void setBoolean(String key, boolean value) {
editPreferences().putBoolean(key, value).commit();
}
#Override
public boolean getBoolean(String key) {
return getPreferences().getBoolean(key, false);
}
#Override
public void setInteger(String key, int value) {
editPreferences().putInt(key, value).commit();
}
#Override
public int getInteger(String key) {
return getPreferences().getInt(key, 0);
}
#Override
public void setFloat(String key, float value) {
editPreferences().putFloat(key, value).commit();
}
#Override
public float getFloat(String key) {
return getPreferences().getFloat(key, 0);
}
}
Note: Replace your key of SharedPreference with SP_TITLE.
Examples:
Store string in shareperence:
setString("my_key", "my_value");
Get string from shareperence:
String strValue = getString("my_key");
Hope this will help you.
I write a helper class for sharedpreferences:
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by mete_ on 23.12.2016.
*/
public class HelperSharedPref {
Context mContext;
public HelperSharedPref(Context mContext) {
this.mContext = mContext;
}
/**
*
* #param key Constant RC
* #param value Only String, Integer, Long, Float, Boolean types
*/
public void saveToSharedPref(String key, Object value) throws Exception {
SharedPreferences.Editor editor = mContext.getSharedPreferences(key, Context.MODE_PRIVATE).edit();
if (value instanceof String) {
editor.putString(key, (String) value);
} else if (value instanceof Integer) {
editor.putInt(key, (Integer) value);
} else if (value instanceof Long) {
editor.putLong(key, (Long) value);
} else if (value instanceof Float) {
editor.putFloat(key, (Float) value);
} else if (value instanceof Boolean) {
editor.putBoolean(key, (Boolean) value);
} else {
throw new Exception("Unacceptable object type");
}
editor.commit();
}
/**
* Return String
* #param key
* #return null default is null
*/
public String loadStringFromSharedPref(String key) throws Exception {
SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
String restoredText = prefs.getString(key, null);
return restoredText;
}
/**
* Return int
* #param key
* #return null default is -1
*/
public Integer loadIntegerFromSharedPref(String key) throws Exception {
SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
Integer restoredText = prefs.getInt(key, -1);
return restoredText;
}
/**
* Return float
* #param key
* #return null default is -1
*/
public Float loadFloatFromSharedPref(String key) throws Exception {
SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
Float restoredText = prefs.getFloat(key, -1);
return restoredText;
}
/**
* Return long
* #param key
* #return null default is -1
*/
public Long loadLongFromSharedPref(String key) throws Exception {
SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
Long restoredText = prefs.getLong(key, -1);
return restoredText;
}
/**
* Return boolean
* #param key
* #return null default is false
*/
public Boolean loadBooleanFromSharedPref(String key) throws Exception {
SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
Boolean restoredText = prefs.getBoolean(key, false);
return restoredText;
}
}
To store values in shared preferences:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Name","Jayesh");
editor.commit();
To retrieve values from shared preferences:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString("Name", "");
Use used this example simple and clear and checked
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
public class MainActivity extends AppCompatActivity {
EditText ed1,ed2,ed3;
Button b1;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
public static final String Email = "emailKey";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);
b1=(Button)findViewById(R.id.button);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String n = ed1.getText().toString();
String ph = ed2.getText().toString();
String e = ed3.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.commit();
Toast.makeText(MainActivity.this,"Thanks",Toast.LENGTH_LONG).show();
}
});
}
}
Using this simple library, here is how you make the calls to SharedPreferences..
TinyDB tinydb = new TinyDB(context);
tinydb.putInt("clickCount", 2);
tinydb.putString("userName", "john");
tinydb.putBoolean("isUserMale", true);
tinydb.putList("MyUsers", mUsersArray);
tinydb.putImagePNG("DropBox/WorkImages", "MeAtlunch.png", lunchBitmap);
//These plus the corresponding get methods are all Included
I wanted to add here that most of the snippets for this question will have something like MODE_PRIVATE when using SharedPreferences. Well, MODE_PRIVATE means that whatever you write into this shared preference can only be read by your application only.
Whatever key you pass to getSharedPreferences() method, android creates a file with that name and stores the preference data into it.
Also remember that getSharedPreferences() is supposed to be used when you intend to have multiple preference files for your application. If you intend to use single preference file and store all key-value pairs into it then use the getSharedPreference() method. Its weird why everyone (including myself) simply uses getSharedPreferences() flavor without even understanding the difference between the above two.
The following video tutorial should help
https://www.youtube.com/watch?v=2PcAQ1NBy98
Simple and hassle-free :: "Android-SharedPreferences-Helper" library
Better late than never: I created the "Android-SharedPreferences-Helper" library to help reduce the complexity and effort of using SharedPreferences. It also provides some extended functionality. Few things that it offers are as follows:
One line initialization and setup
Easily selecting whether to use default preferences or a custom preference file
Predefined (data type defaults) and customizable (what you may choose) default values for each datatype
Ability to set different default value for single use with just an additional param
You can register and unregister OnSharedPreferenceChangeListener as you do for default class
dependencies {
...
...
compile(group: 'com.viralypatel.sharedpreferenceshelper', name: 'library', version: '1.1.0', ext: 'aar')
}
Declaration of SharedPreferencesHelper object: (recommended at class
level)
SharedPreferencesHelper sph;
Instantiation of the SharedPreferencesHelper object: (recommended in
onCreate() method)
// use one of the following ways to instantiate
sph = new SharedPreferencesHelper(this); //this will use default shared preferences
sph = new SharedPreferencesHelper(this, "myappprefs"); // this will create a named shared preference file
sph = new SharedPreferencesHelper(this, "myappprefs", 0); // this will allow you to specify a mode
Putting values into shared preferences
Fairly simple! Unlike the default way (when using the SharedPreferences class) you'll NOT need to call .edit() and .commit() ever time.
sph.putBoolean("boolKey", true);
sph.putInt("intKey", 123);
sph.putString("stringKey", "string value");
sph.putLong("longKey", 456876451);
sph.putFloat("floatKey", 1.51f);
// putStringSet is supported only for android versions above HONEYCOMB
Set name = new HashSet();
name.add("Viral");
name.add("Patel");
sph.putStringSet("name", name);
That's it! Your values are stored in the shared preferences.
Getting values from shared preferences
Again, just one simple method call with the key name.
sph.getBoolean("boolKey");
sph.getInt("intKey");
sph.getString("stringKey");
sph.getLong("longKey");
sph.getFloat("floatKey");
// getStringSet is supported only for android versions above HONEYCOMB
sph.getStringSet("name");
It has a lot of other extended functionality
Check the details of extended functionality, usage and installation instructions etc on the GitHub Repository Page.
I have created a Helper class to make my Life easy. This is a generic class and has a-lot of methods those are commonly used in Apps like Shared Preferences, Email Validity, Date Time Format. Copy this class in your code and access it's methods wherever you need.
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.support.v4.app.FragmentActivity;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* Created by Zohaib Hassan on 3/4/2016.
*/
public class Helper {
private static ProgressDialog pd;
public static void saveData(String key, String value, Context context) {
SharedPreferences sp = context.getApplicationContext()
.getSharedPreferences("appData", 0);
SharedPreferences.Editor editor;
editor = sp.edit();
editor.putString(key, value);
editor.commit();
}
public static void deleteData(String key, Context context){
SharedPreferences sp = context.getApplicationContext()
.getSharedPreferences("appData", 0);
SharedPreferences.Editor editor;
editor = sp.edit();
editor.remove(key);
editor.commit();
}
public static String getSaveData(String key, Context context) {
SharedPreferences sp = context.getApplicationContext()
.getSharedPreferences("appData", 0);
String data = sp.getString(key, "");
return data;
}
public static long dateToUnix(String dt, String format) {
SimpleDateFormat formatter;
Date date = null;
long unixtime;
formatter = new SimpleDateFormat(format);
try {
date = formatter.parse(dt);
} catch (Exception ex) {
ex.printStackTrace();
}
unixtime = date.getTime();
return unixtime;
}
public static String getData(long unixTime, String formate) {
long unixSeconds = unixTime;
Date date = new Date(unixSeconds);
SimpleDateFormat sdf = new SimpleDateFormat(formate);
String formattedDate = sdf.format(date);
return formattedDate;
}
public static String getFormattedDate(String date, String currentFormat,
String desiredFormat) {
return getData(dateToUnix(date, currentFormat), desiredFormat);
}
public static double distance(double lat1, double lon1, double lat2,
double lon2, char unit) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2))
+ Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2))
* Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
if (unit == 'K') {
dist = dist * 1.609344;
} else if (unit == 'N') {
dist = dist * 0.8684;
}
return (dist);
}
/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
/* :: This function converts decimal degrees to radians : */
/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
private static double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
/* :: This function converts radians to decimal degrees : */
/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
private static double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
public static int getRendNumber() {
Random r = new Random();
return r.nextInt(360);
}
public static void hideKeyboard(Context context, EditText editText) {
InputMethodManager imm = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
public static void showLoder(Context context, String message) {
pd = new ProgressDialog(context);
pd.setCancelable(false);
pd.setMessage(message);
pd.show();
}
public static void showLoderImage(Context context, String message) {
pd = new ProgressDialog(context);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setCancelable(false);
pd.setMessage(message);
pd.show();
}
public static void dismissLoder() {
pd.dismiss();
}
public static void toast(Context context, String text) {
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}
/*
public static Boolean connection(Context context) {
ConnectionDetector connection = new ConnectionDetector(context);
if (!connection.isConnectingToInternet()) {
Helper.showAlert(context, "No Internet access...!");
//Helper.toast(context, "No internet access..!");
return false;
} else
return true;
}*/
public static void removeMapFrgment(FragmentActivity fa, int id) {
android.support.v4.app.Fragment fragment;
android.support.v4.app.FragmentManager fm;
android.support.v4.app.FragmentTransaction ft;
fm = fa.getSupportFragmentManager();
fragment = fm.findFragmentById(id);
ft = fa.getSupportFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
}
public static AlertDialog showDialog(Context context, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// TODO Auto-generated method stub
}
});
return builder.create();
}
public static void showAlert(Context context, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Alert");
builder.setMessage(message)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
}).show();
}
public static boolean isURL(String url) {
if (url == null)
return false;
boolean foundMatch = false;
try {
Pattern regex = Pattern
.compile(
"\\b(?:(https?|ftp|file)://|www\\.)?[-A-Z0-9+&#/%?=~_|$!:,.;]*[A-Z0-9+&##/%=~_|$]\\.[-A-Z0-9+&##/%?=~_|$!:,.;]*[A-Z0-9+&##/%=~_|$]",
Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher regexMatcher = regex.matcher(url);
foundMatch = regexMatcher.matches();
return foundMatch;
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
return false;
}
}
public static boolean atLeastOneChr(String string) {
if (string == null)
return false;
boolean foundMatch = false;
try {
Pattern regex = Pattern.compile("[a-zA-Z0-9]",
Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher regexMatcher = regex.matcher(string);
foundMatch = regexMatcher.matches();
return foundMatch;
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
return false;
}
}
public static boolean isValidEmail(String email, Context context) {
String expression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
return true;
} else {
// Helper.toast(context, "Email is not valid..!");
return false;
}
}
public static boolean isValidUserName(String email, Context context) {
String expression = "^[0-9a-zA-Z]+$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
return true;
} else {
Helper.toast(context, "Username is not valid..!");
return false;
}
}
public static boolean isValidDateSlash(String inDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
dateFormat.setLenient(false);
try {
dateFormat.parse(inDate.trim());
} catch (ParseException pe) {
return false;
}
return true;
}
public static boolean isValidDateDash(String inDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy");
dateFormat.setLenient(false);
try {
dateFormat.parse(inDate.trim());
} catch (ParseException pe) {
return false;
}
return true;
}
public static boolean isValidDateDot(String inDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.mm.yyyy");
dateFormat.setLenient(false);
try {
dateFormat.parse(inDate.trim());
} catch (ParseException pe) {
return false;
}
return true;
}
}
SharedPreferences.Editor editor = getSharedPreferences("identifier",
MODE_PRIVATE).edit();
//identifier is the unique to fetch data from your SharedPreference.
editor.putInt("keyword", 0);
// saved value place with 0.
//use this "keyword" to fetch saved value again.
editor.commit();//important line without this line your value is not stored in preference
// fetch the stored data using ....
SharedPreferences prefs = getSharedPreferences("identifier", MODE_PRIVATE);
// here both identifier will same
int fetchvalue = prefs.getInt("keyword", 0);
// here keyword will same as used above.
// 0 is default value when you nothing save in preference that time fetch value is 0.
you need to use SharedPreferences in AdapterClass or any other.
that time just use this declaration and use same ass above.
SharedPreferences.Editor editor = context.getSharedPreferences("idetifier",
Context.MODE_PRIVATE).edit();
SharedPreferences prefs = context.getSharedPreferences("identifier", Context.MODE_PRIVATE);
//here context is your application context
for string or boolean value
editor.putString("stringkeyword", "your string");
editor.putBoolean("booleankeyword","your boolean value");
editor.commit();
fetch data same as above
String fetchvalue = prefs.getString("keyword", "");
Boolean fetchvalue = prefs.getBoolean("keyword", "");
2.for Storing in shared prefrence
SharedPreferences.Editor editor =
getSharedPreferences("DeviceToken",MODE_PRIVATE).edit();
editor.putString("DeviceTokenkey","ABABABABABABABB12345");
editor.apply();
2.for retrieving the same use
SharedPreferences prefs = getSharedPreferences("DeviceToken",
MODE_PRIVATE);
String deviceToken = prefs.getString("DeviceTokenkey", null);
Here i have created an Helper class to use preferences in android.
This is the helper class:
public class PrefsUtil {
public static SharedPreferences getPreference() {
return PreferenceManager.getDefaultSharedPreferences(Applicatoin.getAppContext());
}
public static void putBoolean(String key, boolean value) {
getPreference().edit().putBoolean(key, value)
.apply();
}
public static boolean getBoolean(String key) {
return getPreference().getBoolean(key, false);
}
public static void putInt(String key, int value) {
getPreference().edit().putInt(key, value).apply();
}
public static void delKey(String key) {
getPreference().edit().remove(key).apply();
}
}
To store and retrieve global variables in a function way.
To test, make sure you have Textview items on your page, uncomment the two lines in the code and run. Then comment the two lines again, and run.
Here the id of the TextView is username and password.
In every Class where you want to use it, add these two routines at the end.
I would like this routine to be global routines, but do not know how. This works.
The variabels are available everywhere.
It stores the variables in "MyFile". You may change it your way.
You call it using
storeSession("username","frans");
storeSession("password","!2#4%");***
the variable username will be filled with "frans" and the password with "!2#4%". Even after a restart they are available.
and you retrieve it using
password.setText(getSession(("password")));
usernames.setText(getSession(("username")));
below the entire code of my grid.java
package nl.yentel.yenteldb2;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class Grid extends AppCompatActivity {
private TextView usernames;
private TextView password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
***// storeSession("username","frans.eilering#gmail.com");
//storeSession("password","mijn wachtwoord");***
password = (TextView) findViewById(R.id.password);
password.setText(getSession(("password")));
usernames=(TextView) findViewById(R.id.username);
usernames.setText(getSession(("username")));
}
public void storeSession(String key, String waarde) {
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyFile", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(key, waarde);
editor.commit();
}
public String getSession(String key) {
//http://androidexample.com/Android_SharedPreferences_Basics/index.php?view=article_discription&aid=126&aaid=146
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyFile", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
String output = pref.getString(key, null);
return output;
}
}
below you find the textview items
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="usernames"
android:id="#+id/username"
android:layout_below="#+id/textView"
android:layout_alignParentStart="true"
android:layout_marginTop="39dp"
android:hint="hier komt de username" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="password"
android:id="#+id/password"
android:layout_below="#+id/user"
android:layout_alignParentStart="true"
android:hint="hier komt het wachtwoord" />

Categories

Resources