Android:How to save perennialy a variable? - java

I have a variable and I want to change it only the first time that I start my app. For example:
I open the app: Variable is not initialized. Variable changes to 4.
I close the app
I open the app Variable is 4.
And so on.
How can I do this?

I guess you are new to Android. You can save the values using "SharedPreferences".
Check this link : https://developer.android.com/training/basics/data-storage/shared-preferences.html
Also check out this example :
https://www.tutorialspoint.com/android/android_shared_preferences.htm
You can use this code :
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putString("key", "value");
editor.commit();
Here, MyPREFERENCES is the file name. Replace the "value" with the variable name.
Again, if you want to retrieve the value, then use:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.getBoolean("key", true);
//There are other methods like getInt(),getDouoble().getString() depending on the type of value

You can also write to a local file and use SQLite for that purposes if you would like to persist big object's data.

Related

storing & loading your apps previous state

I am using static session_counter to store the data,
yes the data I want to retrieve when app is opened is a INTEGER
private static int session_counter = 0;
MY app state
AFTER USER PERFORMED AN ACTION THE SESSION COUNTER SHOWS 1,
BUT WHEN THE APPLICATION IS CLOSED AND RE-OPENED AGAIN THE COUNTER IS SET TO 0
I WANT THAT SESSION COUNTER TO BE THE SAME AS PREVIOUS STATE TILL THE SPECIFIC CONDITION IS MET
For applications such as this you need a way where you can persist the data between each session.
as a previous answer mentioned shared preferences is the most effective way to do it.
Other alternatives exist as
Room
A remote database (Firebase) etc.
The structure will be somewhat like this
```
// Create object of SharedPreferences.
SharedPreferences sharedPref = getSharedPreferences("mypref", 0);
//now get Editor
SharedPreferences.Editor editor = sharedPref.edit();
//put your value
editor.putString("session_value", required_Text);
//commits your edits
editor.commit();
// Its used to retrieve data
SharedPreferences sharedPref = getSharedPreferences("mypref", 0);
String name = sharedPref.getString("session_value", "")
```
In your case it will be like
textView.text= sharedPref.getString("session_value", "")
if(condition){
editor.putString("session_value", required_Text);
}
You might want to use shared-preferences to save your value. This answer might be useful

SharedPreferences is not updating its value

Below is a snippet of code that i use in my save settings function (DialogFragment):
String orderBy = mOrderBySpinner.getSelectedItem().toString();
String search = mSearchEditText.getText().toString().trim();
SharedPreferences sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(InventoryPreferences.ORDER_BY, orderBy);
editor.putString(InventoryPreferences.SEARCH_TERM, search);
editor.apply();
I then retrieve that data with the following (Activity):
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
String orderBy = sharedPrefs.getString(InventoryPreferences.ORDER_BY, "name ASC");
String searchTerm = sharedPrefs.getString(
InventoryPreferences.SEARCH_TERM,"").trim();
These are my keys:
public static final String ORDER_BY = "orderBy";
public static final String SEARCH_TERM = "search";
Is there any reason as to why it wouldn't update the values when the key is the same?
getActivity().getPreferences(Context.MODE_PRIVATE);
is not
PreferenceManager.getDefaultSharedPreferences(this);
Use the second line in both methods.
From the docs:
https://developer.android.com/reference/android/app/Activity.html#getPreferences(int)
Retrieve a SharedPreferences object for accessing preferences that are
private to this activity
You are using two different methods to get access to a SharedPreferences file.
The first time using getActivity().getPreferences(Context.MODE_PRIVATE) you are calling Activity's getPreferences(int mode) which returns a SharedPreferences object which is supposed to be private to the activity which requests it. The name of the preferences file this SharedPreferences object points to is CLASS_NAME.xml
The second time using PreferenceManager.getDefaultSharedPreferences(this)
returns a SharedPreferences object which is supposed to be available and useful for the entire application. The name of the preferences file this SharedPreferences object points to is PACKAGE_NAME_preferences.xml.
So your problem is that you are using one file to write the preferences to and another to read them. Try using the more global thinking PreferenceManager.getDefaultSharedPreferences(Context context) to store preferences that relate to the entire application, and only use Activity.getPreferences(int mode) for preferences that only relate to a specific activity. (And then also remember to use the appropriate methods to retrieve them)
Use PreferenceManager to access SharedPreference.
Your code for updating preference value is correct.
Consider verifying that the values in input controls really changed
and verify, that the application has permission to write preferences.

Access SharedPreference and Editor object in other Java classes

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)

Android Preference different data for same getPreference() value

I am using Android Shared Preference for saving some small Boolean data. Now if I use the same keyword string that passed as String Parameter to the getSharedPreferences() method to save my all boolean values like that sample code is they conflict?
I mean if I use A common String for all getSharedPreferences() method and inside them if I use different String in putBoolean() is they are saved properly? Actually whats the functionality of the String argument of getSharedPreferences()?
I used this to save values:
public void saveStatus(boolean b){
SharedPreferences preferences = getApplicationContext().getSharedPreferences("STATUS", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("s1",b);
editor.commit();
}
they won't conflict if you use different key values like s1 s2 s3 different keyword for each boolean value other wise it will overwrite earlier value(This way will make keys unique):
why don't you pass two parameters to tackle issue like this:
public void saveStatus(String key,boolean b){
SharedPreferences preferences = getApplicationContext().getSharedPreferences("STATUS", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key,b);
editor.commit();
}
They will not conflict
Shared Preferences are stored as xml files.So the string argument(first one) you are passing in the getSharedPreferences() is the name of the xml file which will be created in persistent storage while the one you are using in the putBoolean() is the name of the property with its value specified as second argument which wil be added in that xml file.
For further details also see this:
Where are shared preferences stored?
About XML files

Getting java.lang.nullPointerException using SharedPreferences

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

Categories