REZA
REZA

Reputation: 73

How to use Shared preferences in my class

I want to use Shared preferences in Meghdar.javathis is my code but it does not work.

public class Meghdar {

private final Context context;
SharedPreferences sp;
String Text;

public Meghdar(Context context) {
    super();
    this.context = context;
    sp = context.getApplicationContext ().getSharedPreferences("AppPreferences", Activity.MODE_PRIVATE);

    Text = sp.getString ("text",null);
}}

Upvotes: 1

Views: 592

Answers (5)

Mahdi Nouri
Mahdi Nouri

Reputation: 1389

Change it to this:

public class Meghdar {

    SharedPreferences sp;
    String text;

    public Meghdar(Context context) {
        super();
        sp = context.getSharedPreferences("AppPreferences", Context.MODE_PRIVATE);

        text = sp.getString("text", "");
    }
}

Upvotes: 1

REZA
REZA

Reputation: 73

Thanks a lot i change it but it does not work. i also use this code in my MainActivity.java maybe the error is here please see it (it the force stop)

String a = editTextM.getText ().toString ();
                sharedPreferences = getApplicationContext ().getSharedPreferences ("userB", 0);
                editor = sharedPreferences.edit ();
                editor.putString ("text", a);
                editor.commit ();
                Toast.makeText (getApplicationContext (), "با موفقیت ذخیره شد.", Toast.LENGTH_LONG).show ();
                finish ();
                startActivity (getIntent ());

Upvotes: 0

Vyacheslav
Vyacheslav

Reputation: 27221

an example for three methods:

public static SharedPreferences getPreferences(Context c){
    if (settings == null) {
        settings = PreferenceManager.getDefaultSharedPreferences(c.getApplicationContext());
    }
    return settings;
}
public static void save(int ndx, String val) {
    SharedPreferences st = settings;
    SharedPreferences.Editor editor = st.edit();
    editor.putString(CTBASE + ndx, val);
    editor.commit();

}
public static String get(int ndx) {
    return settings.getString(CTBASE + ndx, DEFVAL);
}

Upvotes: 0

Tural Mehdiyev
Tural Mehdiyev

Reputation: 86

just remove getApplicationContext()

context is for getActivity and getApplicationContext.

You mustn't use both of them at same time.

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);

in your code it should be like this

sp = context.getSharedPreferences("AppPreferences",context.MODE_PRIVATE);

Upvotes: 0

Anjal Saneen
Anjal Saneen

Reputation: 3219

Change to like this :

sp = context.getSharedPreferences("AppPreferences", Context.MODE_PRIVATE);

Upvotes: 0

Related Questions