Android - 如何从其他活动获得共享偏好?

时间:2011-05-31 10:20:52

标签: android sharedpreferences

在我的应用中有一个按钮(activity1)。当用户点击它时我想在游戏中没有声音。我想我应该通过在按钮的onClick方法中使用activity1中的sharedpreferences来做到这一点:

SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("sound","1");
editor.commit();

声音和游戏从另一个活动(activity2)开始。我需要阅读那里的set sharedpreferences,但我不知道该怎么做。

由于

修改

我离开了这条线:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Activity1.this);

根据你在Activity2.class中的帮助,我读了这样的偏好:

SharedPreferences myPrefs = getSharedPreferences("Activity1", MODE_PRIVATE);  //Activity1.class
String ifsound = myPrefs.getString("sound","");

 if (ifsound.equals("1"))
 {
     Toast.makeText(Activity1.this, "1", Toast.LENGTH_LONG).show();
 }
 else
 {
      Toast.makeText(Activity1.this, "0", Toast.LENGTH_LONG).show();
 }
  1. 在Activity1.class中,我点击按钮将“声音”设置为“1”。
  2. 我点击另一个打开Activity2.class的btn,我总是在Toast msg中得到“0”。

10 个答案:

答案 0 :(得分:65)

使用以下功能添加共享首选项并从所有活动中获取保存的值。

public static void setDefaults(String key, String value, Context context) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString(key, value);
    editor.commit();
}

public static String getDefaults(String key, Context context) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    return preferences.getString(key, null);
}

答案 1 :(得分:13)

在Activity1中保存首选项时使用:

SharedPreferences mPrefs = getSharedPreferences("IDvalue", 0);    
//Give any name for //preference as I have given "IDvalue" and value 0.    
SharedPreferences.Editor editor = mPrefs.edit();    
editor.putString(key, value);     
// give key value as "sound" you mentioned and value what you // to want give as "1" in you mentioned    
editor.commit();

在Activity2中,在检索共享值时使用:

SharedPreferences mPrefs = getSharedPreferences("IDvalue",0);    
String str = mPrefs.getString("sound", "");    
if (str.equals("1")) {    
     // Do what you want    
} else {    
    // Do what you want
}

答案 2 :(得分:11)

您可以将其保存为一项活动:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = prefs.edit();
editor.putString("NameOfShared", "Value");
editor.commit();

从其他活动中获取:

final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext()); 
String value=(mSharedPreference.getString("NameOfShared", "Default_Value"));

答案 3 :(得分:2)

SharedPreferences myPrefs = getSharedPreferences("filename", MODE_PRIVATE);         
String ipAdrs=myPrefs.getString("key", "");

如果密钥内部没有任何值,则wii给出u hava赋值的默认值("key", "")

答案 4 :(得分:0)

SharedPrefernces prefs = getPreferences();
String sound = prefs.getString("sound");

请确保您已为首选项文件提及相同的文件名。

答案 5 :(得分:0)

太容易了!但请注意,您必须在创建的活动中定义首选项名称public static printf("Address of first element of a = %p\n", p);

然后调用另一个这样的活动

public static String Preference = "yourPreferenceName";

答案 6 :(得分:0)

首先在MainActivity中创建方法,用于生成上下文:

 public  Context getContext(){
        Context mContext = MainActivity.this;
        return mContext;
    }

在你想要的每个班级中使用它:

MainActivity mContext = new MainActivity();
        SharedPreferences sharedPrefs = 
PreferenceManager.getDefaultSharedPreferences(mContext.getContext());            

答案 7 :(得分:0)

创建共享首选项的类

package android.com.be_uniquenative26_dec_2018.beUniqSmartit.util;

import android.com.be_uniquenative26_dec_2018.R;
import android.content.Context;
import android.content.SharedPreferences;

import java.util.Map;
import java.util.Set;

/**
 * Created by android on 2/2/19.
 */

public class SessionSecuredPreferences implements SharedPreferences {

    private SharedPreferences sharedPref;
    protected Context context;

    public SessionSecuredPreferences(Context context, SharedPreferences delegate) {
        this.sharedPref = delegate;
        this.context = context;
    }

