Reputation: 21893
I just want to store username and password when a checkbox is clicked. I don't need a context menu and a preference screen. how can I have a simple method that store those values in my login class?
Upvotes: 1
Views: 242
Reputation: 10785
to store a string value(for example) in the application shared prefs, from any activity derived class:
SharedPreferences prefs = getSharedPreferences(PEFS_DESIRED_NAME, MODE_PRIVATE);
prefs.edit().putString("password", mPasswordValue).commit();
to load it next time:
SharedPreferences prefs = getSharedPreferences(PEFS_DESIRED_NAME, MODE_PRIVATE);
mPasswordValue = prefs.getString("password", DEFAULT_VALUE_IF_NOT_EXISTS);
Upvotes: 5
Reputation: 116382
you don't have to use the preferences screen .
here's a sample code (should be run in an activity , service , or whatever context that you have ) :
reading:
SharedPreferences sharedPreferences=getSharedPreferences("settings",Context.MODE_PRIVATE);
String userName=sharedPreferences.getString("userName",null);
String password=sharedPreferences.getString("password",null);
writing:
Editor editor=getSharedPreferences("settings",Context.MODE_PRIVATE).edit();
editor.putString("userName",userName);
editor.putString("password",password);
editor.commit()
for the "settings" , i suggest using a unique constant string , like the activity's class name . of course you can use anything you wish ...
Upvotes: 3