Check Out Mobile Application Proposal

Session Manager with SharedPreferences in Android , Global session manager .

We are going to create a global session manager class to store and get data from all over the android application. Here we are going to create with shared preferences and shared preferences editor.

private final SharedPreferences sharedPreferences;
private final SharedPreferences.Editor editor;

public SessionManager(Context context) {
sharedPreferences = context.getSharedPreferences("your preference name", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
}
public void setString(String key, String value){
editor.putString(key,value);
editor.commit();
}
public String getString(String key){
return sharedPreferences.getString(key,"");
}
public void setInt(String key, int value){
editor.putInt(key,value);
editor.commit();
}
public int getInt(String key){
return sharedPreferences.getInt(key,0);
}
public long getLong(String key){
return sharedPreferences.getLong(key,0);
}
public void setLong(String key, long value){
editor.putLong(key,value);
editor.commit();
}
public void setBoolean(String key, boolean value){
editor.putBoolean(key,value);
editor.commit();
}
public boolean getBoolean(String key){
return sharedPreferences.getBoolean(key,false);
}

The above class is the session manager . you can use this through the application.

SessionManager sessionManager = new SessionManager(context); 

Use the below code to store the data : 

 sessionManager.setString("status", "login"); 

Use the below code to get the data :

getString("status");

 

Thank you, Hope this will help you :) 

 

 

Comments