I am trying to access shared preferences from a service. I have used the the following to save the value of text to a string...
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("Ignore1_value", Example.getText().toString());
editor.commit();
But, how would i get the value in a service? Everything i have tried returns as nothing. Any help would be perfect and much appreciated?
I looked through some other questions as well with no solution. I have came up with this, but like i said it returns it as no text.
Context ctx = getApplicationContext();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(ctx);
String example1string = sharedPreferences.getString("Ignore1_value","");
Log.i("**GetSettings", example1string);
I'm always using PreferenceManager.getDefaultSharedPreferences(context). This is the same for all Contexts in your application.
A Service is a Context itself, so this would be sufficient:
PreferenceManager.getDefaultSharedPreferences(this);
Related
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
I'm using the library android material app rating (https://github.com/stepstone-tech/android-material-app-rating)
and I don't know how to save in SharedPreferences that the user has already done the review or rating.
I can save information in SharedPreferences if it's a TextView, but in this case I have no idea what to do.
Can you help me?
Example of how to save the info whether the user has rated you app:
SharedPreferences sharedPreferences = getSharedPreferences("MyShared", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("HasUserRating", true);
editor.apply();
Read back from SharedPreferences that the user has or has not rated:
SharedPreferences sharedPreferences = getSharedPreferences("MyShared", MODE_PRIVATE);
boolean hasRated = sharedPreferences.getBoolean("HasUserRating", false);
(Note: This will return false if the SharedPreferences key "HasUserRating" is not present.)
Use the callbacks within RatingDialogListener to save a value to SharedPreferences. Check for the existence of that SharedPreferences value prior to displaying the dialog.
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.
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.
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)