Use sharedpreferences inside class

若如初见. 提交于 2019-12-12 04:23:02

问题


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
}


来源:https://stackoverflow.com/questions/18768926/use-sharedpreferences-inside-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!