    public SessionSecuredPreferences(Context context) {
        this.sharedPref = context.getSharedPreferences ( StringUtil.getStringForID ( R.string.app_name ), Context.MODE_PRIVATE );
        this.context = context;
    }

    @Override
    public Map <String, ?> getAll() {
        return this.sharedPref.getAll ( );
    }

    public Editor edit() {
        return new Editor ( );
    }

    @Override
    public boolean getBoolean(String key, boolean defValue) {
        return this.sharedPref.getBoolean ( key, defValue );
    }

    @Override
    public float getFloat(String key, float defValue) {
        return this.sharedPref.getFloat ( key, defValue );
    }

    @Override
    public int getInt(String key, int defValue) {
        return this.sharedPref.getInt ( key, defValue );
    }

    @Override
    public long getLong(String key, long defValue) {
        return this.sharedPref.getLong ( key, defValue );
    }

    @Override
    public String getString(String key, String defValue) {
        return this.sharedPref.getString ( key, defValue );
    }

    @Override
    public Set <String> getStringSet(String key, Set <String> defValues) {
        return this.sharedPref.getStringSet ( key, defValues );
    }

    @Override
    public boolean contains(String s) {
        return this.sharedPref.contains ( s );
    }

    @Override
    public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener onSharedPreferenceChangeListener) {
        this.sharedPref.registerOnSharedPreferenceChangeListener ( onSharedPreferenceChangeListener );
    }

    @Override
    public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener onSharedPreferenceChangeListener) {
        this.sharedPref.unregisterOnSharedPreferenceChangeListener ( onSharedPreferenceChangeListener );
    }

    public class Editor implements SharedPreferences.Editor {

        protected SharedPreferences.Editor editor;

        public Editor() {
            this.editor = SessionSecuredPreferences.this.sharedPref.edit ( );
        }

        @Override
        public Editor putBoolean(String key, boolean value) {
            this.editor.putBoolean ( key, value );
            return this;
        }

        @Override
        public Editor putFloat(String key, float value) {
            this.editor.putFloat ( key, value );
            return this;
        }

        @Override
        public Editor putInt(String key, int value) {
            this.editor.putInt ( key, value );
            return this;
        }

        @Override
        public Editor putLong(String key, long value) {
            this.editor.putLong ( key, value );
            return this;
        }

        @Override
        public Editor putString(String key, String value) {
            this.editor.putString ( key, value );
            return this;
        }

        @Override
        public Editor putStringSet(String key, Set <String> values) {
            this.editor.putStringSet ( key, values );
            return this;
        }

        @Override
        public void apply() {
            this.editor.apply ( );
        }

        @Override
        public Editor clear() {
            this.editor.clear ( );
            return this;
        }

        @Override
        public boolean commit() {
            return this.editor.commit ( );
        }

        @Override
        public Editor remove(String s) {
            this.editor.remove ( s );
            return this;
        }

    }

}

并使用此类的任何活动和片段 并轻松按共享首选项存储数据

答案 8 :(得分:0)

在公共类MainActivity中使用它扩展AppCompatActivity(或其他任何方法)

public static void setDefaults(String key, String value, Context context) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString(key, value);
    editor.commit();
}

public static String getDefaults(String key, Context context) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    return preferences.getString(key, null);
}

然后将这些功能用于:

String name = getDefaults("key_name", getApplicationContext());
setDefaults("key_name", "Matthew", getApplicationContext());

如果键不存在,则函数getDefaults返回null

答案 9 :(得分:0)

假设如果要为SharedPreference创建一个不同的类,那么如果您想仅通过一个活动(构造函数中的pass活动)获得首选项值。如果要从多个活动中访问,则传递上下文。

public Prefs_Name(Context context) {
        this.preferences = PreferenceManager.getDefaultSharedPreferences(context);
    }

像这样。 从另一个活动调用它时,只需获取该活动的上下文,并在创建sharedpreference类的对象时传递该上下文。然后,您可以更改首选项,甚至可以从那里保存访问数据。

 PreferenceManager.getDefaultSharedPreferences(context);
    prefs_name=new Prefs_Name(context);

希望有帮助。