SharedPreferences keep on returning default value - android

I would like to display the name and user type after registration and login. For this app, after a person registers, one is taken back to the log in screen. If the login is successful, the homepage activity will open.
I'm trying to send the name and user type value from registration to homepage but sharePreferences kept on returning the null value.
(Registration)
//grab the user type to homepage
Spinner spinner = (Spinner)findViewById(R.id.user_type_spinner);
String userType = spinner.getSelectedItem().toString();
EditText name=(EditText) findViewById(R.id.name);
preferences = this.getSharedPreferences(PREFS_NAME,
Registration.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("NAME", name.getText().toString());
editor.putString("USER_TYPE", userType);
editor.commit();
(Homepage)
//Grab name and user type to show in homepage
preferences = this.getSharedPreferences(PREFS_NAME,
Registration.MODE_PRIVATE);
textUserType = (TextView) findViewById(R.id.textView3);
textName = (TextView) findViewById(R.id.textView1);
textWelcome = (TextView) findViewById(R.id.textView2);
//Get name and user type
String prefName=preferences.getString("NAME", "");
String prefUserName=preferences.getString("USER_TYPE", "");
//display the view
textName.setText("Hello " + prefName + "!");
textWelcome.setText("Welcome");
textUserType.setText("User type:" +prefUserName);

You can follow the answer given by Haj Ali, it works....But I think that keeping an user and his password inside the sharedpreferences XML file is a REALLY bad practice since anyone can steal the file and obtain the credentials.
-> If your passing parameters from one activity to another, add the parameters to your intent.
-> If you're passing parameters from an activity to a fragment, add the parameters to a bundle, and then add the bundle to the fragment.

Follow such a model:
Activity A:
//inputs
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
//SharedPreferences
SharedPreferences prefs = PreferenceManager.
getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = prefs.edit();
editor.putString("email",email);
editor.putString("password",password);
editor.commit();
Activity B:
SharedPreferences sharedPreferences = PreferenceManager.
getDefaultSharedPreferences(getApplicationContext());
email= sharedPreferences.getString("email", "");
password = sharedPreferences.getString("password", "");

Related

Cannot load string from Fragment's shared preferences

I am trying to save and load a string value from a fragment's shared preferences. However, the string I am committing to the preferences does not load back from the preferences. Here is my code.
// Prefs string handle
String NAME = "myPref";
// Get default prefs for the fragment
SharedPreferences defaultPrefs =
PreferenceManager.getDefaultSharedPreferences(getActivity());
// Commit a string to prefs
defaultPrefs.edit().putString(NAME, "Hello world!");
defaultPrefs.edit().commit();
// Load the string just commited to prefs
String commitedString = defaultPrefs.getString(NAME,"defaultString");
// Print the loaded string
// logs defaultString
// does not log Hello world!
Log.v(TAG,"commitedString value is "+commitedString);
You are editing, putting a String, not committing, then editing again, putting nothing, and then committing.
Change
defaultPrefs.edit().putString(NAME, "Hello world!");
defaultPrefs.edit().commit();
To
defaultPrefs.edit().putString(NAME, "Hello world!").commit();
change this
defaultPrefs.edit().putString(NAME, "Hello world!");
defaultPrefs.edit().commit();
to this:
SharedPreferences.Editor editor = defaultPrefs.edit();
editor.putString(NAME, "Hello world!");
editor.commit();
and it should work
//This always seemed to work for me
Context context = YourFragmentName.this;
String NAME = "";
SharedPreferences share = context.getSharedPreferences("prefs", 0);
share.getString(NAME, NAME);
SharedPreferences.Editor editor = share.edit();
editor.putString(NAME, "myPref");
editor.apply();
//then get your string
String commitedString = share.getString(NAME, "");

shared preferences First Time Empty When i restart the app with out logout Code works Fine

Problem is i have stored Facebook username email id and profile picture and retrieving data in next activity but the problem is when i log in the data is null when i restart the App code working fine.
Storing Data
String email = object.getString("email");
String id = object.getString("id");`
sessionManager.setfacebookid(object.getString("email").toString());
String imageurl = "https://graph.facebook.com/" + id + "/picture?type=large";
sessionManager.setfacebookimage("https://graph.facebook.com/" + id + "/picture?type=large".toString());
Retrieving Data
sessionManager.isUserLogin();
navHeader = navigationView.getHeaderView(0);
String facebookname = sessionManager.getfacebookname();
tvvwelcome2 = (TextView) navHeader.findViewById(R.id.tvwelcome2);
tvvwelcome2.setText(facebookname);
Log.e("facebooknamein text....", "" + facebookname);
String facebookid = sessionManager.getfacebookid();
tvemail2 = (TextView) navHeader.findViewById(R.id.headeremail2);
tvemail2.setText(facebookid);
Log.e("emailfbinnavigation", "" + facebookid);
String facedp = sessionManager.getfacebookdp();
imgbtn2 = (ImageView) navHeader.findViewById(R.id.profileheader2);
Picasso.with(this).load(facedp).into(imgbtn2);
Log.e("imageview in image", "" + facedp);
Thanks In Advance
Try using SharedPreferences like below mentioned,
To save data:
SharedPreferences prefs = getSharedPreferences("my_prefs", MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putString("name", "Sahil");
editor.commit();
To retrieve data:
SharedPreferences prefs = getSharedPreferences("my_prefs", MODE_PRIVATE);
String name= prefs.getString("name");

Similar like Php session for Android Studio

I'm newbie for Android Studio & Java, i'm PHP user.
Just want to know how to do like PHP session in Android Studio.
No matter which Activity i go to, i can easily get the session value example like the User ID. (session["USERID"])
now the method i using is putting extra everytime i call for another activity.
i'm sure there will be a better way to do this.
anyone have any good suggestion?
PS: I google around and it keep return me PHP session tutorial/example/etc but not for Android Studio....(may be i enter work #keyword or sentence)
Thank You Very Much
Thanks to fillobotto & Arshid KV
here is my code
first_main activity
sharedpreference = getSharedPreferences(BIZInfo, Context.MODE_PRIVATE);
sharedpreference.edit().putString(userid, "12345");
sharedpreference.edit().commit();
second_main activity
sharedpreference = PreferenceManager.getDefaultSharedPreferences(this);
String restoredText = sharedpreference.getString("text", null);
if (restoredText != null) {
sp_name = sharedpreference.getString("userid", "No name defined");
}
Log.i("TAG", "onCreate: [" + sp_name + "]");
log show empty value/nothing...
what went wrong!?
You can use SharedPreferences as session in php
Demo code :-
Setting values in Preference:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Arshid");
editor.putInt("Age", 22);
editor.commit();
Retrieve data from preference:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int Age = prefs.getInt("Age", 0); //0 is the default value.
}
You were really near to the solution. This is what I use:
public static String getSession(Activity context) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
return sharedPreferences.getString("session", null);
}
public static void setSession(Activity context, String session) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("session", session);
editor.apply();
}
I'm actually passing the Activityto get SharedPreferences, but in this way you will obtain an instance of the object which is not activity-related.

Add data fromEeditText to double

I have an app where the user can enter an amount into an EditText but then I want to be able to add or subtract this to/from a double then be able to display this double with a TextView within another activity.
I'm not sure how to go about this and would appreciate some help.
Thanks in advance!
Edit: I forgot to mention that I also want this data to be kept between app launches/closes.
In your activity that accepts the input from the EditText:
double value = Double.parseDouble(yourEditText.getText().toString());
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (adding) {
value = prefs.getFloat("your.float.key", 0f) + value;
} else {
value = prefs.getFloat("your.float.key", 0f) - value;
}
SharedPreferences.Editor editor = prefs.edit();
editor.putFloat("your.float.key", value);
editor.apply();
In your activity that shows the value:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Double value = prefs.getFloat("your.float.key", 0f);
yourTextView.setText(value.toString());
Firstly you will need to parse the data from your EditText, you can get a String from an EditText using
EditText.getText().toString()
and then use some form of
Double.parseDouble(String)
Integer.parseInt(String)
to get a numeric value from the string, with which you can then use for whatever math you need. After you calculate this value you will want to send it to another Activity via intent
Intent i = new Intent(this, ActivityTwo.class);
i.putExtra("KEY", myDouble);
startActivity(i);
to receive the intent in your next activity use
Bundle extras = getIntent().getExtras();
if (extras != null) {
Double myDouble = extras.getDouble("KEY");
}
and then if you want to save the value you will want to look into SharedPreferences
to save
SharedPreferences prefs = getSharedPreferences("KEY", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putFloat("KEY", myFloat);
editor.commit();
to get
SharedPreferences prefs = getSharedPreferences("KEY", Context.MODE_PRIVATE);
myFloat = prefs.getFloat("KEY", myFloat);

Receive the token,userid using SharedPreferences.Editor in Android

Hi i have one doubt that how could i pass and receive the token using SharedPreferences.Editor
i have tried to pass the token by using:
appSharedPrefs = this.getSharedPreferences("Login", MODE_PRIVATE);
prefsEditor = appSharedPrefs.edit();
prefsEditor.putString("Userid", mUserid );
prefsEditor.putString("Token", mToken );
prefsEditor.putString("UserName", mUserName );
prefsEditor.putString("Password", mPassword );
prefsEditor.commit();
to pass the userid is right i think but how could i receive the username with userid in next Activity.Need Help!! Thanks
SharedPreferences prefs;
prefs = this.getSharedPreferences("Login", MODE_PRIVATE);
String mUserid = prefs.getString("Userid", "NA");
String mToken = prefs.getString("Token", "NA" );
String mUserName = prefs.getString("UserName", "NA");
String mPassword = prefs.getString("Password", "NA");
NA is the default value passed to the String here, change it as you will.
Also read up http://developer.android.com/reference/android/content/SharedPreferences.html
You can get all the details in any screen if you have already saved it to SharedPreferences. You can git it in a below manner.
SharedPreferences pref = this.getSharedPreferences("Login", MODE_PRIVATE); // Get reference if SharedPreference
String userid = pref.getString("Userid", "no name");
String token = pref.getString("Token", "no token");
String userName = pref.getString("UserName","no username");
String mPass = pref.getString("Password","no pass");

Categories

Resources