Is there a way i can get a sharedpreference name? - android

Let's say i created a shared preference.
sp = this.getSharedPreferences("name",MODE_PRIVATE);
If i'm in another activity, is there a way i can find the name of sp and set it to a string?

you can access the sharedpreferences with the same method you have used. use a public static varibale to hold the name in a class.

Use a constant. a public final static String NAME = "the_name";. Then you can alway reference it as NameOfTheClassWhereYouPutIt.NAME

If you are looking to refer to a given shared preference in another activity, you can pass that String key of that preference to the new Activity via its Intent when creating it.
If you simply need to find a certain preference in any activity, you can iterate over all of the preferences, and get access to all the keys (and values) that way.
Assuming your shared preferences is in the variable mySharedPreferences, an example of getting all of the keys and vales would be:
Map<String,?> preferenceMap = mySharedPreferences.getAll();
for ( Map.Entry<String, ?> keyValPair : preferenceMap.entrySet() )
{
String key = keyValPair.getKey(); // this is your preference name
String val = keyValPair.getValue(); // this is your preference value
}

Related

Getting data from sharedPreference to a specific activity

Is it possible to get a sharedprefence data from MainActivity_A and fetch it only to MainActivity_B and the other activities like MainActivity_C and MainActivity_D cannot access the data that has been fetched to MainActivity_B?
Well It totally depends on you wheather you wanna get that data or not..once you store data in shared preference with key then just get that data in the specific activity you want Thats It !!
For Example in Activity X you save the Shared Preference value like this
public static final String SHARED_PREFS = "sharedPrefs";
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS,MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("Key",Value);
Then in Activity A you want to use this value then you can do it like this
SharedPreferences pref;
pref = getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);
String Value = pref.getString("Key");
In This way the value will be stored in variable String
And if you don't want the value in other activity then just don't call it !!

How to set values globally in android [duplicate]

This question already has answers here:
Android global variable
(14 answers)
How to use SharedPreferences in Android to store, fetch and edit values [closed]
(30 answers)
Closed 6 years ago.
How to set values globally so that i can access from any activity or fragment.
For eg : activity_login.java > user_id need to store globally so every time any section which depends on user_id, checking and pulling data from backend will be easy instead of passing through activity (intent)
Edit :
i do need setter and getter from fragment or activtiy.
There are many ways to store values globally so it can be access from any where in application all classes :
Declare public static variable but it's not preferable for long storage.
Use shared preferences - SharedPreferences
Use database - SQlite
You can use any of one above alternative to access globally values.
Use Sharedpreferences.its safe, Here's the example https://www.tutorialspoint.com/android/android_shared_preferences.htm
Use sharedPreferences and access the values at any of your class
Put the below code at SamplePreferences.java
private static final String TOTALCOUNT = "total_count";
public static void setTotalCount(Context thisActivity, String id) {
Editor editor = thisActivity.getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();
editor.putString(TOTALCOUNT, id);
editor.commit();
}
public static String getTotalCount(Context thisActivity) {
SharedPreferences user_pref = thisActivity.getSharedPreferences(KEY, Context.MODE_PRIVATE);
return user_pref.getString(TOTALCOUNT, "0");
}
You can set the values from any of your class use below code
SamplePreferences.setTotalCount(thisContext, "2");
Access that value using below code
SamplePreferences.getTotalCount(thisContext);

Can't Get Shared Preference Value Even Though Values Exist

Any time I try to getInt() from a SharedPreference my app crashes, yet I can iterate through the preferences as a map. For instance, see the starred lines below:
private void loadPref(){
myPrefs = PreferenceManager.getDefaultSharedPreferences(this);
int sf = DEFAULT_VALUE;
Map<String,?> keys = myPrefs.getAll();
for(Map.Entry<String,?> entry : keys.entrySet()){
if (entry.getKey().contentEquals("score_format"))
// this works: //*****
sf = Integer.parseInt(entry.getValue().toString()); //*****
}
// but this does not: //*****
// sf = myPrefs.getInt("score_format", DEFAULT_VALUE); //*****
setScoreFormat(sf);
}
Clearly, my prefs are being saved (as evidenced by this sample and working preference screens across multiple activities). I am calling super.onCreate() before trying to access getDefaultSharedPreferences.
What should I be considering to understand why this code is not working? Why would the map work but not the "getInt" method? I did notice that the app would also crash if I tried to cast the key value explicitly... I had to cast it toString first.
What am I missing?
if you don't want to parse, make sure the score you're putting into the intent with putExtra is an int type, not a string.
Looks like object assosiated with score_format key is a String but you are trying to obtain it as int which is a mistake.

