views:

87

answers:

1

Hi, 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.

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

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"

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

+1  A: 

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