как сохранить и загрузить тему, используя общие настройки? - PullRequest
0 голосов
/ 10 июля 2020

пожалуйста, помогите мне, прошло 3 дня, и я все еще не понимаю, почему мои общие настройки не сохраняют и не загружают мою тему

вот мое основное действие


import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String SHARED_PREF = "sharedPrefs";


    public Button button11, button22, button33;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        int LT = loadTheme(0);
        int ST = saveTheme(0);
        Utils.onActivityCreateSetTheme(this, LT,ST);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.button1).setOnClickListener(this);
        findViewById(R.id.button2).setOnClickListener(this);
        findViewById(R.id.button3).setOnClickListener(this);
    }
    @Override
    public void onClick(View v)
    {
        // TODO Auto-generated method stub
        switch (v.getId())
        {
            case R.id.button1:
                Utils.changeToTheme(this, Utils.THEME_DEFAULT);
                loadTheme(0);
                saveTheme(0);
                break;
            case R.id.button2:
                Utils.changeToTheme(this, Utils.THEME_WHITE);
                loadTheme(1);
                saveTheme(1);
                break;
            case R.id.button3:
                Utils.changeToTheme(this, Utils.THEME_BLUE);
                loadTheme(2);
                saveTheme(2);
                break;
        }

    }
    public void restartApp() {
        Intent i = new Intent(getApplicationContext(),MainActivity.class);
        startActivity(i);
        finish();
    }

    public int loadTheme(int defval) {
        if (defval == 1) {
            SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
            sharedPreferences.getInt("Theme", 1);
            Toast.makeText(this, "LOADTHEMEVAL= 1", Toast.LENGTH_SHORT).show();

        } else if (defval == 2) {
            SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
            sharedPreferences.getInt("Theme", 2);
            Toast.makeText(this, "LOADTHEMEVAL= 2", Toast.LENGTH_SHORT).show();

        } else if(defval == 0) {
            SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
            sharedPreferences.getInt("Theme", 0);
            Toast.makeText(this, "LOADTHEMEVAL= 0", Toast.LENGTH_SHORT).show();

        }

        return defval;
    }
    public int saveTheme(int defval) {
        if (defval == 2) {
            SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
            SharedPreferences.Editor prefEditor = sharedPreferences.edit();
            prefEditor.clear();
            prefEditor.putInt("Theme", 2);
            prefEditor.apply();
            Toast.makeText(this, "SAVETHEMEVAL= 2", Toast.LENGTH_SHORT).show();
        } else if (defval == 1) {
            SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
            SharedPreferences.Editor prefEditor = sharedPreferences.edit();
            prefEditor.clear();
            prefEditor.putInt("Theme", 1);
            prefEditor.apply();
            Toast.makeText(this, "SAVETHEMEVAL= 1", Toast.LENGTH_SHORT).show();

        } else if (defval == 0) {
            SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
            SharedPreferences.Editor prefEditor = sharedPreferences.edit();
            prefEditor.clear();
            prefEditor.putInt("Theme", 0);
            prefEditor.apply();
            Toast.makeText(this, "SAVETHEMEVAL= 0", Toast.LENGTH_SHORT).show();
        }
        return defval;
    }

}

вот мои утилиты

package com.perz.themeactivity;
import android.app.Activity;
import android.content.Intent;
public class Utils
{
    private static int sTheme;
    public final static int THEME_DEFAULT = 0;
    public final static int THEME_WHITE = 1;
    public final static int THEME_BLUE = 2;
    /**
     * Set the theme of the Activity, and restart it by creating a new Activity of the same type.
     */
    public static void changeToTheme(Activity activity, int theme)
    {
        sTheme = theme;
        activity.finish();
        activity.startActivity(new Intent(activity, activity.getClass()));
    }
    /** Set the theme of the activity, according to the configuration. */
    public static void onActivityCreateSetTheme(Activity activity, int theme, int them)
    {
        switch (sTheme)
        {
            default:
            case THEME_DEFAULT:
                activity.setTheme(R.style.AppTheme);
                break;
            case THEME_WHITE:
                activity.setTheme(R.style.Cerv_Theme);
                break;
            case THEME_BLUE:
                activity.setTheme(R.style.Giant_Theme);
                break;
        }
    }
}

