In my app i want to create a session for login and log out.
I dont have any idea how to work with session. Anybody help me by giving some sample example.
In my app i want to create a session for login and log out.
I dont have any idea how to work with session. Anybody help me by giving some sample example.
I think the session object should be a static object declared and initialized when your application starts running. I have met this problem and decided to put my session object in a utils class which contains mathods used by every activity in my app.
Here is a short example:
create a class for utils which will contain session object, Session is the class by which you implement your session object. It can contain, for example, userId, userName, etc.:
public class Utils {
public static Session mySessionObject = null;
}
When login button is pushed initialize your session object:
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Utils.mySessionObject = new Session();
//some extra initalization, for example setting userId
}
});
On logout you can destroy your session object.
Here is a link telling more about sessions.
If you're trying to keep some data in memory during the life of your app, maybe you should consider using a singleton pattern. I use it this way.
public class Session {
@SuppressWarnings("unused")
private GoogleAnalyticsTracker mGoogleAnalyticsTracker = null;
private static Session sInstance = null;
private Session(Context pContext) {
mGoogleAnalyticsTracker = GoogleAnalyticsTracker.getInstance();
mGoogleAnalyticsTracker.startNewSession(pContext.getString(R.string.google_analytics_web_property_id),
pContext.getResources().getInteger(R.integer.google_analytics_tracking_time_in_seconds),
pContext.getApplicationContext());
}
public static void init(Context pContext) {
sInstance = new Session(pContext);
}
public static Session getInstance() {
return sInstance;
}
}
I load the session during the splash screen. Keep in mind that with this solution you shouldn't keep big objects in memory.
Session.init(this);
For example I use it for the Google Analytics tracker initialization, development mode, etc