保存设置数据具有共享首选项,并在其他活动中使用

发布于 2025-02-10 08:11:11 字数 2986 浏览 2 评论 0原文

我目前正在构建一个测验应用程序,并尝试添加设置活动,其中用户将能够管理某些游戏参数,例如声音(使用切换按钮)或游戏时间。我尝试使用共享的首选项实现它,但出现了问题:退出活动后,切换按钮的状态不会保存,并且似乎共享的偏好功能也无法正常工作。如果有人知道如何解决此问题或如何正确构建此问题,将会感到非常高兴。这是我的代码:

设置活动:

SwitchCompat switchButton;
    ImageView imageViewOn;
    private Context mContext;

public Settings(){}

public Settings(Context mContext) {
    this.mContext = mContext;
}


private String soundState;

public static final String PREFERRENCE = "shared_prefrence";
//public static final boolean TOGGLE_STATE = false;
public static final String SOUND_STATE = "sound state";
public static final String PREFERRENCE_SOUND_ON = "sound_on";
public static final String PREFERENCE_SOUND_OFF = "sound_of";

public String getSoundState() {
    return soundState;
}

public void setSoundState(String soundState) {
    this.soundState = soundState;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings);

    switchButton = findViewById(R.id.switchButton);
    imageViewOn = findViewById(R.id.sound_on);
    loadSound();
            
switchButton.setOnCheckedChangeListener((compoundButton, b) -> {
if(compoundButton.isChecked()){
            soundState = PREFERENCE_SOUND_OFF;
            updateSoundState(soundState);
            imageViewOn.setImageResource(R.drawable.sound_off);


    }
    else{
        soundState = PREFERRENCE_SOUND_ON;
        updateSoundState(soundState);
        imageViewOn.setImageResource(R.drawable.sound_on);
    }
});
}

private void updateSoundState(String soundState) {
    SharedPreferences sharedPreferences = getSharedPreferences(PREFERRENCE,MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(SOUND_STATE,soundState);
    editor.apply();
}

private void loadSound() {
    SharedPreferences sharedPreferences = getSharedPreferences(PREFERRENCE,MODE_PRIVATE);
    sharedPreferences.getString(SOUND_STATE, PREFERRENCE_SOUND_ON);
}

测验活动(触发声音提示的地方)添加相关代码,否则将非常长。如果缺少某些内容,请评论,我补充:

 private  Settings settings; 
 private PlayAudioForAnswers playAudioForAnswers;// class which plays audio


protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quiz);
        setupUI();

        loadPreferences();

        playAudioForAnswers = new PlayAudioForAnswers(this);

    }

private void setupUI(){
            settings = new Settings(this);
    }


`private void loadPreferences()`
{
    
SharedPreferences sharedPreferences = getSharedPreferences(settings.PREFERRENCE, MODE_PRIVATE);
                String sound = sharedPreferences.getString(settings.SOUND_STATE,settings.PREFERRENCE_SOUND_ON);
settings.setSoundState(sound);
 }

if(settings.getSoundState().equals(settings.PREFERRENCE_SOUND_ON))
            playAudioForAnswers.setAudioforAnswer(FLAG);
 // playing the sound cue if the state is on

I'm currently building a quiz app and trying to add Settings activity in which the user will be able to manage some game parameters like sound(using a toggle button) or game time. I tried implementing it using shared preferences but something went wrong: The state of toggle button is not saved after exiting the activity and seems that the shared preferences functionality isn't working correctly either. Will be really happy if someone knows how to fix this, or how to build this correctly. Here is my code:

Settings activity:

SwitchCompat switchButton;
    ImageView imageViewOn;
    private Context mContext;

public Settings(){}

public Settings(Context mContext) {
    this.mContext = mContext;
}


private String soundState;

public static final String PREFERRENCE = "shared_prefrence";
//public static final boolean TOGGLE_STATE = false;
public static final String SOUND_STATE = "sound state";
public static final String PREFERRENCE_SOUND_ON = "sound_on";
public static final String PREFERENCE_SOUND_OFF = "sound_of";

public String getSoundState() {
    return soundState;
}