вот моя activity_main. xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Theme default"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.101"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.25"
        tools:ignore="MissingConstraints" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Cerv_Theme"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.878"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.25"
        tools:ignore="MissingConstraints" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Giant Theme"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.486"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.366"
        tools:ignore="MissingConstraints" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="?attr/textcolor"
        android:text="PRIMARYLETTER"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.112"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="MissingConstraints" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="?attr/gaugebackcolor"
        android:text="COLOR SECONDARY"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.553"
        tools:ignore="MissingConstraints" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="?attr/gaugebackcolor"
        android:text="COLOR TERTIARY"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.899"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>

и мой цвет. xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#E80A0A </color>

    <color name="colorPrimaryDark">#E80A0A </color>
    <color name="colorPrimaryletter">#E80A0A</color>
    <color name="colorSecondary">#000000</color>
    <color name="colorTertiary">#E80A0A</color>
    <color name="colorAccent">#000000</color>
    <color name="pure_black">#000000</color>
</resources>

и, наконец, мой стиль . xml

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="backgroundColor">@color/pure_black</item>
        <item name="textcolor">@color/colorPrimaryletter</item>
        <item name="gaugebackcolor">@color/colorSecondary</item>
        <item name="scalecolor">@color/colorTertiary</item>
        <item name="colorback">@color/colorAccent</item>
    </style>

    <style name="Cerv_Theme" parent="Theme.AppCompat.Light.DarkActionBar">

        <!-- Customize your theme here. -->

        <item name="colorPrimary">#000000</item>
        <item name="colorPrimaryDark">#EFECEC</item>
        <item name="colorAccent">#000000</item>
        <item name="backgroundColor">#000000</item>
        <item name="textcolor">#EFECEC</item>
        <item name="gaugebackcolor">#FFFFFF</item>
        <item name="scalecolor">#000000</item>
        <item name="colorback">#000000</item>
    </style>

    <style name="Giant_Theme" parent="Theme.AppCompat.Light.DarkActionBar">

        <!-- Customize your theme here. -->

        <item name="colorPrimary">#0143C6</item>
        <item name="colorPrimaryDark">#FFFFFF</item>
        <item name="colorAccent">#0439A3</item>
        <item name="backgroundColor">#000000</item>
        <item name="textcolor">#EFECEC</item>
        <item name="gaugebackcolor">#0143C6</item>
        <item name="scalecolor">#000000</item>
        <item name="colorback">#0439A3</item>
    </style>

</resources>

пожалуйста, помогите мне, я действительно хочу сделать эту работу, я попробовал несколько ответов, связанных с моей проблемой, например: Изменение темы в Android (Android Studio) , сохранить android тему с использованием общих настроек , Сохранение значения int с использованием общих настроек , Как сохранить тему на SharedPreference в Android, Как изменить значение int onclick и передать его другому действию? на android? и, наконец, Общие настройки не постоянны , но они не устранили мою проблему: (

по этой ссылке: Изменение темы в Android (Android Studio)

Я попытался применить ответ к своему приложению

теперь UTILS выглядит так

package com.perz.themeactivity;
import android.app.Activity;
import android.content.Intent;
public class Utils
{
    private static int sTheme;
    public final static int THEME_DEFAULT = 0;
    public final static int THEME_WHITE = 1;
    public final static int THEME_BLUE = 2;
    /**
     * Set the theme of the Activity, and restart it by creating a new Activity of the same type.
     */
    public static void changeToTheme(Activity activity, int theme)
    {
        sTheme = theme;
        activity.finish();
        activity.startActivity(new Intent(activity, activity.getClass()));
    }
    /** Set the theme of the activity, according to the configuration. */
    public static void onActivityCreateSetTheme(Activity activity, int sTheme)
    {
        switch (sTheme)
        {
            default:
            case THEME_DEFAULT:
                int myTheme = R.style.AppTheme;
                activity.setTheme(myTheme);

                MainActivity obj0 = new MainActivity();
                obj0.saveTheme(myTheme);
                break;
            case THEME_WHITE:
                int myTheme1 = R.style.Cerv_Theme;
                activity.setTheme(myTheme1);

                MainActivity obj1 = new MainActivity();
                obj1.saveTheme(myTheme1);
                break;
            case THEME_BLUE:
                int myTheme2 = R.style.Giant_Theme;
                activity.setTheme(myTheme2);

                MainActivity obj2 = new MainActivity();
                obj2.saveTheme(myTheme2);
                break;
        }
    }
}

и ОСНОВНАЯ АКТИВНОСТЬ

{
    private static final String SHARED_PREF = "sharedPrefs";
    private static final int THEME_DEFAULT = 0;
    public final static int THEME_WHITE = 1;
    public final static int THEME_BLUE = 2;

    public Button button11, button22, button33;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        int theme = loadTheme();
        Utils.onActivityCreateSetTheme(this,theme );
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.button1).setOnClickListener(this);
        findViewById(R.id.button2).setOnClickListener(this);
        findViewById(R.id.button3).setOnClickListener(this);
    }
    @Override
    public void onClick(View v)
    {
        // TODO Auto-generated method stub
        switch (v.getId())
        {
            case R.id.button1:
                Utils.changeToTheme(this, Utils.THEME_DEFAULT);
                break;
            case R.id.button2:
                Utils.changeToTheme(this, Utils.THEME_WHITE);

                break;
            case R.id.button3:
                Utils.changeToTheme(this, Utils.THEME_BLUE);

                break;
        }

    }
    public void restartApp() {
        Intent i = new Intent(getApplicationContext(),MainActivity.class);
        startActivity(i);
        finish();
    }

    public int loadTheme(){
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

        //Load theme color
        int theme = sharedPreferences.getInt("Theme",THEME_DEFAULT); //RED is default color, when nothing is saved yet

        return theme;
    }
    public void saveTheme(int theme)
    {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor prefEditor = sharedPreferences.edit();
        prefEditor.putInt("Theme",theme);
    }

}

