Can't get SharedPreferences with activity - android

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

Related

how to pass data to more number of activities

I would like to pass data from one activity to another.If it is two or three activities we can send data via intent.suppose more number of activities are present (approximately 20).how can i pass data from first activity to last activity?
i want to go Activity A-->B-->C-->D-->......Y-->Z
if we send data via intent(put Extra) that is worst method.
is there any other way to send data?
thanks in advance
I would use SharedPreferences for this.
This will be easier because, we can change it anywhere in any activity and access them as needed. And we don't need to pass on each and every activity transition.
Simple example:
To set value in shared preference
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Nabin");
editor.putInt("idName", 12);
editor.commit();
And retrieve as
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
}
You can refer here more about it.
If you need some data to multiple activities, Just save data into SharedPreference and you will be able to access to all activities.
Here is full tutorial.
Save Data
// Create object of SharedPreferences.
SharedPreferences sharedPref= getSharedPreferences("mypref", 0);
SharedPreferences.Editor editor= sharedPref.edit();
//put your value
editor.putString("name", strName);
editor.putString("pwd", strPass);
editor.commit(); //commits your edits
Retrieve Data
SharedPreferences sharedPref= getSharedPreferences("mypref", 0);
String name = sharedPref.getString("name", "");
String password = sharedPref.getString("pwd", "");
If it's not a must case to use activities, you can change activities to fragments, attach them to same activity, cache your data in activity and get it from fragments.

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

SharedPreferences does not work for save

I'm using SharedPreferences to save username but it's not working.
In login Activity (read):
ocUserName = (EditText)findViewById(R.id.userNameText);
SharedPreferences prefs = this.getPreferences(Context.MODE_PRIVATE);
String userNameKey = "userName";
String userNameTV = prefs.getString(userNameKey,null);
SharedPreferences.Editor editor = prefs.edit();
if(userNameTV != null) {
ocUserName.setText(userNameTV);
}
in second Activity (write):
SharedPreferences prefs =
getSharedPreferences("com.mesbahsoft.IRIB", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
String userNameKey = "userName";
editor.putString(userNameKey, ocUser);
editor.commit();
Activity.getPreferences(int mode) (as used in your login activity) has a comment:
Retrieve a {#link SharedPreferences} object for accessing preferences that are private to this activity.
In your second activity you use Activity.getSharedPreferences(String name, int mode) and provide what looks like your Application Id as the name.
In effect, you are using two different sets of shared preferences in each activity.
I recommend using PreferenceManager.getDefaultSharedPreferences(Context context) if you intend to use the shared preferences throughout your application.
I assume the problem is that you are unable to read the written value. You need to use the same file in login activity:
SharedPreferences prefs = this.getSharedPreferences("com.mesbahsoft.IRIB", Context.MODE_PRIVATE);
If this does not work, kindly specify clearly where you are seeing the problem and also specify exceptions seen.
You are accessing different shared preferences in your activities,
this.getPreferences( Context.MODE_PRIVATE); is shorthand for this.getSharedPreferences( <activity's class name>, Context.MODE_PRIVATE);
In you login activity, use this,
getSharedPreferences("com.mesbahsoft.IRIB", MODE_PRIVATE);
References:
http://developer.android.com/reference/android/app/Activity.html#getPreferences(int)
http://developer.android.com/reference/android/content/Context.html#getSharedPreferences(java.lang.String,int)

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

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

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"

Categories

Resources