Hello.

Faced a problem when working with SharedPreferences. I need to set the initial settings, which the user can then change in a separate activation, but I don’t understand how to make the settings not always initial.

That is, when you first start in the main activation, I set the values, but then even when changing the settings in the Activation Setting, when you restart, there will be the same initial values ​​that I set in the main activation.

In general, I'm confused.

  • show the code that updates SharedPreferences - tCode
  • Perhaps I understood your task in my own way. But as I understand it, you want the very first launch of the application to have certain settings. And so that these settings are set only for the first time, and in subsequent launches either remain the same or the user asked their own? Then I would add an additional parameter to SharedPreferences, which would indicate that the initial settings have already been set. Well, or another option is to check whether the keys for the start settings already exist, if not, then the settings have never been installed, and if they exist, then do not touch. - cheerful_weasel
  • In general, when reading any type of data from the settings, the default value is specified by the second parameter, which will be used if nothing has been written to the settings for this key previously. - pavlofff

2 answers 2

The structure of preferences is usually specified in an XML file that is usually placed in the res / xml directory, such as:

<?xml version="1.0" encoding="utf-8"?> <android.support.v7.preference.PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <android.support.v7.preference.EditTextPreference android:key="@string/pref_myTextPref" android:title="@string/myText" android:summary="" android:persistent="true" android:defaultValue="15" android:inputType="number" android:numeric="integer" /> </android.support.v7.preference.PreferenceScreen> 

The initial value is set via android:defaultValue

PS Here is an example through the compat library, if religion does not allow, there are other standard classes (although they only work for older versions of Android)

    1. Create a class public class App extends Application .
    2. Register this class in the application manifest. This class will always start first. To do this, inside the application tag, add android:name=".App"
     <application android:icon="@drawable/your_ico" android:theme="@style/AppTheme" android:name=".App" > ... </application> 
    1. Override the onCreate(); method onCreate(); in the class App Add loading settings to it. If they are empty (not yet created) - create them from constants and save.

    2. If they are not empty (already created) - do not overwrite.