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", "");
Related
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!
I use twitter4j in my android application. I can get oauth_verifier and fetch token and secret ( with accessToken.getToken() and accessToken.getTokenSecret() ). I store those value.
However,I don't know how to use this value when the app open again.I found something like this.
accessToken = this.twitter.getOAuthAccessToken(requestToken, verifier);
but how can I create requestToken?
when you got the token and the token secret save them in your app , example using SharedPreference
AccessToken accessToken = twitter.getOAuthAccessToken(oathVerifier);
SharedPreferences pref= getSharedPreferences("social_pref",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("token",accessToken.getToken());
editor.putString("token_secret",accessToken.getTokenSecret());
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.GINGERBREAD) {
editor.apply();
}else{
editor.commit();
}
Now you can easily know if there is a stored token and token secret
public boolean doIhaveTokenAndTokenSecret(Context context){
SharedPreferences pref= getSharedPreferences("social_pref",Context.MODE_PRIVATE);
return pref.getString("token",null)!=null && pref.getString("token_secret",null)!=null ;
}
if you have them stored provide them to ConfigurationBuilder object
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(Constants.TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(Constants.TWITTER_CONSUMER_SECRET);
if(doIhaveTokenAndTokenSecret(getApplicationContext()){
SharedPreferences mSharePref = context.getSharedPreferences(Constants.SOCIAL_PREF_NAME, Context.MODE_PRIVATE);
builder.setOAuthAccessToken(mSharePref.getString("token",null));
builder.setOAuthAccessTokenSecret(mSharePref.getString("token_secret",null));
}
Configuration configuration = builder.build();
Twitter mTwitter = new TwitterFactory(configuration).getInstance();
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);
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
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();