John O'Neil
John O'Neil

Reputation: 365

What context to use with shared preferences in another class?

I can't work out how to use shared preferences in another class that isn't a fragment or anything

Here is my main activity code:

public class MainActivity extends AppCompatActivity {

    Backgrounds backs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        backs = new Backgrounds(this);
        bg = (LinearLayout) findViewById(R.id.background);
        bg.setBackgroundColor(getResources().getColor(backs.getBackground()));
        }
}

And here is a my Backgrounds class:

public class Backgrounds {
    Integer colors[] = {
            R.color.red,
            R.color.pink,
            R.color.purple,
    };

    private context;
    SharedPreferences sharedPref = context.getSharedPreferences("file", 0);
    SharedPreferences.Editor editor = sharedPref.edit();
    int i = sharedPref.getInt("background", -1);
    public Backgrounds(Context context)
    {
        this.context = context
    }
    public int getBackground()
    {
        i++;
        try{
            editor.putInt("factIndex", i);
            editor.commit();
            return colors[i];
        }catch (Exception e){
            i = 0;
            editor.putInt("factIndex", i);
            editor.commit();
            return colors[i];
        }
    }
}

I have tried this many ways. I am almost certain it is a problem with the context part of the code as I get this error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference

I have also tried it using context.getApplicationContext() but the error was similar. I thought it might be because I needed to move the assinging of the Backs object into the onCreate() but that still doesn't work. I have cleaned the project and synced files with gradle but the program still crashes before it loads. The code works perfectly when removing any SharedPrefrences stuff.

Upvotes: 2

Views: 4617

Answers (4)

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

You are using the context before receiving it mean outside constructor or say before constructor get executed so do it like

    SharedPreferences sharedPref ;
    SharedPreferences.Editor editor;
    int i = sharedPref.getInt("background", -1);

    // before this , you cannot use the context reference ,it will be null
    public Backgrounds(Context context)
    {
       this.context = context
       // receive the context here and now you can safely use it
       sharedPref = context.getSharedPreferences("file", 0)
       editor = sharedPref.edit() 
  } 

Upvotes: 1

Alexander Pereverzev
Alexander Pereverzev

Reputation: 235

Don't save Context as a field it's a potential memory leak. The best way it's like @Shanmugavel GK wrote below, create a static methods or at least make

this.context = context.getApplicationContext();

Upvotes: 1

Shanmugavel GK
Shanmugavel GK

Reputation: 368

This is for Common class for Preference.

public class Preference {
    private final static String PREF_FILE = "PREF";

    /**
     * Set a string shared preference
     *
     * @param key   - Key to set shared preference
     * @param value - Value for the key
     */
    public static void setSharedPreferenceString(Context context, String key, String value) {
        SharedPreferences settings = context.getSharedPreferences(PREF_FILE, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(key, value);
        editor.apply();
    }

    /**
     * Set a integer shared preference
     *
     * @param key   - Key to set shared preference
     * @param value - Value for the key
     */
    public static void setSharedPreferenceInt(Context context, String key, int value) {
        SharedPreferences settings = context.getSharedPreferences(PREF_FILE, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt(key, value);
        editor.apply();
    }

    /**
     * Set a Boolean shared preference
     *
     * @param key   - Key to set shared preference
     * @param value - Value for the key
     */
    public static void setSharedPreferenceBoolean(Context context, String key, boolean value) {
        SharedPreferences settings = context.getSharedPreferences(PREF_FILE, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean(key, value);
        editor.apply();
    }

    /**
     * Get a string shared preference
     *
     * @param key      - Key to look up in shared preferences.
     * @param defValue - Default value to be returned if shared preference isn't found.
     * @return value - String containing value of the shared preference if found.
     */
    public static String getSharedPreferenceString(Context context, String key, String defValue) {
        SharedPreferences settings = context.getSharedPreferences(PREF_FILE, 0);
        return settings.getString(key, defValue);
    }

    /**
     * Get a integer shared preference
     *
     * @param key      - Key to look up in shared preferences.
     * @param defValue - Default value to be returned if shared preference isn't found.
     * @return value - String containing value of the shared preference if found.
     */
    public static int getSharedPreferenceInt(Context context, String key, int defValue) {
        SharedPreferences settings = context.getSharedPreferences(PREF_FILE, 0);
        return settings.getInt(key, defValue);
    }

    /**
     * Get a boolean shared preference
     *
     * @param key      - Key to look up in shared preferences.
     * @param defValue - Default value to be returned if shared preference isn't found.
     * @return value - String containing value of the shared preference if found.
     */
    public static boolean getSharedPreferenceBoolean(Context context, String key, boolean defValue) {
        SharedPreferences settings = context.getSharedPreferences(PREF_FILE, 0);
        return settings.getBoolean(key, defValue);
    }
}

this is usage for Get and Set Preference

Preference.setSharedPreferenceString(this, "Key", "Value")
Preference.getSharedPreferenceString(this, "Key", "default_Value")

You can use anywhere in the application.

Upvotes: 4

Piyush
Piyush

Reputation: 18923

Move your this code

SharedPreferences sharedPref = context.getSharedPreferences("file", 0);
SharedPreferences.Editor editor = sharedPref.edit();

after

SharedPreferences sharedPref;
SharedPreferences.Editor editor
public Backgrounds(Context context)
{
    this.context = context
    sharedPref = context.getSharedPreferences("file", 0);
    editor = sharedPref.edit();
}

because its initialing here. before this it is null.

Upvotes: 1

Related Questions