There are two ways to save data globally:
1. Save data in global variables:If we are storing data in global variable , data will be lost once user closes the application.
2. Save the data in shared preferences:
If we are Storing data in shared preferences will be persistent to all application even after user closes the application. You can save key, value pair data in Shared preferences.
FILE : UserSessionManager.java
This class contain all user session related functions.
In this class file creating SharedPreferences and inserting / updating / deleting user session data from SharedPreferences.
further explanation given as comment in class code.
- package com.androidexample.usersessions;
- import java.util.HashMap;
- import android.content.Context;
- import android.content.Intent;
- import android.content.SharedPreferences;
- import android.content.SharedPreferences.Editor;
- public class UserSessionManager {
- // Shared Preferences reference
- SharedPreferences pref;
- // Editor reference for Shared preferences
- Editor editor;
- // Context
- Context _context;
- // Shared pref mode
- int PRIVATE_MODE = 0;
- // Sharedpref file name
- private static final String PREFER_NAME = "AndroidExamplePref";
- // All Shared Preferences Keys
- private static final String IS_USER_LOGIN = "IsUserLoggedIn";
- // User name (make variable public to access from outside)
- public static final String KEY_NAME = "name";
- // Email address (make variable public to access from outside)
- public static final String KEY_EMAIL = "email";
- // Constructor
- public UserSessionManager(Context context){
- this._context = context;
- pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
- editor = pref.edit();
- }
- //Create login session
- public void createUserLoginSession(String name, String email){
- // Storing login value as TRUE
- editor.putBoolean(IS_USER_LOGIN, true);
- // Storing name in pref
- editor.putString(KEY_NAME, name);
- // Storing email in pref
- editor.putString(KEY_EMAIL, email);
- // commit changes
- editor.commit();
- }
- /**
- * Check login method will check user login status
- * If false it will redirect user to login page
- * Else do anything
- * */
- public boolean checkLogin(){
- // Check login status
- if(!this.isUserLoggedIn()){
- // user is not logged in redirect him to Login Activity
- Intent i = new Intent(_context, LoginActivity.class);
- // Closing all the Activities from stack
- i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
- // Add new Flag to start new Activity
- i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- // Staring Login Activity
- _context.startActivity(i);
- return true;
- }
- return false;
- }
- /**
- * Get stored session data
- * */
- public HashMap
getUserDetails(){ //Use hashmap to store user credentials HashMap user = new HashMap (); // user name user.put(KEY_NAME, pref.getString(KEY_NAME, null)); // user email id user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null)); // return user return user; } /** * Clear session details * */ public void logoutUser(){ // Clearing all user data from Shared Preferences editor.clear(); editor.commit(); // After logout redirect user to Login Activity Intent i = new Intent(_context, LoginActivity.class); // Closing all the Activities i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // Add new Flag to start new Activity i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // Staring Login Activity _context.startActivity(i); } // Check for login public boolean isUserLoggedIn(){ return pref.getBoolean(IS_USER_LOGIN, false); } }
FILE : LoginActivity.java
This is the first screen( Login screen ).
For Login using Username: admin and Password: admin
Using createUserLoginSession() to save user data in SharedPreferences for further use.
- package com.androidexample.usersessions;
- import android.app.Activity;
- import android.content.Intent;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.Toast;
- public class LoginActivity extends Activity {
- Button btnLogin;
- EditText txtUsername, txtPassword;
- // User Session Manager Class
- UserSessionManager session;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_login);
- // User Session Manager
- session = new UserSessionManager(getApplicationContext());
- // get Email, Password input text
- txtUsername = (EditText) findViewById(R.id.txtUsername);
- txtPassword = (EditText) findViewById(R.id.txtPassword);
- Toast.makeText(getApplicationContext(),
- "User Login Status: " + session.isUserLoggedIn(),
- Toast.LENGTH_LONG).show();
- // User Login button
- btnLogin = (Button) findViewById(R.id.btnLogin);
- // Login button click event
- btnLogin.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View arg0) {
- // Get username, password from EditText
- String username = txtUsername.getText().toString();
- String password = txtPassword.getText().toString();
- // Validate if username, password is filled
- if(username.trim().length() > 0 && password.trim().length() > 0){
- // For testing puspose username, password is checked with static data
- // username = admin
- // password = admin
- if(username.equals("admin") && password.equals("admin")){
- // Creating user login session
- // Statically storing name="Android Example"
- // and email="androidexample84@gmail.com"
- session.createUserLoginSession("Android Example",
- "androidexample84@gmail.com");
- // Starting MainActivity
- Intent i = new Intent(getApplicationContext(), MainActivity.class);
- i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
- // Add new Flag to start new Activity
- i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- startActivity(i);
- finish();
- }else{
- // username / password doesn't match&
- Toast.makeText(getApplicationContext(),
- "Username/Password is incorrect",
- Toast.LENGTH_LONG).show();
- }
- }else{
- // user didn't entered username or password
- Toast.makeText(getApplicationContext(),
- "Please enter username and password",
- Toast.LENGTH_LONG).show();
- }
- }
- });
- }
- }
FILE : activity_login.xml
This file is used as layout file in LoginActivity.java.
It will create login screen design.
android:layout_width
=
"match_parent"
android:layout_height
=
"match_parent"
android:orientation
=
"vertical"
android:padding
=
"10dip"
>
<
TextView
android:layout_width
=
"fill_parent"
android:layout_height
=
"wrap_content"
android:text
=
"Username (Enter 'admin')"
android:singleLine
=
"true"
android:layout_marginBottom
=
"5dip"
/>
<
EditText
android:id
=
"@+id/txtUsername"
android:layout_width
=
"fill_parent"
android:layout_height
=
"wrap_content"
android:layout_marginBottom
=
"10dip"
/>
<
TextView
android:layout_width
=
"fill_parent"
android:layout_height
=
"wrap_content"
android:text
=
"Password (Enter 'admin')"
android:layout_marginBottom
=
"5dip"
/>
<
EditText
android:id
=
"@+id/txtPassword"
android:layout_width
=
"fill_parent"
android:layout_height
=
"wrap_content"
android:layout_marginBottom
=
"20dip"
android:password
=
"true"
android:singleLine
=
"true"
/>
<
Button
android:id
=
"@+id/btnLogin"
android:layout_width
=
"fill_parent"
android:layout_height
=
"wrap_content"
android:text
=
"Login"
/>
</
LinearLayout
>
FILE : MainActivity.java
This is the welcome screen after user login.
Get user data from SharedPreferences and show on activity.
- package com.androidexample.usersessions;
- import java.util.HashMap;
- import android.app.Activity;
- import android.os.Bundle;
- import android.text.Html;
- import android.view.View;
- import android.widget.Button;
- import android.widget.TextView;
- import android.widget.Toast;
- public class MainActivity extends Activity {
- // User Session Manager Class
- UserSessionManager session;
- // Button Logout
- Button btnLogout;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- // Session class instance
- session = new UserSessionManager(getApplicationContext());
- TextView lblName = (TextView) findViewById(R.id.lblName);
- TextView lblEmail = (TextView) findViewById(R.id.lblEmail);
- // Button logout
- btnLogout = (Button) findViewById(R.id.btnLogout);
- Toast.makeText(getApplicationContext(),
- "User Login Status: " + session.isUserLoggedIn(),
- Toast.LENGTH_LONG).show();
- // Check user login (this is the important point)
- // If User is not logged in , This will redirect user to LoginActivity
- // and finish current activity from activity stack.
- if(session.checkLogin())
- finish();
- // get user data from session
- HashMap
user = session.getUserDetails(); // get name String name = user.get(UserSessionManager.KEY_NAME); // get email String email = user.get(UserSessionManager.KEY_EMAIL); // Show user data on activity lblName.setText(Html.fromHtml("Name: " + name + "")); lblEmail.setText(Html.fromHtml("Email: " + email + "")); btnLogout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // Clear the User session data // and redirect user to LoginActivity session.logoutUser(); } }); } }
FILE : activity_login.xml
This file is used as layout file in MainActivity.java.
It will create Welcome screen (after login) design.
android:layout_width
=
"match_parent"
android:layout_height
=
"match_parent"
android:orientation
=
"vertical"
android:padding
=
"10dip"
>
<
TextView
android:id
=
"@+id/lblName"
android:layout_width
=
"fill_parent"
android:layout_height
=
"wrap_content"
android:singleLine
=
"true"
android:layout_marginTop
=
"40dip"
android:layout_marginBottom
=
"10dip"
/>
<
TextView
android:id
=
"@+id/lblEmail"
android:layout_width
=
"fill_parent"
android:layout_height
=
"wrap_content"
android:singleLine
=
"true"
android:layout_marginBottom
=
"40dip"
/>
<
Button
android:id
=
"@+id/btnLogout"
android:layout_width
=
"fill_parent"
android:layout_height
=
"wrap_content"
android:text
=
"Logout"
/>
</
LinearLayout
>
No comments:
Post a Comment