теперь вывод отладчика

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.perz.themeactivity, PID: 23544
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.perz.themeactivity/com.perz.themeactivity.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
        at android.content.ContextWrapper.getPackageName(ContextWrapper.java:135)
        at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:537)
        at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:526)
        at com.perz.themeactivity.MainActivity.saveTheme(MainActivity.java:66)
        at com.perz.themeactivity.Utils.onActivityCreateSetTheme(Utils.java:30)
        at com.perz.themeactivity.MainActivity.onCreate(MainActivity.java:23)
        at android.app.Activity.performCreate(Activity.java:7009)
        at android.app.Activity.performCreate(Activity.java:7000)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)

ясно, что он не работает должным образом, даже если я немного его подправлю, двигаемся дальше. Далее это: сохранить android тему используя общие настройки

я использовал лучший ответ

теперь UTILS:

{
    private static int sTheme;
    public final static int THEME_DEFAULT = 0;
    public final static int THEME_WHITE = 1;
    public final static int THEME_BLUE = 2;
    /**
     * Set the theme of the Activity, and restart it by creating a new Activity of the same type.
     */
    public static void changeToTheme(Activity activity, int theme)
    {
        sTheme = theme;
        activity.finish();
        activity.startActivity(new Intent(activity, activity.getClass()));
    }
    /** Set the theme of the activity, according to the configuration. */
    public static void onActivityCreateSetTheme(Activity activity, int theme)
    {
        switch (sTheme)
        {
            default:
            case THEME_DEFAULT:
                activity.setTheme(R.style.AppTheme);
                break;
            case THEME_WHITE:
                activity.setTheme(R.style.Cerv_Theme);
                break;
            case THEME_BLUE:
                activity.setTheme(R.style.Giant_Theme);
                break;
        }
    }
}

и ОСНОВНАЯ АКТИВНОСТЬ:

{
    private static final String SHARED_PREF = "sharedPrefs";
    public final static int THEME_DEFAULT = 0;
    public final static int THEME_WHITE = 1;
    public final static int THEME_BLUE = 2;

    public Button button11, button22, button33;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        Utils.onActivityCreateSetTheme(this, new SharedPreferencesManager(this).retrieveInt("theme", THEME_DEFAULT));
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.button1).setOnClickListener(this);
        findViewById(R.id.button2).setOnClickListener(this);
        findViewById(R.id.button3).setOnClickListener(this);
    }
    @Override
    public void onClick(View v)
    {

        switch (v.getId())
        {
            case R.id.button1:
                Utils.changeToTheme(this, Utils.THEME_DEFAULT);
                new SharedPreferencesManager(getApplicationContext()).storeInt("theme", THEME_DEFAULT);
                break;
            case R.id.button2:
                Utils.changeToTheme(this, Utils.THEME_WHITE);
                new SharedPreferencesManager(getApplicationContext()).storeInt("theme", THEME_WHITE);
                break;
            case R.id.button3:
                Utils.changeToTheme(this, Utils.THEME_BLUE);
                new SharedPreferencesManager(getApplicationContext()).storeInt("theme", THEME_BLUE);
                break;
        }

    }
    public void restartApp() {
        Intent i = new Intent(getApplicationContext(),MainActivity.class);
        startActivity(i);
        finish();
    }


}

