如何使用共享preferences如何使用、preferences

2023-09-12 22:06:47 作者:◇﹏妄想者βмeι痕迹

我是新的Andr​​oid开发 - 采用了一本书叫将由Sams Android应用开发在24小时内。跟着它,但迄今为止卡住尝试使用共享preferences。

I'm new to android development - using a book called Sams Teach Yourself Android Application Development in 24 hours. Followed it so far but got stuck trying to use SharedPreferences.

在文件夹中的src / com.androidbook.triviaquiz我有一个名为QuizActivity文件,在里面我已经得到了以下内容:

In the folder src/com.androidbook.triviaquiz I've got a file called QuizActivity, in it I've got the following:

package com.androidbook.triviaquiz;

import android.app.Activity;
import android.os.Bundle;
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", "JaneDoe");
    prefEditor.putInt("UserAge", 22);
    prefEditor.commit();
}

这是什么书告诉我使用,但它在以下几点返回错误:     在下面 。第2 prefEditor陈述后,     根据(用户名,JaneDoe)     根据(UserAge,22);     并在承诺

This is what the book tells me to use, but it returns errors at the following points: under the "." after the first 2 prefEditor statements, under ("UserName", "JaneDoe") under ("UserAge", 22); and under "commit"

我看的网站寻求帮助负载,但似乎都使用相同的code。我究竟做错了什么?

I've looked on loads of websites for help but all seem to use the same code. What am I doing wrong?

推荐答案

尝试把它在你的onCreate()。此外, getDefaultShared preferences()更容易:

Try putting it in your onCreate(). Also, getDefaultSharedPreferences() is easier:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    // Access the default SharedPreferences
    SharedPreferences preferences = 
    PreferenceManager.getDefaultSharedPreferences(this);
    // The SharedPreferences editor - must use commit() to submit changes
    SharedPreferences.Editor editor = preferences.edit();

    // Edit the saved preferences
    editor.putString("UserName", "JaneDoe");
    editor.putInt("UserAge", 22);
    editor.commit();
}