How to get CheckBoxPreference value within the Receiver/Service in Android? - java

I use CheckBoxPreference in my PreferenceActivity to set a value. Later on, I want to check that value from Receiver and/or Service. findPreference() method is not available from that context. I know, that this preference value is stored in SharedPreferences anyway, but what is the key? How could I get the value of the checkbox?

I know, that this preference value is stored in SharedPreferences anyway, but what is the key?
Whatever value you have for android:key in your preference XML.
How could I get the value of the checkbox?
Call PreferenceManager.getDefaultSharedPreferences() to get the SharedPreferences, then call getBoolean() with the key you used in android:key.

In your preferences XML you'll have something like this:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference android:enabled="true"
android:title="#string/s_pref" android:key="#string/pref"
android:defaultValue="#string/d_pref"></CheckBoxPreference>
</PreferenceScreen>
Your strings.xml would have something like this:
<string name="pref">my.package.PREF</string>
<string name="s_pref">Prompt</string>
<string name="d_pref">true</string>
Your Activity's onCreate() would have something like this:
prefs = PreferenceManager.getDefaultSharedPreferences(this);
pref = prefs.getBoolean(getString(R.string.pref), true));
If you want to do something when someone changes the preferences, add an onActivityResult() to your activity and start the preferences activity with startActivityForResult(). When onActivityResult() is invoked with whatever result code you want to indicate a change in preferences, you can do another getDefaultSharedPreferences().
The shared preferences framework automatically persists the data... you don't have to actively deal with it yourself, though you can if you wish with an OnPreferenceChangeListener in the preferences activity

The only thing I would add to CommonsWare's answer is, since you mentioned a service, you can put whatever preferences the service needs to know about in its Intent extras. For example:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Intent intent = new Intent(this, MyService.class);
intent.putExtra("mypref", prefs.getString("mypref", ""));
startService(intent);

try to write this in your service
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplication());
and here specify the key that you have used in xml
if(preferences.getBoolean(your key ,true))
{
hope this help .

Related

Update data between two Activities Android Java

I am making a simple Android game that displaying a sequence of visual stimuli. I have two activities (Main & Settings). In the setting you will be able to edit the number of stimuli. When I edit the number it does not update at the main activity.
This is into Main activity onCreate
settings = new SettingsActivity();
setNrOfStimuli = settings.getSetNrOfStimuli();
stimuli = new int[setNrOfStimuli];
This is on Main activity
public void onSettingBtnClicked(View view) {
startActivity(new Intent(getApplicationContext(),SettingsActivity.class));
}
This is on Settings activity
public void onBackBtnClicked(View view) {
setNrOfStimuli = Integer.parseInt(inputNrOfStimuliView.getText().toString());
finish();
}
I can transfer the value of number by Intent or getter & setter but the problem is with initialization when it comes back to Main activity from Settings.
I think you should use SharedPreferences to store user's settings. You can go through this tutorial to learn about it.
https://www.javatpoint.com/android-preferences-example
You have to change this in the tutorial's code:
In prefs.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<!-- you do not worry about how this information will be stored, it will be handled
by the android. You have to use those data by getting that data by their key -->
<EditTextPreference
android:key="stimuli_numbers"
android:summary="Please enter Number of stimuli"
android:inputType="numberDecimal"
android:digits="0123456789"
android:title="Number of stimuli" />
</PreferenceScreen>
and in your Main Activity
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
//get the number of stimuli
//stimuli_numbers is the key and 0 is the default value (you can change this according to yours.
setNrOfStimuli = Integer.valueOf(prefs.getString("stimuli_numbers","0");

How to change starting activity in android studio?

Hello I am developing a simple project with android studio and I wanted to know how can I change the starting activity of the application via Java Code. I know how to do it with the androidmanifest.xml but I want the user to insert some data in the starting activity and then the next time the user loads the application the main activity pops up directly and not the starting activity again.
Thank you.
Use shared preference, with this you can save limited information. depending on what your user has selected you can save it and start an activity from it. the information remains even after the application is closed.
e.g. so you create a start activity that checks what settings have been selected and depending on that it starts the required activity with an intent.
search for shared preference and intent.
You should save a flag in Shared preference. For example in a first activity that launch save this:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "isNew");
editor.apply();
And when you want to Retrieve data from preference:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String name = prefs.getString("name", "default value");//"default value defined" is the default value.
Then Check if (name == isNew) then start your MainActivity class

In Shared Preference- Android I am not able to remove the error of "Private mode"

Here I am Facing the error
SharedPreferences sharedPreferences= MainActivity.this.getPreferences(getString(R.string.PREF_FILE),Context.MODE_PRIVATE);
I have al ready made this in string.xml
<string name="PREF_FILE">APP_PREF_FILE</string>
Youre using it wrong the methods are
QBActivity.this.getPreferences(Activity.MODE_PRIVATE);
QBActivity.this.getSharedPreferences("FILE",Activity.MODE_PRIVATE);
you want to use the 2nd way.
SharedPreferences sharedPreferences= MainActivity.this.getSharedPreferences(getString(R.string.PREF_FILE),Context.MODE_PRIVATE);
You have to call getSharedPreferences() instead. You are calling getPreferences() which has only one parameter.
SharedPreferences sharedPreferences= MainActivity.this.getSharedPreferences(getString(R.string.PREF_FILE),Context.MODE_PRIVATE);

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)

How to retrieve data stored with Shared Preference in MainActivity class to SplashScreen activity class? [duplicate]

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.

Categories