What context to use with shared preferences in another class?
<p>I can't work out how to use shared preferences in another class that isn't a fragment or anything</p>

<p>Here is my main activity code:</p>

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

<p>And here is a my Backgrounds class:</p>

<pre><code>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];
        }
    }
}
</code></pre>

<p>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:</p>

<p>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</p>

<p>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.</p>