android default values for shared preferences

I am trying to understand the SharedPreferences of Android. I am a beginner
and don't know a lot about it.
I have this class I implemented for my app Preferences
public class Preferences {
public static final String MY_PREF = "MyPreferences";
private SharedPreferences sharedPreferences;
private Editor editor;
public Preferences(Context context) {
this.sharedPreferences = context.getSharedPreferences(MY_PREF, 0);
this.editor = this.sharedPreferences.edit();
}
public void set(String key, String value) {
this.editor.putString(key, value);
this.editor.commit();
}
public String get(String key) {
return this.sharedPreferences.getString(key, null);
}
public void clear(String key) {
this.editor.remove(key);
this.editor.commit();
}
public void clear() {
this.editor.clear();
this.editor.commit();
}
}
The thing is that I would like to set default preferences. They would be set when the app is installed and could be modified after by the application and stay persistent.
I heard about a preferences.xml but I don't understand the process.
Could someone help me?
Thanks for you time
Simple, if you want a separate default value for each variable, you need to do it for each one, but on your method:
public String get(String key) {
return this.sharedPreferences.getString(key,"this is your default value");
}
If the variable was never accessed by the user or was never created, the system will set the default value as value and if you or the user changed this value, the default value is ignored. See http://developer.android.com/guide/topics/data/data-storage.html#pref
Directly from the Android Documentation:
The SharedPreferences class provides a general framework that allows
you to save and retrieve persistent key-value pairs of primitive data
types. You can use SharedPreferences to save any primitive data:
booleans, floats, ints, longs, and strings. This data will persist
across user sessions (even if your application is killed).
Could you use the default value parameter of the getX() method?
For example, to get a String called 'username', you could use this:
String username = prefs.getString("username_key", "DefaultUsername");
You can simply define your default values in your Preferences class.
You can store default values in string resource:
<string name="key_name">default_value</string>
and then get it as it follows:
int ResId = context.getResources().getIdentifier(key_name, "string", context.getPackageName()));
prefs.getString(key_name,context.getResources().getString(ResId);

Why cannot save INT to SharedPreferences?

I have a strange problem. I have never had it before. When I try to save int value to my SharedPreference and then restore in other Activity. Value is always 0 even if I save there other value (for example: 1);
private String Number;
private String Profile;
and then saving values (in this case "1") to SharedPreferences in first Activity:
SharedPreferences a = FirstActivity.this.getSharedPreferences("a", MODE_PRIVATE);
SharedPreferences.Editor prefsEditorProfiles = a.edit();
prefsEditorProfiles.putInt(Profile, 1);
prefsEditorProfiles.putInt(Number, 1);
prefsEditorProfiles.commit();
then restore SharedPreferences in other Activity:
SharedPreferences a = SecondActivity.this.getSharedPreferences("a", MODE_PRIVATE);
int ab = a.getInt(Number, 0);
And application shows me 0 instead of 1. My other SharedPreferences works great. I don't know where is the problem.
I'd check what's the value of the Number and Profile variables you declared... you are using their values as keys, so if they have conflicting names, you might be overwriting one setting with the other even though the code looks right.
I'd recommend replacing this:
private String Number;
private String Profile;
With this:
private final String NUMBER = "Number";
private final String PROFILE = "Profile";
And then using those constants when setting/getting your preference value.
Do you ever set a value for
"Number" and "Profile"?
If not then that is your problem -those strings are null.
Please try to use
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
rather than using
SharedPreferences prefs = getActivity().getSharedPreferences ("PREFS_KEY", 0);
when Storing int in shared preference
I've been trying for a while to use putInt like you but it always give an error.
prefsEditorProfiles.putInt(Number, 1);
by just changing a.putInt to a.putString and retrieving it with a.getString I was able to have the correct value.
so, I guess there should be something wrong with putInt and getInt.
Anyway, try that also to have the correct value you need to continue for application.

Categories

Resources