public void setSoundState(String soundState) {
    this.soundState = soundState;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings);

    switchButton = findViewById(R.id.switchButton);
    imageViewOn = findViewById(R.id.sound_on);
    loadSound();
            
switchButton.setOnCheckedChangeListener((compoundButton, b) -> {
if(compoundButton.isChecked()){
            soundState = PREFERENCE_SOUND_OFF;
            updateSoundState(soundState);
            imageViewOn.setImageResource(R.drawable.sound_off);


    }
    else{
        soundState = PREFERRENCE_SOUND_ON;
        updateSoundState(soundState);
        imageViewOn.setImageResource(R.drawable.sound_on);
    }
});
}

private void updateSoundState(String soundState) {
    SharedPreferences sharedPreferences = getSharedPreferences(PREFERRENCE,MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(SOUND_STATE,soundState);
    editor.apply();
}

private void loadSound() {
    SharedPreferences sharedPreferences = getSharedPreferences(PREFERRENCE,MODE_PRIVATE);
    sharedPreferences.getString(SOUND_STATE, PREFERRENCE_SOUND_ON);
}

Quiz activity (where sound cues are triggered) adding the relevant code, otherwise it will be extremely long. If something is missing please comment, I'll add:

 private  Settings settings; 
 private PlayAudioForAnswers playAudioForAnswers;// class which plays audio


protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quiz);
        setupUI();

        loadPreferences();

        playAudioForAnswers = new PlayAudioForAnswers(this);

    }

private void setupUI(){
            settings = new Settings(this);
    }


`private void loadPreferences()`
{
    
SharedPreferences sharedPreferences = getSharedPreferences(settings.PREFERRENCE, MODE_PRIVATE);
                String sound = sharedPreferences.getString(settings.SOUND_STATE,settings.PREFERRENCE_SOUND_ON);
settings.setSoundState(sound);
 }

if(settings.getSoundState().equals(settings.PREFERRENCE_SOUND_ON))
            playAudioForAnswers.setAudioforAnswer(FLAG);
 // playing the sound cue if the state is on

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

牵你的手,一向走下去 2025-02-17 08:11:11

代码中的顺序错误。
首先,您应该更改声音状态,然后再保存。

    soundState = PREFERENCE_SOUND_OFF;
    updateSoundState(soundState);

相反

    updateSoundState(soundState);
    soundState = PREFERENCE_SOUND_OFF;

,您也没有调用

    soundState = PREFERRENCE_SOUND_ON;;

There is wrong order in your code.
First, you should change the sound state and next save it.

    soundState = PREFERENCE_SOUND_OFF;
    updateSoundState(soundState);

instead

    updateSoundState(soundState);
    soundState = PREFERENCE_SOUND_OFF;

Also you didn't invoke after

    soundState = PREFERRENCE_SOUND_ON;;
分開簡單 2025-02-17 08:11:11

另一个工作良好的练习

您可以将pref与活动分开:

1-共享prefshelper

import android.content.Context;
import android.content.SharedPreferences;    
import static android.content.Context.MODE_PRIVATE;

/**
 * @author Islam
 * @date 10/11/2018
 */

public class SharedPrefsHelper {

    SharedPreferences mSharedPreferences;

    private static final String MY_PREFS = "YOUR_APP";
    
    public SharedPrefsHelper(Context context) {
        mSharedPreferences = context.getSharedPreferences(MY_PREFS, MODE_PRIVATE);
    }

    private static SharedPreferences getPref(Context context) {
        return context.getSharedPreferences(MY_PREFS, Context.MODE_PRIVATE);
    }

    public void clear(Context context) {
        getPref(context).edit().clear().apply();
    }
    
    /**
     * set Load all tasks
     *
     * @param isLoadAllTasks
     */
    public void setIsLoadAllTasks( boolean isLoadAllTasks) {
        mSharedPreferences.edit().putBoolean(Constants.LOAD_ALL_TASKS, isLoadAllTasks).apply();
    }

    /**
     * get Scanner Scanning
     *
     * @return
     */
    public boolean getIsLoadAllTasks() {
        return mSharedPreferences.getBoolean(Constants.LOAD_ALL_TASKS,false);

    }
    
