Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
534 views
in Technique[技术] by (71.8m points)

android - Using shared preferences editor

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Edit: 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.putString("Gender", "Male");
        prefEditor.commit();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...