开发者

Sharedpreferences - crashes on startup

开发者 https://www.devze.com 2023-03-22 08:49 出处:网络
I\'m trying to write an activity that would be able to both write and read sharedpreferences data. I initiate SharedPreferences at the beginning

I'm trying to write an activity that would be able to both write and read sharedpreferences data.

I initiate SharedPreferences at the beginning

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

Then this function writes an int to SP and call another function.

public void SetHue(int i)
{
    SharedPreferences.Editor editor = preferences.edit();
    editor.putInt("storedInt", i); // value to store
    editor.commit();
    ApplyHue();
}

this other function should read that int from SP...

开发者_StackOverflow中文版
    public void ApplyHue()
    {   
    int hueInt = preferences.getInt("storedInt", 0);
    /// adjust background image hue according to hueInt.
    }

I can't simply pass this int from one function to another, because I need other activities to be able to run ApplyHue() function, which should use hueInt from memory.

What do you think might be causing it to crash?

Thanks!


I think you wrote this line in the class before your onCreate method.

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

Decalare SharedPreferences preferences; in the class and then in onCreate

preferences = PreferenceManager.getDefaultSharedPreferences(this);

Hopefully your problem will be solved

0

精彩评论

暂无评论...
验证码 换一张
取 消