使用共享preferences编辑器编辑器、preferences

由网友(别跟自己过不去)分享简介:我慢慢地通过一个Android学习书的工作,并给予下列code到指定用户数据:I'm slowly working through an Android learning book and was given the following code to assign user data:package com.an...

我慢慢地通过一个Android学习书的工作,并给予下列code到指定用户数据:

I'm slowly working through an Android learning book and was given the following code to assign user data:

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();
}

不过,我得到了突出的时期,并说错位结构,也即强调的论点说:删除这些令牌错误(并评论表示行)。我已经看到了相同的格式的其他应用程序完成这件事,我不明白什么是错的。

However, I get an error (lines indicated with comments) that underlines the period and says "misplaced construct" and also that underlines the arguments saying "delete these tokens". I have seen this done in other applications in the same format, I don't understand what is wrong.

推荐答案

编辑:当然!这些声明不能直接放入类在这一水平,并且必须是一个方法中,这样的事情:

Of course! Those statements cannot be put directly into the class at that level and must be inside a method, something like this:

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.commit();
    }
}
阅读全文

相关推荐

最新文章