How to use SharedPreferences to store persistant data Android - 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();

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);

SharedPreferences and Emulator

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

Android: Retrieving shared preferences of other application

I have a settings application from which i have to retrieve other applications preferences, but i don't have the details of keys in them, how can i retrieve all the available keys and values in that preference?
Thanks,
Swathi
Okay! using this code in Application 1 ( with package name is "com.sharedpref1" ) to store data with Shared Preferences.
SharedPreferences prefs = getSharedPreferences("demopref",
Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("demostring", strShareValue);
editor.commit();
And using this code in Application 2 to get data from Shared Preferences in Application 1. We can get it because we use MODE_WORLD_READABLE in application 1:
try {
con = createPackageContext("com.sharedpref1", 0);
SharedPreferences pref = con.getSharedPreferences(
"demopref", Context.MODE_PRIVATE);
String data = pref.getString("demostring", "No Value");
displaySharedValue.setText(data);
} catch (NameNotFoundException e) {
Log.e("Not data shared", e.toString());
}
More information please visit this URL:
http://androiddhamu.blogspot.in/2012/03/share-data-across-application-in.html
Assuming the preference are WORLD_READABLE, this might work:
final ArrayList<HashMap<String,String>> LIST = new ArrayList<HashMap<String,String>>();
// where com.example is the owning app containing the preferences
Context myContext = createPackageContext("com.example", Context.MODE_WORLD_WRITEABLE);
SharedPreferences testPrefs = myContext.getSharedPreferences("test_prefs", Context.MODE_WORLD_READABLE);
Map<String, ?> items = testPrefs .getAll();
for(String s : items.keySet()) {
// do something like String value = items.get(s).toString());
}
Additionally you have to add same android:sharedUserId in the both app's manifest file.
Unfortunately the docs now don't even explain MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE, instead saying:
This constant was depreciated in API level 17.
Creating world-readable files is very dangerous, and likely to cause security holes in applications. It is strongly discouraged; instead, ....etc
Since the depreciation, implementing file sharing between apps with sharedpreferences may be too risky, although it was simple. I'm not too concerned with security holes from the MODE_WORLD_READABLE mode in game apps where I just want to be able to transfer characters from one app to another. It's too bad they depreciated both sharing modes.
It can work if we want read perference value from other app/pkg/process.
but there is something wrong in jkhouw1's answer:
Context myContext = createPackageContext("com.example",
Context.MODE_WORLD_WRITEABLE);
It should be :
Context myContext = createPackageContext("com.example",
Context.CONTEXT_IGNORE_SECURITY);
though , CONTEXT_IGNORE_SECURITY and MODE_WORLD_WRITEABLE with the same value of "int 2"
At all ,thanks for this question and answers.
It's simple to retrieve store shared preferences data of one application to another application.
Step 1: add the same android:sharedUserId="android.uid.shared" in both app's manifest files.
Step 2: Store Value application1
SharedPreferences preferences = context.getSharedPreferences("token_id", Context.MODE_WORLD_READABLE);
Editor editor = preferences.edit();
editor.putString("shared_token", encryptedValue);
Log.e("aaa *** shared_token : ", encryptedValue.toString());
editor.commit();
Step 3: Get Value From application2
Context con = null;
try {
con = createPackageContext("application2 package name", Context.CONTEXT_IGNORE_SECURITY);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
try {
if (con != null) {
SharedPreferences pref = con.getSharedPreferences(
"token_id", Context.MODE_WORLD_READABLE);
String data = pref.getString("shared_token", "");
Log.d("msg", "Other App Data: " + data);
} else {
Log.d("msg", "Other App Data: Context null");
}
} catch (Exception e) {
e.printStackTrace();
}

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