value is not getting in sharedpreferences, always default value is coming - android

I am storing one value in sharedpreferences using the below code
SharedPreferences sp;
sp = getApplicationContext().getSharedPreferences("myshare",
MODE_PRIVATE);
Editor e = sp.edit();
e.putString("a","unni");
e.commit();
this is in AddBluetooth Activity
Now I am retrieving that value from another activity called Dashboard Activity, which is using the below code
SharedPreferences sp;
sp = getApplicationContext().getSharedPreferences("myshare",
MODE_PRIVATE);
String aa =sp.getString("a","me");
but its's only returning the default value, how can I fix this issue

IF you're defining your preferences in a preferences.xml you need to access it using SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);

// declare this class variable in class from where u will put the string u wanna store in shared pref
//class variables
SharedPreferences pref;
SharedPreferences.Editor editor;
-------------------
//in oncrete method
// declare this in oncreate method
pref = getSharedPreferences("testapp", MODE_PRIVATE);
editor = pref.edit();
// the varibale u wanna put use the below statements
// for string use putString
// for boolean as u need use putBoolean
// have a look at the various option it offers..
editor.putString("selected", "nil");
editor.commit();
// here is the statement use this statement in class where u wanna retireve ur strings
// use getBoolean for Boolean variables
pref.getString("selected", "nil")
// here in sceond parameter in above statement is : if the value u r requesting for that is specified in first parameter is not present then it will return the //value which is your second parameter..
Pull Ur Shared-Pref :
Go to Data-->Data-->Ur package-->Pull The SharedPref file [DDMS]

Actually for me the above code snippet is not working in API 19, but for lower versions its working. So I used,
SharedPreferences saved_values = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor=saved_values.edit();
editor.putString("newCEAAddress", address);
editor.commit();
for getting value
SharedPreferences saved_values = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
DEVICE_ADDRESS=saved_values.getString("newCEAAddress", "nil");

Related

Can't access sharedpreferences from other activity?

I have a fragment where I let set some SharedPreference values set.
In the fragment, everything works fine - I can get any value I want, saving, editing, deleting works fine.
Then I have an Activity, from where I want to get the value "savedValue1" - but it does not work
public static final String MyPref = "MyPreference";
static SharedPreferences sharedpreferences;
//onCreateView...
sharedpreferences = this.getActivity().getSharedPreferences(MyPref,
Context.MODE_PRIVATE);
editor.putString("savedValue1", someString);
editor.commit();
I tried it with in Fragment:
public static String getValue(){
return sharedpreferences.getString("savedValue1","");
}
in Activity:
String newValue = Fragment.getValue();
But that doesn't work - any hint?
You should not have a Fragment.getValue() method.
SharedPreferences are here to avoid that.
Use the same getSharedPreferences("whatever", Context.MODE_PRIVATE) code and you shall get/set the same values inside the same preferences.
That is how it is supposed to be used. From the official documentation:
For any particular set of preferences, there is a single instance of
this class that all clients share.
Use this code to save and retrieve values from SharedPreferences
//To save string
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor e = settings.edit();
e.putString("savedValue1", someString);
e.commit();
//Retrieve team score
String saved_value = settings.getString("savedValue1", "");

How do I use sharedPreferences in Android?

I have an Android app which in one of the activities the user check one of the radio buttons. I want to save the user's choice and use its value in another activity.
To store
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences();
prefs.edit().putBoolean("KEY", your_boolean).commit();
To retrieve
Boolean your_boolean = prefs.getBoolean("KEY", false);
You can use shared preference for saving the values.
For Saving value into SharedPreferences use below code
SharedPreferences.Editor editor = getApplicationContext().getSharedPreferences(
"SHARED_PREF", MODE_PRIVATE).edit();
editor.putString("radio_value", value);
editor.commit();
For Retriving value from SharedPreferences use below code
SharedPreferences prefs = getApplicationContext().getSharedPreferences(
"SHARED_PREF", MODE_PRIVATE);
String storedValue = prefs.getString("radio_value","");

Can't get SharedPreferences with activity

