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);
Related
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 !!
This question already has answers here:
How can I save an activity state using the save instance state?
(35 answers)
How to save app settings?
(6 answers)
Closed 8 years ago.
I'm developing a level-based app, and I want to be able to save the user's level number (1, 2, 3 etc..) and then when the app starts get the level number and do something with it.
How can I do it?
Use Shared Preferences like so:
Create these methods for use, or just use the content inside of the methods whenever you want:
public int getLevel()
{
SharedPreferences sp = getSharedPreferences("prefName", 0);
int level = sp.getInt("levelReference", 1);
return level;
}
public void setLevel(String level)
{
SharedPreferences.Editor editor = getSharedPreferences("prefName", 0).edit();
editor.putInt("levelReference", level);
editor.commit();
}
The 1 in sp.getInt("levelReference", 1); means that the method will return 1 if the preference is not found, so the default level is 1.
You can call them like this:
int level = getLevel(); // level is now the level that the user is on
setLevel(4); // user is now on level 4
Use SharedPreferences for storing level number:
http://developer.android.com/reference/android/content/SharedPreferences.html
http://android-er.blogspot.ru/2011/01/example-of-using-sharedpreferencesedito.html
If you read up in the documentation here you can see that to save data like a level number, you can use SharedPreferences. First, you'll need a SharedPreferences object, which you can obtain using
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
Then to save a piece of data, use:
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("level", level);
editor.commit();
And finally, to get that level back later, use:
sharedPref.getInt("level", 0);
Good luck!
I have a problem with with sharing data between two different activities. I have data like :
int number
String name
int number_2
int time
int total
I'm trying to make something like order list with this set of data . So it will take one set of data , then back to previous activity , move forward and again add data to it .
I have an idea of making it in array of object - but data inside was cleared after changing activity.
How can I make it ?
I don't know if and how to add Array of object to SharedPreferences , and get value of one element from there.
You should have a look at the documentation of the Intent(s) if you want to do that on the fly associating a key to the value(s) that you want to pass to your second activity.
Anyway, you can think any(sharedpref, database,...) way to pass your parameters but for those kind of things it's a convention and a good practice to follow that.
Don't used share preferences for this...Use the singleton pattern, extend Application, or just make a class with static variables and update them...
You can use .putExtra but since you are communicating with more than one activity the above suggestions are probably the best.
public class ShareData {
private String s;
private int s;
private static ShareData shareData = new ShareData();
private ShareData(){}
public static ShareData getInstance(){ return shareData}
//create getters and setters;
}
Why not to use Intents
Intent intent = new Intent(FirstActivity.this, (destination activity)SecondActivity.class);
intent.putExtra("some_key", value);
intent.putExtra("some_other_key", "a value");
startActivity(intent);
in the second activity
Bundle bundle = getIntent().getExtras();
int value = bundle.getInt("some_key");
String value2 = bundle.getString("some_other_key");
EDIT if you want to read more about adding array to shared preferences check this
Is it possible to add an array or object to SharedPreferences on Android
also this
http://www.sherif.mobi/2012/05/string-arrays-and-object-arrays-in.html
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
}
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.