简体   繁体   中英

How to access a string value of a shared preference from a method of another class

The title is the question. I have saved a string value in the shared preference and i was able to access it in that class. Now i want to access it from a another method of another class. Tried some ways but didn't work.

The class that saves string inside shared preference:

http://pastie.org/4254511

Class trying to retrieve the username that was previously save in shared preference:

public class testSharedPrefernce extends Activity{
TextView tv;
 @Override
    protected void onCreate(Bundle savedInstanceState){
     super.onCreate(savedInstanceState);
     setContentView(R.layout.lo);
     tv = (TextView)findViewById(R.id.textView1);
     SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
     String name = myPrefs.getString("NAME", "YourName");
     tv.setText(name);
 }

}

Just make a constructor of that class which accepts the context.As example:

class Abc
{
    Context contaxt;
    public Abc(Context context)
    {
        this.context = context;
    }
}
..........
..........
// now use this context to SharedPref..
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);

Use below code for get preferences.

SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
boolean cbvalue = myPrefs.getBoolean("CHECKBOX", false);
String name = myPrefs.getString("NAME", "YourName");
String paswrd =myPrefs.getString("PASSWORD", "123");

Use below code for save preferences.

SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();

prefsEditor.putString("NAME", "Dipak");
prefsEditor.putString("PASSWORD", "Dipak123");
prefsEditor.commit();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM