android – Using shared preferences editor-ThrowExceptions

Exception or error:

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.

How to solve:

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

###

I think you may missed up OnCreate() method ,let be sure you should place the shared preference in your OnCreate() method… i just edited your code go through it

please go through the code…below

public class A extends Activity {
static SharedPreferences settings;
 public static final String PREFS_NAME = "YourPrefName";

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        settings = getSharedPreferences(PREFS_NAME, 0);
Log.v("UserName"," - "+settings.getString("username","android"));
SharedPreferences.Editor editor = settings.edit();          
            editor.putString("username","Change Android");          
            editor.commit();

Log.v("UserName after changed editing preference key value"," - "+settings.getString("username","android"));


}

}

###

SharedPreferences will work out side a onCreate() method as long as it has a context:

SharedPreferences settings = getAplicationContext().getSharedPreferences(GAME_PREFERENCES, MODE_PRIVATE);

Leave a Reply

Your email address will not be published. Required fields are marked *