и мой SHAREDPREFERENCEMANAGER


package com.perz.themeactivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class SharedPreferencesManager {
    /**
     * SharedPreferences to store the settings. This way, they'll be available next time the user starts the app
     */
    private SharedPreferences sPreferences;
    /**
     * Editor to make changes on sharedPreferences
     */
    private SharedPreferences.Editor sEditor;

    /**
     * The class itself
     */
    private Context context;

    public SharedPreferencesManager(Context context) {
        this.context = context;
        sPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    }

    private SharedPreferences.Editor getEditor() {
        return sPreferences.edit();
    }

    /**
     * Store a boolean value in sharedPreferences
     *
     * @param tag   identifies the value
     * @param value the value itself
     */

    public void storeBoolean(String tag, boolean value) {
        sEditor = getEditor();
        sEditor.putBoolean(tag, value);
        sEditor.commit();
    }

    /**
     * Store a string in sharedPreferences
     *
     * @param tag identifies the value
     * @param str the string itself
     */

    public void storeString(String tag, String str) {
        sEditor = getEditor();
        sEditor.putString(tag, str);
        sEditor.commit();
    }

    /**
     * @param tag      identifies the value
     * @param defValue default value
     * @return the stored or default value
     */

    public boolean retrieveBoolean(String tag, boolean defValue) {
        return sPreferences.getBoolean(tag, defValue);

    }

    /**
     * @param tag    identifies the string
     * @param defStr default string
     * @return the stored or default string
     */

    public String retrieveString(String tag, String defStr) {
        return sPreferences.getString(tag, defStr);
    }

    /**
     * @param tag      identifies the value
     * @param defValue default value
     * @return the stored or default value
     */
    public int retrieveInt(String tag, int defValue) {
        return sPreferences.getInt(tag, defValue);
    }

    /**
     * @param tag      identifies the value
     * @param defValue the value itself
     */
    public void storeInt(String tag, int defValue) {
        sEditor = getEditor();
        sEditor.putInt(tag, defValue);
        sEditor.commit();
    }
//Incorrect Bracket Closing Removal
}

теперь, когда я выхожу из приложения, он возвращается к теме по умолчанию и не сохраняет int, я просто хочу тему, которую я хочу оставить, даже если я выйду из приложения и вернусь , прошу прощения, если это выглядит немного сложно

1 Ответ

0 голосов
/ 13 июля 2020

НАШЛИ ОТВЕТ !!! сначала вам нужно убедиться, что это в UTILS

