Android Session Management Using SharedPreferences

Here you will get an example of android session management using SharedPreferences.

If you don’t know about SharedPreferences then read my previous tutorial: Android SharedPreferences Example

In this tutorial you will learn how to manage login session of user. The whole process works like this:

  • When user enters correct username and password then the login details are stored in SharedPreferences and user is redirected to home or welcome screen. After opening home screen I have killed or finished login screen so that user can’t go back.
  • Now even if user closes the app and open it again then he did not require to enter the login details because the details are already stored in SharedPreferences. He will be directly redirected to home screen.
  • When user click on logout button, the data stored in SharedPreferences is deleted and login session is destroyed. The user is redirected to login screen and home screen is killed so that he can’t go back.

 

In this way user login session is managed. Session management concept is very important and frequently used while developing any android app.

Below I have shared an example that will help you to implement it in your app.

 

Android Session Management Using SharedPreferences

Create a new project with package name com.sessionmanagement.

Now create two blank activities with name MainActivity and Home. By default you may get MainActivity, in that case you have to create only Home activity.

Now add following code in respective files.

 

Note: Here I have used programmer as username and password. You can change the login details according to you or you can get the details from server or database and then compare with it.

 

MainActivity.java

 

activity_main.xml

 

Home.java

 

activity_home.xml

 

Finally run and test your app.

 

Output

Android Session Management Using SharedPreferences

Android Session Management Using SharedPreferences

Comment below if you have any queries related to above android session management tutorial.

Happy Coding!! 🙂 🙂

11 thoughts on “Android Session Management Using SharedPreferences”

  1. same code i wrote but while im going to run, that time app crashed and asking for wait or close, anyone can tell why it is so…??
    thanks in advanse

  2. Hi Neeraj, I have some error like this, java.lang.NullPointerException: Attempt to invoke virtual method ‘android.text.Editable android.widget.EditText.getText()’ on a null object reference. can you solve this probel, please ? I’m newbie.

  3. i couldn’t find a line which shows the connection to any database. or this tutorial just give an idea to implement without the database?

    1. Yes this tutorial is written to explain the implementation of session management without database. You can implement it along with database.

Leave a Comment

Your email address will not be published. Required fields are marked *