使用共享偏好编辑器

时间:2011-02-11 09:29:28

标签: android sharedpreferences

我正在慢慢学习Android学习手册,并获得以下代码来分配用户数据:

package com.androidbook.triviaquiz;

import android.app.Activity;
import android.content.SharedPreferences;

public class QuizActivity extends Activity {
    public static final String GAME_PREFERENCES = "GamePrefs";
    SharedPreferences settings = getSharedPreferences(GAME_PREFERENCES, MODE_PRIVATE);
    SharedPreferences.Editor prefEditor = settings.edit();
    prefeditor.putString("UserName", "John Doe"); //**syntax error on tokens**
    prefEditor.putInt("UserAge", 22); //**syntax error on tokens**
    prefEditor.commit();
}

然而,我得到一个错误(用注释表示的行)强调了句点,并说“错位的构造”,并且还强调了“删除这些令牌”的论点。我已经在其他应用程序中以相同的格式看到了这一点,我不明白是什么问题。

3 个答案:

答案 0 :(得分:34)

编辑:当然!这些语句不能直接放在该级别的类中,并且必须位于方法中,如下所示:

public class QuizActivity extends Activity {
    public static final String GAME_PREFERENCES = "GamePrefs";

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        SharedPreferences settings = getSharedPreferences(GAME_PREFERENCES, MODE_PRIVATE);
        SharedPreferences.Editor prefEditor = settings.edit();
        prefEditor.putString("UserName", "John Doe");
        prefEditor.putInt("UserAge", 22);
        prefEditor.putString("Gender", "Male");
        prefEditor.commit();
    }
}

答案 1 :(得分:3)

我想您可能错过了OnCreate()方法,请确保您应该将共享首选项放在OnCreate()方法中...我只是编辑了您的代码通过它

请仔细阅读以下代码

public class A extends Activity {
static SharedPreferences settings;
 public static final String PREFS_NAME = "YourPrefName";

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        settings = getSharedPreferences(PREFS_NAME, 0);
Log.v("UserName"," - "+settings.getString("username","android"));
SharedPreferences.Editor editor = settings.edit();          
            editor.putString("username","Change Android");          
            editor.commit();

Log.v("UserName after changed editing preference key value"," - "+settings.getString("username","android"));


}

}

答案 2 :(得分:0)

只要具有上下文,

SharedPreferences就可以解决onCreate()方法:

SharedPreferences settings = getAplicationContext().getSharedPreferences(GAME_PREFERENCES, MODE_PRIVATE);