Android - How do I get sharedpreferences from another activity?
Asked Answered
T

11

41

In my app there is a button (activity1). When user clicks it, I want no sound in the game. I thought I should do this by using sharedpreferences in activity1 in the onClick method of the button:

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

The sound and the game starts in another activity (activity2). I need to read the set sharedpreferences there, but I don't know how to do it.

Thanks

Edit

I have left this line out:

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

Based on your help in the Activity2.class I read the preferences like this:

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. In Activity1.class i click on the button to set the "sound" to "1".
  2. I click on another btn that opens Activity2.class where I always get always "0" in the Toast msg.
Thought answered 31/5, 2011 at 10:20 Comment(0)
H
77

Use the following functions to add shared preferences and to fetch the saved values from all activities.

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.apply(); // or editor.commit() in case you want to write data instantly
}

public static String getDefaults(String key, Context context) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    return preferences.getString(key, null);
}
Henig answered 31/5, 2011 at 10:30 Comment(2)
how can I use these functions to access the shared preference value?Orrin
PreferenceManager is now deprecatedKennakennan
C
19

In Activity1 while saving preferences use:

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

In Activity2 while retrieving shared values use :

SharedPreferences mPrefs = getSharedPreferences("IDvalue",0);    
String str = mPrefs.getString("sound", "");    
if (str.equals("1")) {    
     // Do what you want    
} else {    
    // Do what you want
}
Cima answered 12/6, 2012 at 6:56 Comment(0)
T
14

You can save it one activity:

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

And get it from other activity:

final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext()); 
String value=(mSharedPreference.getString("NameOfShared", "Default_Value"));
Tainataint answered 24/12, 2013 at 9:3 Comment(0)
Q
2
SharedPreferences myPrefs = getSharedPreferences("filename", MODE_PRIVATE);         
String ipAdrs=myPrefs.getString("key", "");

if the key doesnot hav any value inside it it wii give the default value that u hava give in value ("key", "")

Quittance answered 31/5, 2011 at 10:29 Comment(0)
F
2

So easy! but keep one thing in mind you have to define Preferences name public static in the activity where you creating like
public static String Preference = "yourPreferenceName";

and then call in another activity like this

SharedPreferences myPreferences =getSharedPreferences("YourprefereneName",MODE_PRIVATE)
Freida answered 26/9, 2017 at 23:53 Comment(0)
S
2

create class for shared preference

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

    }

}

and use this class any activity and fragment and store data in share preference easily

Stearne answered 5/2, 2019 at 13:56 Comment(0)
M
1

First create method in MainActivity for geting Context:

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

and

use this in every Class you want:

MainActivity mContext = new MainActivity();
        SharedPreferences sharedPrefs = 
PreferenceManager.getDefaultSharedPreferences(mContext.getContext());            
Melioration answered 14/11, 2017 at 22:59 Comment(0)
P
0
SharedPrefernces prefs = getPreferences();
String sound = prefs.getString("sound");

Ensure, you have mentioned the same file name for the preferences file.

Photochemistry answered 31/5, 2011 at 10:25 Comment(0)
A
0

Use this inside your public class MainActivity extends AppCompatActivity (or whatever)

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

Then use these functions with:

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

Functions getDefaults return null if key doesn't exist

Athwart answered 6/11, 2019 at 21:30 Comment(0)
D
0

Suppose if you are creating a different class for SharedPreference then if you want to get the preference value only by one activity the pass activity in constructor. If you want to access from more than one activity the pass context.

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

like this. While calling it from a different activity just get the context of that activity and while creating object of sharedpreference class pass that context.Then you can make changes to the preference or even access saves data from there.

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

Hope it helps.

Dimphia answered 25/1, 2020 at 9:14 Comment(0)
K
0

Solution in Kotlin

Set preferences in Activity1:

fun setPref(key: String, value: String) {
    val prefs = getSharedPreferences("your_prefs_name", Context.MODE_PRIVATE)
    val editor = prefs.edit()
    editor.putString(key, value)
    editor.apply()
}

Get preferences in Activity2:

fun getPrefs(key: String): String? {
    val prefs = getSharedPreferences("your_prefs_name", Context.MODE_PRIVATE)
    return prefs.getString(key, "default_value")
}

Instead of String values you can also put into shared preferences other primitives: https://developer.android.com/reference/android/content/SharedPreferences.Editor

Kennakennan answered 10/5, 2022 at 14:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.