Reputation: 36703
I have a class PreferenceClass
which extends PreferenceActivity
. The code for this class is as follows:
public class Preferenceclass extends PreferenceActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main2);
addPreferencesFromResource(R.layout.preferences);
}}
I also have a non activity class Shakelistener
which implements SensorListener
. The code for this class is as follows:
public class Shakelistener implements SensorListener {
public void onSensorChanged(int sensor, float[] values) {
// Some code
}}
I need to be able to access the preferences from in this non-activity class, but I'm not sure how to do this.
EDIT
This is the code I use to access the shared preferences:
String PREF_FILE_NAME = "preferences";
SharedPreferences pref = mContext.getSharedPreferences(PREF_FILE_NAME , Context.MODE_PRIVATE);
String myListPreference = pref.getString("listpref", "default choice");
boolean cb = pref.getBoolean("checkBox", false);
Toast.makeText(mContext, myListPreference+"-"+cb, Toast.LENGTH_LONG).show();
This code is giving no errors, but it always evaluates the toast to "default choice-false".
Which PREF_FILE_NAME should I be using in this case?
Upvotes: 1
Views: 2022
Reputation: 82533
Take an instance of Context in the constructor of your non-activity class and use that to call all such methods.
Something like this:
public class NonActivityClass implements SensorListener{
Context mContext;
public NonActivtiyClass(Context context) {
this.mContext = context;
}
//Rest of your code
}
Then do this to create an object of that class in your Activtiy's onCreate()
:
NonActivityClass nac = new NonActivityClass(this);
Upvotes: 2