A=Shared Preferences as the name shows that sharing the preferences. And the meaning of preferences here is some data which will be shared.
Q=Why we need shared preferences in applications?
A=We don't need it in every apps but the apps which need user login then there it is needed.
Now the question is why we need this for login apps
Let's take Facebook app as example
:When an user open app first time in their phone after install then they have to enter their login details(username and password) and after successful login we use Facebook app for sometime and came out of the app.
Now when we again open the app then it will not showing login activity/screen and this happen because of shared preferences.
The login data is saved in local file of Facebook and every time time we open Facebook in out phone then it will go through that file and check the data and if it's correct then it will directly take us to our main data screen and not in login screen.
Now let's understand this with some code
and here SharedPreferences will be used in two places which are below
1.In Main Activity > onCreate
SharedPreferences preferences1=getSharedPreferences("loginData",0);
String b=preferences1.getString("is Login","no");
if(b.equals("yes")){
Intent intent=new Intent(this,logoutActivity.class);
startActivity(intent);
finish();
}
2.In Main Activity > onClickOnLogin
Intent intent=new Intent(this,logoutActivity.class);
startActivity(intent);
SharedPreferences preferences=getSharedPreferences("loginData",0);
SharedPreferences.Editor editor=preferences.edit();
editor.putString("isLogin","yes");
editor.apply();Above we used intent to changed activity when click on login button and this login button
will do 2 works for us where
- It will save the data in shared preference
- It will changed the activity/screen so that next time when we will run our app then it will not gonna show the login screen.
Thank you and if you have any doubts regarding this topic then feel free to contact me...