使用共享preferences编辑器 [英] Using shared preferences editor

查看:152
本文介绍了使用共享preferences编辑器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我慢慢地通过一个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();
    }
}

这篇关于使用共享preferences编辑器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