public static void onActivityCreateSetTheme(Activity activity, int theme)
    {
        switch (sTheme)
        

должно выглядеть так

public static void onActivityCreateSetTheme(Activity activity, int sTheme)
    {
        switch (sTheme)

оно всегда должно соответствовать части «переключателя»

второе на your activity / mainactivity

вместо использования «SAVE THEME», сохраните ваши темы непосредственно в onclicklistener, как это

@Override
    public void onClick(View v)
    {
        // TODO Auto-generated method stub
        switch (v.getId())
        {
            case R.id.button1:
                Utils.changeToTheme(this, Utils.THEME_DEFAULT);
                defval = 0;
                Reptheme += Utils.THEME_DEFAULT;
                SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
                SharedPreferences.Editor prefEditor = sharedPreferences.edit();
                prefEditor.putInt("Theme", Utils.THEME_DEFAULT);
                prefEditor.apply();
                value.setText("null" +defval);
                Toast.makeText(this, "SAVETHEMEVAL= 0", Toast.LENGTH_SHORT).show();
                break;
            case R.id.button2:
                Utils.changeToTheme(this, Utils.THEME_WHITE);
                defval = 1;
                Reptheme += Utils.THEME_WHITE;
                SharedPreferences sharedPreferences1 = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
                SharedPreferences.Editor prefEditor1 = sharedPreferences1.edit();
                prefEditor1.putInt("Theme", Utils.THEME_WHITE);
                prefEditor1.apply();
                value.setText("null" +defval);
                Toast.makeText(this, "SAVETHEMEVAL= 1", Toast.LENGTH_SHORT).show();
                break;
            case R.id.button3:
                Utils.changeToTheme(this, Utils.THEME_BLUE);
                defval = 2;
                Reptheme += Utils.THEME_BLUE;
                SharedPreferences sharedPreferences2 = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
                SharedPreferences.Editor prefEditor2 = sharedPreferences2.edit();
                prefEditor2.putInt("Theme", Utils.THEME_BLUE);
                prefEditor2.apply();
                value.setText("null" +defval);
                Toast.makeText(this, "SAVETHEMEVAL= 2", Toast.LENGTH_SHORT).show();
                break;
        }

    }

, наконец, используйте «LOAD THEME» как это

public int loadTheme(){
        SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);

        
        int theme = sharedPreferences.getInt("Theme",1); 

        return theme;
    }

, чтобы подвести итог, это моя основная деятельность

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String SHARED_PREF = "sharedPrefs";
    int defval = 1;
    int Reptheme ;
    public Button button11, button22, button33;
    TextView value;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        Utils.onActivityCreateSetTheme(this, loadTheme());

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.button1).setOnClickListener(this);
        findViewById(R.id.button2).setOnClickListener(this);
        findViewById(R.id.button3).setOnClickListener(this);
        value = (TextView) findViewById(R.id.textView4);

        SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
        defval = sharedPreferences.getInt("Theme", + defval);

        value.setText("null" + defval);
    }
    @Override
    public void onClick(View v)
    {
        // TODO Auto-generated method stub
        switch (v.getId())
        {
            case R.id.button1:
                Utils.changeToTheme(this, Utils.THEME_DEFAULT);
                defval = 0;
                Reptheme += Utils.THEME_DEFAULT;
                SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
                SharedPreferences.Editor prefEditor = sharedPreferences.edit();
                prefEditor.putInt("Theme", Utils.THEME_DEFAULT);
                prefEditor.apply();
                value.setText("null" +defval);
                Toast.makeText(this, "SAVETHEMEVAL= 0", Toast.LENGTH_SHORT).show();
                break;
            case R.id.button2:
                Utils.changeToTheme(this, Utils.THEME_WHITE);
                defval = 1;
                Reptheme += Utils.THEME_WHITE;
                SharedPreferences sharedPreferences1 = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
                SharedPreferences.Editor prefEditor1 = sharedPreferences1.edit();
                prefEditor1.putInt("Theme", Utils.THEME_WHITE);
                prefEditor1.apply();
                value.setText("null" +defval);
                Toast.makeText(this, "SAVETHEMEVAL= 1", Toast.LENGTH_SHORT).show();
                break;
            case R.id.button3:
                Utils.changeToTheme(this, Utils.THEME_BLUE);
                defval = 2;
                Reptheme += Utils.THEME_BLUE;
                SharedPreferences sharedPreferences2 = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
                SharedPreferences.Editor prefEditor2 = sharedPreferences2.edit();
                prefEditor2.putInt("Theme", Utils.THEME_BLUE);
                prefEditor2.apply();
                value.setText("null" +defval);
                Toast.makeText(this, "SAVETHEMEVAL= 2", Toast.LENGTH_SHORT).show();
                break;
        }

    }
    public void restartApp() {
        Intent i = new Intent(getApplicationContext(),MainActivity.class);
        startActivity(i);
        finish();
    }
    public int loadTheme(){
        SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);

        //Load theme colorfdsfdssdfsdfsfsd
        int theme = sharedPreferences.getInt("Theme",1); //RED is default color, when nothing is saved yet

        return theme;
    }

}

и мои UTILS. java

import android.app.Activity;
import android.content.Intent;
public class Utils
{
    private static int sTheme;
    public final static int THEME_DEFAULT = 0;
    public final static int THEME_WHITE = 1;
    public final static int THEME_BLUE = 2;
    /**
     * Set the theme of the Activity, and restart it by creating a new Activity of the same type.
     */
    public static void changeToTheme(Activity activity, int theme)
    {
        sTheme = theme;
        activity.finish();
        activity.startActivity(new Intent(activity, activity.getClass()));
    }
    /** Set the theme of the activity, according to the configuration. */
    public static void onActivityCreateSetTheme(Activity activity, int sTheme)
    {
        switch (sTheme)
        {
            default:
            case THEME_DEFAULT:
                activity.setTheme(R.style.AppTheme);
                break;
            case THEME_WHITE:
                activity.setTheme(R.style.Cerv_Theme);
                break;
            case THEME_BLUE:
                activity.setTheme(R.style.Giant_Theme);
                break;
        }
    }
}
...