读取首选项为int抛出异常

时间:2015-03-23 16:28:51

标签: android android-preferences

我试图将存储在首选项中的值读作Int,它抛出了我的classcast异常。这是代码

SharedPreferences prefs = ct.getSharedPreferences("volumepreference", 0);
        SharedPreferences.Editor editor = prefs.edit();

        int Past_phone_audio_mode = -1;

        try
        {
            Past_phone_audio_mode = prefs.getInt("volumestate", -1);
        }
        catch(Exception ee)
        {

        }

我知道我的代码中有什么问题

1 个答案:

答案 0 :(得分:2)

保存首选项int值:

    final SharedPreferences prefs =
        PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

    // Get preference in editor mode
    final SharedPreferences.Editor editor = prefs.edit();

    // Set the Integer value
    editor.putInt("volumestate", 1);

    // Finally, save changes
    editor.apply();