I want to make a game level logic. The game itself similar with logo quiz game. It has locked and unlocked level. I need to display the locked and unlocked level based on the score which saved in shared preferences. so, how can I access the score variable in XML file?
declare these two variable in your activity
android.content.SharedPreferences someData;
public static String filename = "mySharedString";
initialize the Shared Preferences like this:
someData = getSharedPreferences(filename, 0);
you can add elements to the Shared Preferences like this:
android.content.SharedPreferences.Editor editor = someData.edit();
editor.putString("sharedString", stringData);
editor.commit();
you can retrieve data like this:
String dataReturned = someData.getString("sharedString","Couldn't load data");
The Couldn't load data will be set to the dataReturned variable if the sharedString is not existed in the Shared Preferences
also check this question How to use SharedPreferences in Android to store, fetch and edit values
Related
I am working on android project built partially in kotlin and partially in java. I am trying to pass information from a kotlin fragment class to a java class. I have come to see that there is a problem with the passing of information as I do not receive the needed value. After some debugging I have seen that the information is successfully stored, however when the information from shared preferences is accessed, only the default value is returned.
This is the code in the kotlin class. When a button is clicked it changes the value of a boolean variable to the opposite one, sets the text of a button to true/false and saves the value of the variable in shared preferences.
btnStyle.setOnClickListener() {
styleHasChanged = !styleHasChanged;
if(styleHasChanged == true){
btnStyle.setText("true")
}else{
btnStyle.setText("false")
}
val sharedPref : SharedPreferences?= activity?.getPreferences(MODE_PRIVATE);
sharedPref?.edit()?.putBoolean("bla", styleHasChanged)?.apply()
}
This is the java class. Shared preferences is called inside a function which chooses a filepath based on the received value.
public static String getHtmlContent(Context context, String htmlContent, Config config) {
SharedPreferences sharedPreferences = context.getSharedPreferences("bla",MODE_PRIVATE);
boolean hasStyleChanged = sharedPreferences.getBoolean("bla", false);
//moj
String cssPath;
if (!hasStyleChanged) {
cssPath = String.format(context.getString(R.string.css_tag), "file:///android_asset/css/Style.css");
} else {
cssPath = String.format(context.getString(R.string.css_tag), "file:///android_asset/css/Style2.css");
}
This is where the problem arises. Shared preferences in the java class always fetches the default value, no matter if the button is clicked or not.
The getPreferences method implicitly uses the class name of the Activity as the preference file name. By passing "bla" as the file name to getSharedPreferences you're trying to fetch the saved value from a different file.
If you would like to access the same preferences accross your application, then either use getSharedPreferences (for both writing and reading the preference) with the same file name, or use the getDefaultSharedPreferences static method of PreferenceManager to obtain the default SharedPreferences instance.
You should change your code to something like this:
val sharedPref : SharedPreferences? = activity?
.getSharedPreferences("someFileName", MODE_PRIVATE)
sharedPref?.edit()?.putBoolean("bla", styleHasChanged)?.apply()
And the Java part:
SharedPreferences sharedPreferences = context
.getSharedPreferences("someFileName", MODE_PRIVATE);
boolean hasStyleChanged = sharedPreferences.getBoolean("bla", false);
Your context.getSharedPreferences("PreferencesFileName",MODE_PRIVATE) should be the same even when using the activity?.getPreferences("PreferencesFileName",MODE_PRIVATE). In you code it's not like that.
Plus a simple suggestion, because I'm not sure if you're clear on that. The bla is the key for your boolean value not your Preferences file name. I mean it could be, but it's better to separate.
In MainActivity.java I write
SharedPreferences pref = getApplicationContext().getSharedPreferences("My_Pref" , 0);
Then I create object of Editor to put data in it
Editor edit = pref.edit();
Then I put data
edit.putString("1","Hello");
edit.commit(); / edit.apply();
In Second.java, I get preferences:
SharedPreferences pref = getPreferences(0);
then I try to receive data like
pref.getString("1",null);
and set it to text of textview. But this does not work.
Also, how do I access Preferences and editor in other java classes properly? I cannot understand the concept.
You are writing to and reading from different preference files. Use the same file and it should work.
To get an instance of SharedPreferences you do this:
1) In activity MainActivity:
SharedPreferences pref =
getApplicationContext().getSharedPreferences("My_Pref" , 0);
2) In activitySecond:
SharedPreferences pref =
getPreferences(0);
The first form opens preference file "My_Pref", the second form opens a file named after your activity class, i.e.: "Second". So they are reading and writing in different files.
I always use this form to open a preferences file:
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(this);
Try this way
public void saveToSharedPrefrence(Context context, String word) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = sharedPreferences.edit();
if (sharedPreferences.contains("history")) {
preExistRemove(word, context);
} else {
editor.putString("history", word.trim());
editor.commit();
}
}
Check this for more details
Get the context of your activity
Context shrdContext= ActivityClass.getContextOfApplication();
Now pass the context to get your shared preferences in your another class
SharedPreferences myPrefs= PreferenceManager.getDefaultSharedPreferences(shrdContext);
You have 3 ways to access preferences for a Android application.
The first you used is
SharedPreferences pref = getApplicationContext().getSharedPreferences("My_Pref" , 0); is the first one. With this you can read and write to a custom-named shared preference file. In your case the name of your file would be My_Pref.
This one is useful if you want to have differents preferences differents domain as it allow you to create many shared preferences with differents names. (ex : preferences for timezone, preference for your user).
The second getPreferences(int) allow to access preferences for an Activity and is bind closely to the activity calling it. The file created is named using the Activity name. In your case Second.
The third method PreferenceManager.getDefaultSharedPreferences(Context) create a shared preference file like the first method, but this time the file is named using your application package name. This is the best methods to use shared preferences, if you intend to have only one shared preference file.
In your initial question you wrote a data in one file and tried to read in an other file, which result in an error. That's why like Rob Meeuwisse write you must use PreferenceManager.getDefaultSharedPreferences(Context)
How do I retrieve shared preferences that have been saved from a
previous activity?
Do I need to enable file writing or some other manifest modifications?
You don't need any special manifest modificaiton to achieve that.
Assuming you have already saved preferences you can read those preferences at anytime doing something like I show bellow.
Write on Shared Preferences file:
SharedPreferences prefs = getSharedPreferences("your_file_name", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("yourStringName", "this_is_the_saved_value");
editor.commit(); // This line is IMPORTANT. If you miss this one its not gonna work!
Read from Shared Preferences file:
SharedPreferences prefs = getSharedPreferences("your_file_name",
MODE_PRIVATE); String string = prefs.getString("yourStringName",
"default_value_here_if_string_is_missing");
You can use a default file to save/ read your preferences. Just replace the first line of the two code snippets above by something like: SharedPreferences prefs = getDefaultSharedPreferences(getApplicationContext());
Thats it! Check the Android Developers dedicated page to this matter, here.
Hope it was usefull. Let me know about it.
You don't need to do anything special, other than make sure both activities are writing to/reading from the same file. Under the hood, preferences are just stored as an XML file.
So, your choices are:
1) Use PreferenceManager.getDefaultSharedPreferences() from both activities to write to the default file.
2) Use Context.getSharedPreferences() specifying a custom file name, and use the same name from both activities.
Shared Preferences are just that, shared. As long as you properly save the preferences after editting them by calling Editor.commit(), they will be available in the future.
I am working on a small project that requires a details screen where the user inputs his details and they are permanently stored. The user must have the option to change the details as well if he needs to do so. I looked into the saved preferences library however it does not seem to offer such functionality.
To give a visual idea of what is required, something like this screen should be fine:
http://www.google.com.mt/imgres?start=97&num=10&hl=en&tbo=d&biw=1366&bih=643&tbm=isch&tbnid=aQSZz782gIfOeM:&imgrefurl=http://andrejusb.blogspot.com/2011/10/iphone-web-application-development-with.html&docid=YpPF3-T8zLGOAM&imgurl=http://2.bp.blogspot.com/-YRISJXXajD0/Tq2KTpcqWiI/AAAAAAAAFiE/-aJen8IuVRM/s1600/7.png&w=365&h=712&ei=rbX6ULTDCOfV4gTroIDoCg&zoom=1&iact=hc&vpx=834&vpy=218&dur=2075&hovh=314&hovw=161&tx=80&ty=216&sig=108811856681773622351&page=4&tbnh=155&tbnw=79&ndsp=35&ved=1t:429,r:4,s:100,i:16
Any help is much appreciated. Thanks in advance
You could easily use Shared Preferences to store user's details. Everytime the Preference screen is opened the stored data can then be extracted from the Shared Preferences and presented to the user for edit. ONce the edit is done the new data can be updated back in the the Shared Preferences.
Also look at this thread to see how this can be done.
Using SharedPreferences would be perfect for this kind of small amount of data which you want to store persistently.
// 'this' is simply your Application Context, so you can access this nearly anywhere
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
To obtain from the preferences:
// You can equally use KEY_LAST_NAME to get the last name, etc. They are just key/value pairs
// Note that the 2nd arg is simply the default value if there is no key/value mapping
String firstName = prefs.getString(KEY_FIRST_NAME_CONSTANT, "");
Or to save:
Editor editor = prefs.edit();
// firstName being the text they entered in the EditText
editor.putString(KEY_FIRST_NAME_CONSTANT, firstName);
editor.commit();
You can achieve such functionality using SharedPreferences Class in android.
public void onCreate(Bundle object){
super.onCreate(object);
// Initialize UI and link xml data to java view objects
......
SharedPreferences myPref = getPreferences(MODE_PRIVATE);
nameView.setText(myPref.getString("USER_NAME", null));
passView.setText(myPref.getString("PASSWORD", null));
}
public void onStop(){
super.onStop();
if (isFinishing()) {
getPreferences(MODE_PRIVATE).edit()
.putString("USER_NAME", nameView.getText().toString())
.putString("PASSWORD", passView.getText().toString())
.commit()
}
}
I am trying to save the date of file parsing, so that when next time user, opens the application, the date can be checked against the last parsing date.
I am using shared preference to save the data and retrieve it, but getting error. Here is the code :
SharedPreferences settings = getPreferences(0);
String today = new Date(System.currentTimeMillis()).toString();
SharedPreferences.Editor edit = settings.edit();
System.out.println("******** Today : " + today);
edit.putString("lastdate", today);
String fetch = settings.getString("lastdate", "0");
System.out.println("******** Fetch : " + fetch);
txtTest.setText(fetch);
But I am getting null pointer error, am I missing something?
Many applications may provide a way to capture user preferences on the settings of a specific application or an activity. For supporting this, Android provides a simple set of APIs.
Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). Or it can be something that needs to be stored specific to an activity.
Shared Preferences: The shared preferences can be used by all the components (activities, services etc) off the applications.
Activity handled preferences: These preferences can only be used with in the activity and can not be used by other components of the application.
Shared Preferences:
The shared preferences are managed with the help of getSharedPreferences method of the Context class. The preferences are stored in a default file(1) or you can specify a file name(2) to be used to refer to the preferences.
(1) Here is how you get the instance when you specify the file name
public static final String PREF_FILE_NAME = "PrefFile";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
MODE_PRIVATE is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. Other two mode supported are MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE. In MODE_WORLD_READABLE other application can read the created file but can not modify it. In case of MODE_WORLD_WRITEABLE other applications also have write permissions for the created file.
(2) The recommended way is to use by the default mode, without specifying the file name
SharedPreferences preferences = PreferencesManager.getDefaultSharedPreferences(context);
Finally, once you have the preferences instance, here is how you can retrieve the stored values from the preferences:
int storedPreference = preferences.getInt("storedInt", 0);
To store values in the preference file SharedPreference.Editor object has to be used. Editor is the nested interface of the SharedPreference class.
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
Editor also support methods like remove() and clear() to delete the preference value from the file.
Activity Preferences:
The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activities private preferences. You can do that with the help of getPreferences() method of the activity. The getPreference method uses the getSharedPreferences() method with the name of the activity class for the preference file name.
Following is the code to get preferences
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
The code to store values is also same as in case of shared preferences.
SharedPreferences preferences = getPreference(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
You can also use other methods like storing the activity state in database. Note Android also contains a package called android.preference. The package defines classes to implement application preferences UI.
To see some more examples check Android's Data Storage post on developers site.
You need to change how you get the object
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(context);