Android session using SharedPreferences example

In Android, if you are making an application where you need to manage sessions for your users, then SharedPreferences is the solution for that.

Here is an example that explains how to use SharedPreferences in your app.

Create class Session.java and put the code below into

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.session.app;

import android.content.Context;
import android.content.SharedPreferences;

public class Session {
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;
    Context context;
    public static final String SESSION_NAME = "SESSION";

    public Session (Context context){
        this.context = context;
        sharedPreferences = context.getSharedPreferences(SESSION_NAME, Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
    }

    public void setUserLoggedIn(boolean loggedin, String username) {
        editor.putBoolean("IsLoggedIn", loggedin);
        editor.putString("Username", username);
        editor.apply();
    }

    public boolean isLoggedIn(){
        return sharedPreferences.getBoolean("IsLoggedIn", false);
    }
    public void logoutUser(){
        editor.putBoolean("IsLoggedIn", false);
        editor.clear();
        editor.apply();
    }
    public String getUsername(){
        return sharedPreferences.getString("Username", "");
    }
}

Next how to use this session In your Activity.java file 


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.session.app;

import android.content.Context;
import android.app.Activity;
import android.os.Bundle;

public class LoginActivity extends Activity {
    Session session;
    Context ctx = this;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        session=new Session(this);
		
		if(session.isLoggedIn()){	//Check if user already logged in 
			session.getUsername();	//Get Username from session
		}
	}
	
	public void setUserLoggedin(){
		String LoginUsername="User123";
		session.setUserLoggedIn(true, LoginUsername); //Here you can user session
	}
	
	public void logoutUser(){
		session.logoutUser();	//this will logout the user from session
	}
	
}

That's it, you can use this SharedPreferences (Session) according to your requirement.

Happy Coding!
Thanks.

Comments

Post a Comment