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();
}
Related
Hy, I'm writing an application for a project. I'm trying to pass data between two activities. I tried to use the SharedPreference but it's doesn't work. The output send me always " ".
I post the two function below.
function for send data:
public void SaveUser(FirebaseUser user){
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(TEXT, user.getDisplayName());
}
function for get data:
public String ReturnCreatorName(){
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
String name = sharedPreferences.getString(TEXT, "");
return name;
}
you forgot editor.commit();
public void SaveUser(FirebaseUser user){
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(TEXT, user.getDisplayName());
editor.commit();
}
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);
Writing preference from file Login.java:
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(Login.this);
SharedPreferences.Editor edit = sp.edit();
edit.putString("username", username);
edit.commit();
Loading preference in UpdateList.java:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(UpdateList.this);
String post_username = sp.getString("username", "anon");
I want to pass this shared preference to a php file through json, but it is not able to save the preference across two activities
Try this code to access and write your SharePreference
public static final String PREF_FIELD = "name";
public String getText(Context context) {
SharedPreferences preferences = context.getSharedPreferences(
"GLOBAL",
Context.MODE_PRIVATE);
String sessionId = preferences.getString(
PREF_FIELD,
"");
return sessionId;
}
public void setText(Context context, String text) {
SharedPreferences preferences = context.getSharedPreferences(
"GLOBAL",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(PREF_FIELD, text);
editor.commit();
}
How to save TextView values in SharedPreferences, see my code below and let me know how to store to SharedPreferences and retrieve in onCreate(..)
my code looks like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
txtOperative = (TextView) findViewById(R.id.currentOperative);
txtEvent = (TextView) findViewById(R.id.currentEvent);
intent = getIntent();
strEventName = intent.getStringExtra("eventName");
strOperativeName = intent.getStringExtra("operativeName");
txtEvent.setText(strEventName);
txtOperative.setText(strOperativeName);
}
I want to show these values always in TextViews, whenever user comes back to this activity
Simple use this for save your TextView value in sharedpreference
SharedPreferences sp = getSharedPreferences("key", 0);
SharedPreferences.Editor sedt = sp.edit();
sedt.putString("textvalue", txtEvent.getText().toString());
sedt.putString("txtopertaive", txtOperative.getText().toString());
sedt.commit();
Now after that retrieve it anywhere in your Activity class or any other Activity by
SharedPreferences sp = getSharedPreferences("key", 0);
String tValue = sp.getString("textvalue","");
String tOperative = sp.getString("txtopertaive","");
To save the data, Can't see any call for SharedPreferences - editor/ editor.commit()
Add those functions to your activity:
When you want to save data:
saveDataToPreferences(context, "strEventName", valueHere);
And in your activity,
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
context=this;
txtOperative = (TextView) findViewById(R.id.currentOperative);
txtEvent = (TextView) findViewById(R.id.currentEvent);
intent = getIntent();
strEventName = intent.getStringExtra("eventName");
strOperativeName = intent.getStringExtra("operativeName");
txtEvent.setText(getDataFromPreferences(context,"strEventName"));
txtOperative.setText(getDataFromPreferences(context,"strEventName"));
}
public static void saveDataToPreferences(Context context, String key,
String value) {
SharedPreferences prefs = context.getSharedPreferences("your package name",
Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
}
public static String getDataFromPreferences(Context context, String key) {
SharedPreferences prefs = context.getSharedPreferences("your package name",
Context.MODE_PRIVATE);
return prefs.getString(key, Constants.BLANK);
}
To store in shared preferences your value use that code.
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("OPERATIVE", txtOperative.getText().toString());
editor.String("EVENT", txtEvent.getText().toString());
editor.commit();
Use
prefs.edit().putString(context.getString(R.string.NAME), name).commit();
in order to save data to shared preferences and
prefs.getString(context.getString(R.string.NAME), "");
to get data from shared preferences.
define Editor like below
private Editor editor;
and initialize it after initializing shared preference like
editor = prefs.edit();
editor.putString("key1", "value1");
editor.putString("key2", "value2");
editor.commit();
And to retrieve this value just call
String value = prefs.getString("key1","");
I load from activity A the SharedPreferences in following way:
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
At activity B I want to load the SharedPreferences. Following was a NullPointerException:
private void LoadPreferences(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
data = sharedPreferences.getString("name", "08:00") ;
}
If I try following, I get this compilation error: "No enclosing instance of the type A is accessible in scope"
private void LoadPreferences(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(A.this);
data = sharedPreferences.getString("name", "08:00") ;
}
How can I access the data?
use getApplicationContext() instead of this in both Activities as:
In activity A the SharedPreferences in following way:
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
Intent sd=new Intent(this,Secongtess.class);
startActivity(sd);
}
and in Activity B get Value as:
private void LoadPreferences(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String data = sharedPreferences.getString("name", "08:00") ;
Toast.makeText(this,data, Toast.LENGTH_LONG).show();
}
because as doc says:
getDefaultSharedPreferences(Context context) :
Gets a SharedPreferences instance that points to the default file that
is used by the preference framework in the given context.