    //endregion

}

,然后创建datamanger类是视图和数据源之间的一层(db || pref)。

2- datamanager

/**
 * @author Islam
 * @date 14/2/2020
 */
public class DataManager {

    private static final String TAG = "DataManager";

    private SharedPrefsHelper mSharedPrefsHelper;

    public DataManager(SharedPrefsHelper sharedPrefsHelper) {
        mSharedPrefsHelper = sharedPrefsHelper;
    }

    //region Settings

    /**
     * set Is Load Tasks
     *
     * @param isLoadTasks
     */
    public void setIsLoadAllTasks( boolean isLoadTasks) {
        mSharedPrefsHelper.setIsLoadAllTasks(isLoadTasks);
    }

    /**
     * get Is Load Tasks
     *
     * @return
     */
    public boolean getIsLoadAllTasks() {
        return mSharedPrefsHelper.getIsLoadAllTasks();
    }
    
    //endregion

}

3-设置活动

在ongreate中调用此事

 @Override
    protected void initUIAndActions() {
        // fetch current status 
        binding.switchLoadAll.setChecked(dataManager.getIsLoadAllTasks());
        // checking Listener
        binding.switchLoadAll.setOnCheckedChangeListener((buttonView, isChecked) -> {
            //save is Load all Tasks to Prefs
            dataManager.setIsLoadAllTasks(isChecked);
        });

    }

Another Working Good Practice

You can separate Pref from an activity :

1- SharedPrefsHelper

import android.content.Context;
import android.content.SharedPreferences;    
import static android.content.Context.MODE_PRIVATE;

/**
 * @author Islam
 * @date 10/11/2018
 */

public class SharedPrefsHelper {

    SharedPreferences mSharedPreferences;

    private static final String MY_PREFS = "YOUR_APP";
    
    public SharedPrefsHelper(Context context) {
        mSharedPreferences = context.getSharedPreferences(MY_PREFS, MODE_PRIVATE);
    }

    private static SharedPreferences getPref(Context context) {
        return context.getSharedPreferences(MY_PREFS, Context.MODE_PRIVATE);
    }

    public void clear(Context context) {
        getPref(context).edit().clear().apply();
    }
    
    /**
     * set Load all tasks
     *
     * @param isLoadAllTasks
     */
    public void setIsLoadAllTasks( boolean isLoadAllTasks) {
        mSharedPreferences.edit().putBoolean(Constants.LOAD_ALL_TASKS, isLoadAllTasks).apply();
    }

    /**
     * get Scanner Scanning
     *
     * @return
     */
    public boolean getIsLoadAllTasks() {
        return mSharedPreferences.getBoolean(Constants.LOAD_ALL_TASKS,false);

    }
    
    //endregion

}

Then create DataManger Class to be a layer between view and data source (DB || Pref) .

2- DataManager

/**
 * @author Islam
 * @date 14/2/2020
 */
public class DataManager {

    private static final String TAG = "DataManager";

    private SharedPrefsHelper mSharedPrefsHelper;

    public DataManager(SharedPrefsHelper sharedPrefsHelper) {
        mSharedPrefsHelper = sharedPrefsHelper;
    }

    //region Settings

    /**
     * set Is Load Tasks
     *
     * @param isLoadTasks
     */
    public void setIsLoadAllTasks( boolean isLoadTasks) {
        mSharedPrefsHelper.setIsLoadAllTasks(isLoadTasks);
    }

    /**
     * get Is Load Tasks
     *
     * @return
     */
    public boolean getIsLoadAllTasks() {
        return mSharedPrefsHelper.getIsLoadAllTasks();
    }
    
    //endregion

}

3- Setting Activity

call this in OnCreate

 @Override
    protected void initUIAndActions() {
        // fetch current status 
        binding.switchLoadAll.setChecked(dataManager.getIsLoadAllTasks());
        // checking Listener
        binding.switchLoadAll.setOnCheckedChangeListener((buttonView, isChecked) -> {
            //save is Load all Tasks to Prefs
            dataManager.setIsLoadAllTasks(isChecked);
        });

    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文