Sorry for my bad English.
On my application, I save token (it's a web app) in shared preferences. In first activity I do this:
(token = 123)
SharedPreferences sp = getPreferences(MODE_PRIVATE);
Editor ed = sp.edit();
ed.putString("token", Main.getToken());
ed.commit();
Log.d("Recieved token: ", sp.getString("token", "null")); // Recieved token: 123
As you see, shared prefs are saved.
I have another activity, which may be called from browser to share link.
Code:
sp = getPreferences(MODE_PRIVATE);
Log.d("Token recieved: ", sp.getString("token", "null")); // null
But on another activity shared prefs return null.
What can I do?
To explain the reason why getPreferences() didn't work for you:
When you call getPreferences() without specifying a Shared Preferences name, it returns a Shared Preference using the calling Activity's class name as the Shared Preference name. That's why you are getting null in your other activity - it's actually a different Shared Preference set that you are referring to.
Use getSharedPreferences instead, using whatever preferences name you like:
getSharedPreferences("my_prefs", Activity.MODE_PRIVATE);
That will then be available throughout your application. However using getPreferences() is suitable where you don't need to refer to the data stored outside of a particular Activity.
use like following,,
SharedPreferences mAppSettings = getSharedPreferences("SharedPref", MODE_PRIVATE);
SharedPreferences.Editor prefEditor = mAppSettings.edit();
prefEditor.putString(""token, "");
prefEditor.commit();
for retrieving,,,
final SharedPreferences mAppSettings1 = getSharedPreferences(
"SharedPref", MODE_PRIVATE);
String token= mAppSettings1.getString("token", "");

Storing data in SharedPreferences accessible to all activities

I want to store and retrieve data that is accessible to all activities in my app using SharedPreferences. Is that possible? Up until now I have been doing it such that the data is stored for a particular activity.
Yes. SharePreferences do exactly this.
In every activity you can this:
SharedPreferences prefs = getSharedPreferences(ApplicationConstants.PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(name, value);
editor.commit();
And then retrieve values in other activty doing this:
mPrefs.getString(name, "");
This is the documentation:
http://developer.android.com/reference/android/content/SharedPreferences.html
And this is a good example to start with:
http://myandroidsolutions.blogspot.it/2012/03/android-preferenceactivity.html
Yes, that's the whole purpose of it.
Here's how you should write to it, via Editor
final SharedPreferences shp = ctx.getSharedPreferences(ctx.getString(R.string.app_name), Context.MODE_PRIVATE);
final SharedPreferences.Editor ed = shp.edit();
ed.putString("var1", "var1");
ed.putString("var2", "var2");
And to load it:
shp.getString("var1", "defvalue");
I have a better version. As sometimes when you try to do getSharedPreferences you might get an error as it could not be found.
This is how I store values in my Android projects.
Add
SharedPreferences sharedPreferences=this.getSharedPreferences("packagename", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("username", "specify name here").apply();
Package Name can be directly copied from top of the activity ex: com.example.name.projectname
Retrieve
String username = sharedPreferences.getString("username","");
If you want to access values in all of your activities I think the better way is storing in a custom Application class and later in activities you can:
((CustomApplication)getApplication()).getStoredValue()
Shared preferences are stored in files and this file access is slower.
Is my example for create function for set and get an object data called "USER"
For set sharePreference data
public void saveUser(User usuario) {
SharedPreferences sharedPref = getSharedPreferences("A", Context.MODE_PRIVATE); // sharedpreference set named "A"
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("name", usuario.getNombre());
editor.putString("username", usuario.getUsername());
editor.putString("pass", usuario.getContrasena());
editor.putString("roll",usuario.getRol());
editor.commit();
}
For get sharePreference data
public Usuario getUser() {
SharedPreferences sharedPref = getSharedPreferences("A", Context.MODE_PRIVATE); // sharedpreference set named "A"
User usuario = new User();
usuario.setNombre(sharedPref.getString("name", "null"));
usuario.setUsername(sharedPref.getString("username", "null"));
usuario.setContrasena(sharedPref.getString("pass", "null"));
usuario.setRol(sharedPref.getString("roll", "null"));
return usuario;
}
Important: set name to sharePreference in this case "A"

Trouble using sharedPreferences between two activities

I am trying to save a date in one activity and then have that date put in a textView in another activity. I am not sure about how to get the two activities to communicate with each other.
In file called report.java I have this method that gets the date and save it in sharedPrefernces.
private void updateLabel() {
date.setText(fmtDate.format(dateAndTime.getTime()));
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("date", date.getText().toString()); // value to store
editor.commit();
}
I am trying to figure out how to get my file called inspection use this to populate a textView
The problem I think I am having is with getting the correct name for the report file.
public static final String PREF_FILE_NAME = "report";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
then I have this code on a method called onResume()
#Override
public void onResume() {
super.onResume();
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
String strDate=preferences.getString("date", date.getText().toString());
date.setText(strDate);
}
You are saving the value to two seperate preference files.
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
Use only one.
Why not use the default preference file that is accessible by all classes/activities of your app?
SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(yourContext);
preferences.edit().putString(YOURKEY, yourStrValue);
This way you are not creating extra preference files in your app that you have to remember which values are stored in which files. Definately makes life easier.

Categories

Resources