Receive the token,userid using SharedPreferences.Editor in Android - 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");

Related

SharedPreferences keep on returning default value

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

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

Why sharedpreference value not getting in when retrieving?

I aaded three shared preferences as below code. And I am able to retrieve onl n shared preference value.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("Loggedin",true);
editor.putString("userId",userid);
editor.putString("pwd",password);
editor.apply();
editor.commit();
I used the following code for retrieving from another activity. I am able to retrieve only the boolean value. Other values are not there. getting the default value for the string values. please help me.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Boolean loggedin=preferences.getBoolean("Loggedin", false);
String userId=preferences.getString("userId", "0");
String pwd=preferences.getString("pwd", "0");
check first the value u store in preferences are stored or not
using this code
Boolean loggedin=preferences.getBoolean("Loggedin", false);
String userId=preferences.getString("userId", null);
String pwd=preferences.getString("pwd", null);
if(userId==null || pwd==null)
{
//data not therer
}
else
{
//do something with data
}
and let me know if any error occured..
I think you're not getting the SharedPreferences in a correct way.
See the doc for ex: https://developer.android.com/training/basics/data-storage/shared-preferences.html
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
Also, you don't need to call apply() AND commit(). Just one of those is enough. See the javadoc for the differences btw them.
Use this code
String userId=preferences.getString("userId", null);
String pwd=preferences.getString("pwd", null);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Boolean loggedin=preferences.getBoolean("Loggedin", false);
String userId=preferences.getString("userId", "");
String pwd=preferences.getString("pwd", "");
if(userId==null || userId==""||pwd==null ||pwd=="")
{
}
else
{
}
Try code in this way.
Set values in First Activity
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("Loggedin",true);
editor.putString("userId",userid);
editor.putString("pwd",password);
editor.apply();
Retrieve value in Second Activity
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Boolean loggedin=preferences.getBoolean("Loggedin", false);
String userId=preferences.getString("userId", "");
String pwd=preferences.getString("pwd", "");
Used in that way for retrieve values from shared preferences for your code.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Boolean loggedin=preferences.getBoolean("Loggedin", false);
//Checking the value of userId and pwd,if they are null then there is no values of userId and pwd other than default.
if (userId != null && pwd != null) {
String userId = preferences.getString("userId", "0");
String pwd = preferences.getString("pwd", "0");
} else {
String userId = "0";
String pwd = "0";
}

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.

SharedPreferences in Android

I have used SharedPreferences to save some details in the Main Activity .Now i want to get the details in some other activity but i am not able to get them .
Code to save
public void saveInformation(String username,String password) {
SharedPreferences shared = getSharedPreferences("shared", MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putString("username", username);
editor.putString("password", password);
editor.commit();
}
Code to get
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String username = prefs.getString("username", null);
But this is not working for me . How could I get his?
May this help you:
Buddy Change these lines in your code to get:
SharedPreferences prefs = getSharedPreferences("shared", MODE_PRIVATE);
String username = prefs.getString("username","");
Code to get should be
SharedPreferences prefs = getSharedPreferences("shared", MODE_PRIVATE);

Categories

Resources