如何使用存储在非活动类的sharedpreferences中的数据

时间:2012-07-10 08:51:26

标签: android sharedpreferences

我正在尝试从非活动类中获取并更新存储在sharedpreferences xml文件中的数据。但我不知道如何从android中的非活动类到达存储在sharedPreferences中的数据。在我的活动中class i可以在sharedprefences中存储数据,我也可以在我的activiy类中检索这些数据。但是,我无法从非活动类中检索这些数据。我的代码如下。谢谢你...

    mSharedPrefs = getSharedPreferences("storageforfavorite", 0);
    mPrefsEditor = mSharedPrefs.edit();

    for(int i= 0;i<names.size();i++){
        mPrefsEditor.putString(indexForFav[i],"0"); 
    }
    mPrefsEditor.commit();

    for(int i=0;i<names.size();i++){
        String keyForFav=mSharedPrefs.getString(indexForFav[i], "2");
        valueForFav.add(keyForFav);
    }

2 个答案:

答案 0 :(得分:5)

密钥可以访问Context对象。 因此,如果要在对象内使用sharedPreferences,可能应该在类构造函数中传递Context对象。这样做可以做到这一点:

SharedPreferences prefs = context.getSharedPreferences();

答案 1 :(得分:1)

您必须传递Context才能从非SharedPreferences班级访问Activity

示例:

// mContext => Context-object passed from calling Activity
SharedPreferences mSharedPrefs = mContext.getSharedPreferences("storageforfavorite", 0);