SharedPreferences and Emulator - android

I have this simple piece of code:
SharedPreferences settings = getSharedPreferences(Constants.USER_DETAILS, 0);
SharedPreferences.Editor editor = settings.edit();
//editor.putLong(Constants.USER_DETAILS_SIGNEDINON, registerResponse.getSignedInOn()); // signed in on
editor.putLong(Constants.USER_DETAILS_SIGNEDINON, 1); // signed in on
long test = settings.getLong(Constants.USER_DETAILS_SIGNEDINON, 2);
if (settings.edit().commit()) {
System.out.print("ok");
} else {
System.out.print("not ok");
}
as you can see I have been playing around to understand what is going on.
So, I have checked the /data/data/... and the preferences file is indeed created but is empty (just the Map tag)
The test long variable returns 2, even if I set it to 1 the line before.
The commit returns true.
Am I missing something?
I have set uses-permission android:name=android.permission.WRITE_EXTERNAL_STORAGE
though I believe this is only needed when I truly do external storage.
Regards.
David.

One thing I ran in to was that you cannot keep calling pref.edit() and expect your changes to persist. It appears that each call to pref.edit() produces a new Editor (not a singleton).
WILL NOT PERSIST:
pref.edit().remove("key"); // new editor created
pref.edit().commit(); // new editor created
WILL PERSIST:
Editor edit=pref.edit(); // new editor created
edit.remove("key"); // same editor used
edit.commit(); // same editor used

Try this piece of code.
SharedPreferences settings = getSharedPreferences(Constants.USER_DETAILS, 0);
SharedPreferences.Editor editor = settings.edit();
//editor.putLong(Constants.USER_DETAILS_SIGNEDINON, registerResponse.getSignedInOn()); // signed in on
editor.putLong(Constants.USER_DETAILS_SIGNEDINON, 1); // signed in on
if (editor.commit()) {
System.out.print("ok");
} else {
System.out.print("not ok");
}
long test = settings.getLong(Constants.USER_DETAILS_SIGNEDINON, 2);

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); 0 - for private mode
Editor editor = pref.edit();
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
// returns stored preference value
// If value is not present return second param value - In this case null
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
editor.commit(); // commit changes
editor.clear();
editor.commit(); // commit changes

Related

sharedPreference can't get updated value from a service of another application

