2012-07-02 56 views
1

我有一个类PreferenceClass,它扩展了PreferenceActivity。这个类的代码如下:SharedPreference in non-activity class

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); 

}} 

我也有非活性类Shakelistener它实现SensorListener。这个类的代码如下:

public class Shakelistener implements SensorListener { 
    public void onSensorChanged(int sensor, float[] values) { 
    // Some code 
    }} 

我需要能够从这个非活性类访问喜好,但我不知道如何做到这一点。

编辑

这是我用来访问共享偏好代码:

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(); 

这段代码是给没有错误,但它总是评估举杯“默认选择假” 。

我应该在这种情况下使用哪个PREF_FILE_NAME?

回答

2

在非活动类的构造函数中取一个Context的实例并使用它来调用所有这些方法。

事情是这样的:

public class NonActivityClass implements SensorListener{ 
Context mContext; 
public NonActivtiyClass(Context context) { 
this.mContext = context; 
} 
//Rest of your code 
} 

那么这样做是创建一个类的对象,你Activtiy的onCreate()

NonActivityClass nac = new NonActivityClass(this); 
+0

拉哈夫先生,你能不能给我一个简短的想法我怎么能做到这一点... 或者如果你给我一些关于我的问题的任何教程的链接将是伟大的。 – void

+0

然后我将如何访问共享偏好..? – void

+0

我不会为你编写你的应用程序。使用mContext变量调用您在Activity中使用的所有函数,就像您在那里使用它们一样。 –