How to Maintain Session in Android(Shared Prefrences)


Hey, friends in this Blog I will tell you how you can maintain Session in Android App.
In Android, we use SharedPreference to maintain Session.
Before Starting blog we should know about what is a session and why it's used.

what is the session in Android?
whenever you start any application first time you fill login detail first time after that
whenever next time you open the app you don't need to login in the app this is happening due to session maintained inside applications.

How to do that?
we have to sore details of the user whenever he login first time in the application the when the user again open app check if detail store if details available then without going to login page go directly on the home page.

Steps to do that-
Make a new Android Studio project and make login Screen with uid and pass.




2. Now you need to create another class to store data with help of shared preferences.
 create a class name Session.java .

3.Make a constructor and pass context in it and create SharedPrefrence inside Session class.



4. Now I have created one more Activity name as SecondActivity.

5.In Session create  a private String uid and create its getter and setter method.then
when in getter store value in shared preference and setter return value by sharedPreference Like below code.

 ************************************************************************
  ************************************************************************
  ************************************************************************


6.Now in MainActivity .java in click of button save uid and go to Second Activity

7.Then in oncreate methord if value is not null in SharedPreference class then go on SecondActivity directly.
Full code of MainActivity.java look like-
8.now if we launch app and fill detail first time it will go to SecondActivity but wheen
we relaunch it directly go on SecondActivity


                               Full Project Code-CLICK HERE

Post a Comment

0 Comments