I have 2 different android applications (app1 and app2). In app2, I tried to get the value of the sharedPreference from a service of app1. I used the following codes:
In a service of app 1 :
sharedPreferences = getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("currentKey");
editor.putString("currentKey",target);//update sharedPrerences
editor.apply();
Log.i(TAG,"value is" + sharedPreferences.getString("currentKey", null) );
And in app2:
try {
Context context = createPackageContext("com.example.packageName",0);
sharedPreferences = context.getSharedPreferences(PREFERENCES,Context.MODE_PRIVATE);
String current = sharedPreferences.getString("currentKey",null);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
Two apps have the same following info in the manifest:
android:sharedUserId="com.android.example"
android:sharedUserLabel="#string/user_id_label"
In app2, I can get the value of sharedPreference, but the problem is that the value isn't updated when the service of app1 changes value of the sharedPreference. Have no idea! If someone have fallen in the same case, please help me! Thanks a lot!

Android preferences do not seem to be persisted between application starts

I'm using preferences to save some user settings in my Nexus 7 app. My code for saving a value to preferences is:
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
String systemId = spinnerActivity.getSelectedItem().toString();
editor.putString(PreferenceKeys.SAVED_SYSTEMID, systemId);
if (!editor.commit()) {
Toast.makeText(getApplicationContext(), "Error saving System ID", Toast.LENGTH_LONG).show();
}
I've stepped through this with the debugger and it is being called correctly. When I restart my app. and try to read back the value with the code below, I always get null.
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
String savedSystemId = sharedPref.getString(PreferenceKeys.SAVED_SYSTEMID, null);
ConnectionInfo.setSystemId(savedSystemId);
The loading is called from the onCreate() function in the main activity. Strangely enough loading of other preference values elsewhere in the app. works fine, it's just this one case that doesn't work. Can anyone see what's wrong?
SharedPreferences sharedPref = getSharedPreferences("Name_of_item",Context.MODE_PRIVATE);
please try the below
SharedPreferences sharedPref = getPreferences("preference_name",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
String systemId = spinnerActivity.getSelectedItem().toString();
editor.putString(PreferenceKeys.SAVED_SYSTEMID, systemId);
if (!editor.commit()) {
Toast.makeText(getApplicationContext(), "Error saving System ID", Toast.LENGTH_LONG).show();
}
SharedPreferences sharedPref = getPreferences("preference_name",Context.MODE_PRIVATE);
String savedSystemId = sharedPref.getString(PreferenceKeys.SAVED_SYSTEMID, null);
ConnectionInfo.setSystemId(savedSystemId);
Instead of using:
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
Try to use this:
import android.preference.PreferenceManager;
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
Or, you can use a named preferences page in which case:
public static final String PREF_FILE_NAME = "PrefFile";
SharedPreferences sharedPref = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);

accessing sharedpreference across applications

I am using getDefaultSharedPreferences(con) in my application to store preferences. Now I want to access this shared preference in another application.
I used following method:
con = this.createPackageContext("com.example.preferences", Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);
SharedPreferences filePref = PreferenceManager.getDefaultSharedPreferences(con);
if(filePref != null){
Toast.makeText(getApplicationContext(), "file pref not null --- ", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "file pref is null **** ", Toast.LENGTH_LONG).show();
}
Map<String,?> allkeys = filePref.getAll();
Toast.makeText(getApplicationContext(), "file pref size **** "+allkeys.size(), Toast.LENGTH_LONG).show();
for(Map.Entry<String,?> entry : allkeys.entrySet()){
Toast.makeText(getApplicationContext(), "~~~ file pref --- map values --- "+entry.getKey() + ": "+entry.getValue().toString(), Toast.LENGTH_LONG).show();
}
Another way which tried is specifying file name & accessing it, as follow;
SharedPreferences filePref = gvcon.getSharedPreferences("com.example.preferences_preferences", Context.MODE_PRIVATE);
With this method I am able to access SharedPrefernce file, it returns file is not null but when I check for file size it shows 0. I am not able to read preference value from file.
I used shareduserid of another application so that I get full access to that application.
What is the proper way to go about this?
I'm not sure that I understood your problem completely, but some times this implementation will help you to access data across packages.
Use getSharedPreferences() to store data in shared preferences
This method will store data in shared preferences
public void dataWriter(){
String strShareValue = "Hello! this is shared data";
SharedPreferences prefs = getSharedPreferences("demopref",Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("demostring", strShareValue);
editor.commit();
}
You can access that shared data from another package using this code sample
public void dataRead(){
Context con;
try {
con = createPackageContext("PACKAGE NAME THAT SHARES DATA", 0);
SharedPreferences pref = con.getSharedPreferences("demopref", Context.MODE_PRIVATE);
String dataShared = pref.getString("demostring", "No Value");
}
catch (NameNotFoundException e) {
Log.e("Not data shared", e.toString());
}
}
}

How to use SharedPreferences to store persistant data Android

I am building a camera application. I'm trying to save some information using SharedPreferences.
I want to save some persistant information-the last image taken filepath. But the first time the application is used before taking a picture, the data would be NULL.
So I want to getSharedPreferences in onCreate and check if the value is null. But as far as I know the only way to use getSharedPreferences is only if you have called put on the Editor before. Hence, I am getting a NULL pointer exception on the SharedPreferences object the first time.
How do you resolve this?
//inside on Create()
imageData = getSharedPreferences("ImageData",MODE_PRIVATE);
SharedPreferences.Editor prefEditor = imageData.edit();
prefEditor.commit();
String previousImage = imageData.getString("lastImageTaken", null);
if(previousImage == null){
Log.d(TAG,"previous image is NULL");
}
else{
//do something with the filepath
}
//-----------------------
//in onClick of capture button
imageData = getSharedPreferences("ImageData",MODE_PRIVATE);
SharedPreferences.Editor prefEditor = imageData.edit();
prefEditor.putString("lastImageTaken", MyActivity.this.pictureFilePath);
prefEditor.commit();
Please try this
To read from SharedPreferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String name = preferences.getString("name","default");
String email = preferences.getString("email","default");
To save into SharedPreferences
Editor edit = preferences.edit();
edit.putString("name", "Roy");
edit.putString("email", "roy#mail.com");
edit.commit();

how to implement authentication using shared preferences in android?

I am new to Android.my requirement is to implement simple authentication logic for login screen by using sharedpreferences in android.
can any one suggest me...?
To save details after registration of user (when user is created)...
// Get the app's shared preferences
SharedPreferences login_app_preferences = context.getSharedPreferences("LOGIN_DETAILS", MODE_PRIVATE);
// Update fields
SharedPreferences.Editor editor = login_app_preferences.edit();
editor.putString("email", strEmailOrLoginId);
editor.putString("password", strPassword);
editor.commit(); // Very important
To access it any where in application....
// Get the app's shared preferences
SharedPreferences login_app_preferences = context.getSharedPreferences("LOGIN_DETAILS", MODE_PRIVATE);
strUserName = login_app_preferences.getString("email", "");
strPassword = login_app_preferences.getString("password", "");

Categories

Resources