Use sharedpreferences inside class

2019-08-29 02:58发布

问题:

I am having a problem using my shared preferences inside a class. My code and program flow:

I have a Spinner inside my activity.I am implementing my own OnItemSelectedListener like this:

MyOnItemSelectedListener.java

public class MyOnItemSelectedListener implements OnItemSelectedListener  {
     SharedPreferences pref;
     Editor editor;

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        //parent.setSelection(7);
        Toast.makeText(parent.getContext(), "Selected Country : " + parent.getItemIdAtPosition(pos), Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
}

I call the above class from my activity like this:

spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new MyOnItemSelectedListener());

So far so good.What i want is to save the selected item on spinner1 to the user's preferences(and set it from saved value).

Inside an activity i am using my shared prefs like this:

pref = getApplicationContext().getSharedPreferences("MyPref", 0);

but inside the class the context doesn't exists! Any help retrieving/saving pref when the user selects an item on the spinner?

Thank you!

回答1:

Create a constructor for your listener and pass a Context to it:

public class MyOnItemSelectedListener implements OnItemSelectedListener  {
    SharedPreferences pref;
    Editor editor;

    public MyOnItemSelectedListener(Context context) {
        pref = context.getSharedPreferences("MyPref", 0);
    }

    // rest of your code
}