I am trying to use SharedPreferences to register account for my apps but it is always return different value from what I have saved at saveSipAccount in the first time when i try to get SharedPreferences at getSipAccount . It is only working when i restart my apps.
I am newbie for android and SIP so please help me, thank you so much!
This is my code
private static String PREFERENCE_NAME = "voip_demo_pref";
private static String SIP_DOMAIN_KEY = "sip_domain";
private static String SIP_PROXY_KEY = "proxy";
private static String SIP_USER_KEY = "user";
private static String SIP_PASSWORD_KEY = "password";
public void saveSipAccount(Context context, String domain, String proxy, String user, String password) {
SipAccount account = new SipAccount(domain, proxy, user, password);
saveSipAccount(context, account);
}
public void saveSipAccount(Context context, SipAccount account) {
SharedPreferences pref = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor e = pref.edit();
e.putString(SIP_DOMAIN_KEY, account.getDomain());
e.putString(SIP_PROXY_KEY, account.getProxy());
e.putString(SIP_USER_KEY, account.getUser());
e.putString(SIP_PASSWORD_KEY, encryptString(account.getPassword()));
e.apply();
}
public SipAccount getSipAccount(Context context) {
SipAccount account = new SipAccount();
SharedPreferences pref = context.getSharedPreferences(PREFERENCE_NAME, context.MODE_PRIVATE);
account.setDomain(pref.getString(SIP_DOMAIN_KEY, ""));
account.setProxy(pref.getString(SIP_PROXY_KEY, ""));
account.setUser(pref.getString(SIP_USER_KEY, ""));
String password = pref.getString(SIP_PASSWORD_KEY, "");
if (!TextUtils.isEmpty(password)) {
password = decryptString(password);
}
account.setPassword(password);
return account;
}
and this is the code when I call saveSipAccount
String domain = String.valueOf(sipDomainView.getText());
String proxy = String.valueOf(sipProxyView.getText());
String user = String.valueOf(sipUserView.getText());
String password = String.valueOf(sipPasswordView.getText());
sipManager.saveSipAccount(MyApplication.getInstance().getApplicationContext(), domain, proxy, user, password);
Log.d(TAG, "saved");
try {
service.changeAccount();
}
and this is getSipAccount
public boolean changeAccount() {
sipManager = SipManager.newInstance();
SipAccount profile = sipManager.getSipAccount(MyApplication.getInstance().getApplicationContext());
AccountConfig config = sipManager.getAccountConfig(app, profile.getDomain(), profile.getProxy()
, profile.getUser(), profile.getPassword());
try {
MyApp.ep.libRegisterThread(Thread.currentThread().getName());
} catch (Exception e) {
Log.e(TAG, "libRegisterThread error.", e);
}
changeAccountStatus("processing");
try {
account.modify(config);
} catch (Exception e) {
Log.e(TAG, "MyAccount.modify error.", e);
changeAccountStatus("Fail registration");
return false;
}
return true;
}
You can try this
e.commit()
and creat a String variable like this:
String str1 = pref.getString(SIP_DOMAIN_KEY, null)
and log str1 to check. Hope this help you
Try creating a special class for sharedPreferences. For example:
public class MySharedPreferences {
public static final String MyPREFERENCES = "MyPrefs";
public static final String KEY1 = "key1";
public static final String KEY2 = "key2";
// other keys
private static MySharedPreferences mInstance;
private static Context mCtx;
private MySharedPreferences(Context context) {
mCtx = context;
}
public static synchronized MySharedPreferences getInstance(Context context) {
if (mInstance == null) {
mInstance = new MySharedPreferences(context);
}
return mInstance;
}
//this method will save the sip account
public boolean saveSipAccount(String domain, String proxy, String user, String password) {
SipAccount account = new SipAccount(domain, proxy, user, password);
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(YOUR_KEY, account.getDomain());
//other putString
return editor.commit();
}
public SipAccount getSipAccount() {
SipAccount account = new SipAccount();
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String domain = sharedPreferences.getString(YOUR_KEY, ""));
account.setDomain(domain));
//other code
if (!TextUtils.isEmpty(password)) {
password = decryptString(password);
}
account.setPassword(password);
return account;
}
For obtain a SipAccount
SipAccount acount = MySharedPreferences.getInstance(context).getSipAccount();
Delete and reinstall your app.
My apps worked when I used Tray instead of SharedPreference!
Thank you guy so much for your answer ad your kindness :) !
Related
I'm trying to save a string to shared preferences and then start an activity and retrieve it but doesn't work. What am I doing wrong?
First I set the shared preference key then I start the activity:
SharedPreferences.Editor editor =
getSharedPreferences("PaymentStatus",MODE_PRIVATE).edit();
editor.putString("payment_status","success");
editor.apply();
Intent i = new Intent(getBaseContext(), ProfileActivity.class);
startActivity(i);
and on the ProfileActivity class I trying to retrieve the key:
SharedPreferences prefs = getSharedPreferences("PaymentStatus",
MODE_PRIVATE);
String payment_status = prefs.getString("payment_status", null);
if(payment_status == "success"){
Log.i("payment status", "success");
}
I can't see the payment status success in the logcat.
The issue with the code you have given is not with how you done it with shared preferences (you did that correctly btw)
Your issue is that you are comparing strings via == as this compares the string reference and not the string value. Use .equals() or .contains() instead.
if (payment_status.equals("success")) {
Log.i("payment status", "success");
}
This is my experience in used SharedPreferens.
Perhaps this approach will solve the problem:
public class UserData {
UserData(MainActivity mainActivity){this.mainActivity = mainActivity;}
private static UserData userData;
private final MainActivity mainActivity;
private SharedPreferences sPref;
private SharedPreferences.Editor editor;
final private String USER_ID = "user_id";
public static void create(MainActivity activity) {
if (userData == null) userData = new UserData(activity);
}
public static UserData getUserData() {
return userData;
}
void createUser() {
sPref = mainActivity.getSharedPreferences("UserData", Context.MODE_PRIVATE);
editor = sPref.edit();
// Если user id уже есть, выходим из метода
if(sPref.contains(USER_ID)) return;
editor.putString(USER_ID, createUserId());
editor.apply();
Toast.makeText(mainActivity,"UserId created", Toast.LENGTH_SHORT).show();
}
// id формируется на основе текущей даты и времени
private String createUserId() {
Date currentDate = new Date();
DateFormat dateFormat = new SimpleDateFormat("ddMMyyyyHHmmss", Locale.getDefault());
return dateFormat.format(currentDate);
}
public String getUserId() {
return sPref.getString(USER_ID, "");
}
}
I am very new in android.In my app I make a login page.I use Shared Preferences for session.it works fine but a problem when i close my app and again open then login page comes.I want when user press logout button only that time login page will come.
this is my SharedPreferences class
public class SharedPrefManager {
//the constants
private static final String SHARED_PREF_NAME = "dreamzsharedpref";
private static final String KEY_USERNAME = "keyusername";
private static final String KEY_PHONE = "keyphone";
private static final String KEY_ID = "keyid";
private static SharedPrefManager mInstance;
private static Context mCtx;
private SharedPrefManager(Context context) {
mCtx = context;
}
public static synchronized SharedPrefManager getInstance(Context context) {
if (mInstance == null) {
mInstance = new SharedPrefManager(context);
}
return mInstance;
}
//method to let the user login
//this method will store the user data in shared preferences
public void userLogin(User user) {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(KEY_ID, user.getUserid());
editor.putString(KEY_PHONE, user.getUserphno());
editor.putString(KEY_USERNAME, user.getUsername());
editor.apply();
}
//this method will checker whether user is already logged in or not
public boolean isLoggedIn() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_PHONE, null) != null;
}
//this method will give the logged in user
public User getUser() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return new User(
sharedPreferences.getString(KEY_USERNAME, null),
sharedPreferences.getString(KEY_PHONE, null),
sharedPreferences.getInt(KEY_ID, -1)
);
}
//this method will logout the user
public void logout() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
mCtx.startActivity(new Intent(mCtx, LoginActivity.class));
}
}
this is my login method in login class
private void userLogin() {
//first getting the values
final String username = UsernameEt.getText().toString();
final String password = PasswordEt.getText().toString();
//validating inputs
if (TextUtils.isEmpty(username)) {
UsernameEt.setError("Please enter your username");
UsernameEt.requestFocus();
return;
}
if (TextUtils.isEmpty(password)) {
PasswordEt.setError("Please enter your password");
PasswordEt.requestFocus();
return;
}
//if everything is fine
class UserLogin extends AsyncTask<Void, Void, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(Void... voids) {
//creating request handler object
RequestHandler requestHandler = new RequestHandler();
//creating request parameters
HashMap<String, String> params = new HashMap<>();
params.put("vuserphno", username);
params.put("votp", password);
//returing the response
return requestHandler.sendPostRequest(URLs.URL_LOGIN, params);//this URLs is a class where URL_LOGIN is login url
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressBar.setVisibility(View.GONE);
try {
JSONObject obj = new JSONObject(s);
JSONArray array = obj.getJSONArray("user");
for (int i = 0; i < array.length(); i++) {
//getting the user from the response
JSONObject userJson = array.getJSONObject(i);
//creating a new user object
User user = new User(
userJson.getString("username"),
userJson.getString("userphno"),
userJson.getInt("userid")
);
//storing the user in shared preferences
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
}
//starting the profile activity
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
UserLogin ul = new UserLogin();
ul.execute();
}
please tell me where is the problem and how I can solve this problem.
Thanks.
In your LoginActivity, check for login state and change activity, finish itself so it's clear from the back stack.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
if (SharedPrefManager.getInstance().isLoggedIn(this)) {
startActivity(this, MainActivity.class);
finish();
return;
}
// ...
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Help me on android SharedPreferences, I have login activity when after login will set the SharedPreferences, but when set SharedPreferences always error null pointer. I try to show the value with toast and all variable have value. this my activity
public class LoginNewActivity extends Activity {
public SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView toRegister = (TextView) findViewById(R.id.link_to_register);
toRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
startActivity(i);
}
});
final EditText etUsnm = (EditText) findViewById(R.id.tuserid);
final EditText etPswd = (EditText) findViewById(R.id.tpasswd);
Button bLogin = (Button) findViewById(R.id.btnLogin);
bLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String username = etUsnm.getText().toString();
String password = etPswd.getText().toString();
new UserLoginTask().execute(username, password);
}
});
}
public class UserLoginTask extends AsyncTask<String, String, JSONObject> {
ProgressDialog pdLoading = new ProgressDialog(LoginNewActivity.this);
HttpURLConnection conn;
URL url = null;
JSONParser jsonParser = new JSONParser();
private static final String TAG_MESSAGE = "message";
private static final String TAG_NAMA = "nama_user";
private static final String TAG_USERNAME = "username";
private static final String TAG_HAKAKSES = "role";
private static final String TAG_ERROR = "error";
private static final String LOGIN_URL = "http://192.168.1.101/mlls/getLoginNew.php";
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected JSONObject doInBackground(String... args) {
try {
HashMap<String, String> params = new HashMap<>();
params.put("username", args[0]);
params.put("password", args[1]);
Log.d("request", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
String nama = "";
int iduser = 0;
String email = "";
String hakakses = "";
int error_message = 0;
if (json != null) {
//Toast.makeText(LoginActivity.this, json.toString(),
//Toast.LENGTH_LONG).show();
try {
nama = json.getString(TAG_NAMA);
email = json.getString(TAG_USERNAME);
hakakses = json.getString(TAG_HAKAKSES);
error_message = json.getInt(TAG_ERROR);
} catch (JSONException e) {
e.printStackTrace();
}
}
if(error_message == 1) {
pdLoading.dismiss();
session.setLogin(true);
session.setStatus(hakakses);
session.setNama(nama);
session.setUsername(email);
session.setId(iduser);
Toast.makeText(LoginNewActivity.this, hakakses,
Toast.LENGTH_LONG).show();
//Intent intent = new Intent(LoginNewActivity.this, LessonListActivity.class);
//intent.putExtra("nama", nama);
//intent.putExtra("email", email);
//intent.putExtra("hakakses", hakakses);
//startActivity(intent);
//LoginNewActivity.this.finish();
}else{
Toast.makeText(getApplicationContext(), "User ID atau Password anda salah.", Toast.LENGTH_LONG).show();
}
}
}}
and this is my sharedPreferences
public class SessionManager {
private static String TAG = SessionManager.class.getSimpleName();
SharedPreferences pref;
Editor editor;
Context _context;
int PRIVATE_MODE = 0;
private static final String PREF_NAME = "Hlls";
private static final String KEY_IS_LOGGEDIN = "isLoggenIn";
private static final String KEY_IS_USER = "isStatus";
private static final String KEY_IS_NAMA = "isNama";
private static final String KEY_IS_USERNAME = "isUsername";
private static final String KEY_IS_IDUSER = "isIdUser";
public SessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setLogin(boolean isLoggedIn){
editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn);
editor.commit();
Log.d(TAG, "User login session modified");
}
public void setId(int isIdUser){
editor.putInt(KEY_IS_IDUSER, isIdUser);
editor.commit();
Log.d(TAG, "ID User akses session modified");
}
public void setStatus(String isStatus){
editor.putString(KEY_IS_USER, isStatus);
editor.commit();
Log.d(TAG, "User akses session modified");
}
public void setNama(String isNama){
editor.putString(KEY_IS_NAMA, isNama);
editor.commit();
Log.d(TAG, "Username session modified");
}
public void setUsername(String isUsername){
editor.putString(KEY_IS_USERNAME, isUsername);
editor.commit();
Log.d(TAG, "Username session modified");
}
public String isNama(){
return pref.getString(KEY_IS_NAMA, "");
}
public int isId(){
return pref.getInt(KEY_IS_IDUSER, 0);
}
public String isUsername(){
return pref.getString(KEY_IS_USERNAME, "");
}
public boolean isLoggedIn(){
return pref.getBoolean(KEY_IS_LOGGEDIN, false);
}
public String isStatus(){
return pref.getString(KEY_IS_USER, "");
}
}
help me for this error, sorry for bad english
NullPointerException is thrown when an application attempts to use an
object reference that has the null value .
You should call this in your ONCREATE section .
session=new SessionManager(LoginNewActivity.this);
Finally
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
session=new SessionManager(LoginNewActivity.this);
Use mode private instead of private mode
pref = _context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
It is flag provided by android itself you need not assign any other flag to it.
and you have not initialized session manager context is null.
I guess you are not initializing your Shared Preference class.
SessionManager session = new SessionManager(this);
In case its true
Please try and make it a singleton class as a general practise
Something like this
public final class PreferenceManager {
private static SharedPreferences preferences;
/**
* Private constructor to restrict the instantiation of class.
*/
private PreferenceManager() {
throw new AssertionError();
}
public static SharedPreferences getInstance(Context context) {
if (preferences == null && context != null) {
preferences = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
}
return preferences;
}
}
You need to do the following in your Activity:
session = new SessionManager(LoginNewActivity.this);
You have not created the object of your SessionManager class, so its constructor never gets called and you get NPE.
I am getting the default text and not the actual text saved when trying to access a shared preference. I have tested that it returns true when saving so I am pretty sure the problem is in reading from the preference file.
The preference class
public class SaveWarningMessage : Activity
{
private ISharedPreferences myPref;
private ISharedPreferencesEditor myPrefEditor;
private Context myContext;
public void MyAppPref(Context context)
{
this.myContext = context;
myPref = PreferenceManager.GetDefaultSharedPreferences(myContext);
myPrefEditor = myPref.Edit();
}
public void SaveString(string text)
{
myPrefEditor.PutString("warning text", text);
var returnValue = myPrefEditor.Commit();
}
public string GetString()
{
return myPref.GetString("warning text", "could not get pref");
}
}
}
The class saving the preference:
string warningText = Intent.GetStringExtra("warningText");
Context mContext = Android.App.Application.Context;
SaveWarningMessage classInstans = new SaveWarningMessage();
classInstans.MyAppPref(mContext);
classInstans.SaveString(warningText);
The class reading from the preference:
Context mContext = Android.App.Application.Context;
SaveWarningMessage classInstans = new SaveWarningMessage();
classInstans.MyAppPref(mContext);
string message = classInstans.GetString();
Personally I would not subclass it from Activity(?) and use the .actor to instance your ISharedPreferences, along with a few other changes you end up with this example.
Example:
public class SaveWarningMessage
{
public const string WARNINGTEXT = "warning text";
ISharedPreferences myPref;
public SaveWarningMessage(Context context)
{
myPref = PreferenceManager.GetDefaultSharedPreferences(context);
}
public void SaveString(string text)
{
var myPrefEditor = myPref.Edit();
myPrefEditor.PutString(WARNINGTEXT, text);
if (!myPrefEditor.Commit())
{
Log.Error("SomeTag", $"Saving {text} to Pref:{WARNINGTEXT} failed");
}
// Or replace the Commit & check of return the following
// if you do not care about checking the return value
// myPrefEditor.Apply();
}
public string GetString()
{
return myPref.GetString(WARNINGTEXT, "could not get pref");
}
}
Then you can you it like this:
string warningText = "SomeStringToSave";
SaveWarningMessage classInstans = new SaveWarningMessage(Application.Context);
classInstans.SaveString(warningText);
SaveWarningMessage classInstans2 = new SaveWarningMessage(Application.Context);
string message = classInstans2.GetString();
Log.Debug("SO", message);
I am new to android. I am using a SessionHandler class where i save the username from LoginActivity in shared preferences. I want to access this username from shared preferences in a class of broadcast receiver
Here is the code for SessionHandler class.
public SharedPreferences getLoginPreferences() {
// This sample app persists the registration ID in shared preferences,
// but
// how you store the regID in your app is up to you.
return context.getSharedPreferences(
LoginActivity.class.getSimpleName(), Context.MODE_PRIVATE);
}
public void storeLoginSession(String str_Name) {
final SharedPreferences prefs = getLoginPreferences();
SharedPreferences.Editor editor = prefs.edit();
editor.putString("name", str_Name);
editor.commit();
}
I want to access this name name here in startService().
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
startService();
}
}
private void startService() {
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
strDate = sdf.format(c.getTime());
}
How can I get this value? I tried using context but not working. Can anyone please help me.
Best way to use SharedPreference is to wrap inside your custom Preference class like :
public class YourPreference {
private static YourPreference yourPreference;
private SharedPreferences sharedPreferences;
public static YourPreference getInstance(Context context) {
if (yourPreference == null) {
yourPreference = new YourPreference(context);
}
return yourPreference;
}
private YourPreference(Context context) {
sharedPreferences = context.getSharedPreferences("YourCustomNamedPreference",Context.MODE_PRIVATE);
}
public void storeLoginSession(String str_Name) {
SharedPreferences.Editor prefsEditor = sharedPreferences.edit();
editor.putString("name", str_Name);
prefsEditor.commit();
}
}
Then you can get YourPrefrence instance from any class where contet is available using
YourPreference yourPrefrence = YourPreference.getInstance(context);
yourPreference.storeLoginSession(YOUR_STRING);
You can create global functions for sharedPreferences:
public static void setSharedPrefString(Context context, String key, String value) {
SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preference.edit();
editor.putString(key, value);
editor.commit();
}
public static String getSharedPrefString(Context context, String key) {
SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(context);
if (preference != null) {
return preference.getString(key, "");
}
return "";
}
call "getSharedPrefString" from onReceive of BroadcastReceiver.
Let me know if you find it useful.
Create a class called AppPreference.class
public class AppPreference {
private SharedPreferences mSharedPreferences;
public static final String KEY_LOGIN= "KEY_LOGIN";
public AppPreference(Context context) {
super();
mSharedPreferences = context.getSharedPreferences(context.getString(R.string.app_name), Context.MODE_PRIVATE);
}
public void setLoginStatus(String value) {
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString(KEY_POSTCODE_LOGIN, value);
editor.commit();
}
public String getLoginStatus() {
return mSharedPreferences.getString(KEY_POSTCODE_LOGIN,"");
}
}
You can save in value by calling
AppPreference appPreference = new AppPreference(context);
appPreference .setLoginStatus("value you want to save");
getvalue call
AppPreference appPreference = new AppPreference(context);
appPreference .getLoginStatus();
Hi please use this sample code
public class PreferenceHandler
{
public static boolean storeNameToPrefernce(Context context,
String key, String getDetailsString) {
// TODO Auto-generated method stub
SharedPreferences mySharedPreferences;
try{
mySharedPreferences=context.getSharedPreferences(MyConstants.PREFERENCE_NAME,0);
SharedPreferences.Editor editor=mySharedPreferences.edit();
editor.putString(key,getDetailsString);
editor.commit();
}
catch(Exception e){
System.out.println(e);
return false;
}
return true;
}
public static String getNameFromPreference(Context context,String key)
{
String value;
SharedPreferences mySharedPreferences;
try{
mySharedPreferences = context.getSharedPreferences(MyConstants.PREFERENCE_NAME,0);
value = mySharedPreferences.getString(key, "NONE");
}catch(Exception e){
return "NONE";
}
return value;
}
}
Getting string from Preference class:
In SampleActvity class.
String name =PreferenceHandler.getNameFromPreference(sampleActivity.this,key);
I do it in this simply way:
main class:
public class SWP extends Activity implements LocationListener
{ ....
public static final String MY_PREFERENCES = "SWP_Preferences";
public static SharedPreferences preferencesSwp;
public static SharedPreferences.Editor preferencesEditorSwp;
...
#Override
protected void onCreate(Bundle savedInstanceState)
{ ....
preferencesSwp = getSharedPreferences(MY_PREFERENCES, Activity.MODE_PRIVATE);
preferencesEditorSwp = preferencesSwp.edit();
....
}
....
}
in any other, read
value1 = SWP.preferencesSwp.getString("PREF_value1", "init_text");
and write
SWP.preferencesEditorSwp.putString("PREF_value1", value1 );
SWP.preferencesEditorSwp.commit();