Android : Session management ด้วย Shared preference

ห่างหายจากการเขียนบล๊อคไปนานแสนนาน วันนี้เจอหัวข้อน่าสนใจเลยได้แรงบันดาลใจนำมาเขียนครับ หัวข้อในวันนี้คือหากเราต้องการบริหารจัดการ session บน android เราจะมีวิธีการอย่างไรซึ่งในตัวอย่างนี้ผมนำ Shared preference มาช่วยในการเก็บข้อมูลซึ่งเห็นว่าวิธีการนี้จะมีประโยชน์กับหลายๆคนจึงนำมาเผยแพร่ต่อ ซึ่งได้ code ตัวอย่างมากจาก http://www.tutorialspoint.com/

Session คืออะไร ??

หลายคนที่เคยผ่านการทำเว็บมาก็จะรู้จัก session อยู่แล้ว เจ้าตัว Session ทำหน้าที่เก็บข้อมูลต่างๆไว้ในระบบ (ไม่ใช่ฐานข้อมูล) หากคนที่ไม่มีพื้นฐานความเข้าใจ session มาก่อนให้มองว่า session คือตัวแปรที่ทุกหน้าในโปรแกรมสามารถเรียกใช้ได้ โดยส่วนมากเราจะพบเจอในระบบ ตะกร้าสินค้า หรือการเก็บค่าของผู้ใช้งานว่าตอนนี้ใครเป็นผู้ใช้งานระบบอยู่

Shared preference คืออะไร ??

เป็นการเก็บข้อมูลรูปแบบหนึ่งใน Android จะทำการเก็บข้อมูลนั้นๆไว้ในแอพพลิเคชั่น โดยต่อให้ปิดแอพพลิเคชั่นไปข้อมูลนั้นก็ยังคงอยู่ (หากลบ แอฟฟิเคชั่นจะหายนะ) ข้อดีของ Shared preference คือทุก Activity สามารถเรียกใช้ข้อมูลได้ โดย Shared preference มีข้อจำกัดว่าสามารถเก็บข้อมูลได้แค่ตัวแปรพื้นฐาน เช่น int , String , boolean , float เป็นต้น

การทำ Session Management ด้วย Shared preference

ตัวอย่างข้างล่างนี้อธิบาย Source Code ส่วนที่เก็บข้อมูลด้วย Shared preference โดยมีตัวอย่างทั้งการเรียกใช้ , เพิ่ม และ ลบข้อมูลจาก Shared preference

 

MainActivity

function login() ทำหน้าที่เพิ่มข้อมูล name และ pass ใน Shared preference  และ onResume() ตรวจว่ามีข้อมูลอยู่ใน Shared preference อยู่แล้วไหมโดยหากมีข้อมูล  name และ pass อยู่แล้วก็จะข้ามไปหน้า WelcomeActivity เลย

 package com.example.sessionmanagement;  
 import android.app.Activity;  
 import android.content.Context;  
 import android.content.Intent;  
 import android.content.SharedPreferences;  
 import android.content.SharedPreferences.Editor;  
 import android.os.Bundle;  
 import android.view.Menu;  
 import android.view.View;  
 import android.widget.EditText;  
 public class MainActivity extends Activity {  
   private EditText username,password;  
   public static final String MyPREFERENCES = "MyPrefs" ;  
   public static final String name = "nameKey";   
   public static final String pass = "passwordKey";   
   SharedPreferences sharedpreferences;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState);  
    setContentView(R.layout.activity_main);  
    username = (EditText)findViewById(R.id.editText1);  
    password = (EditText)findViewById(R.id.editText2);  
   }  
   @Override  
   protected void onResume() {  
    sharedpreferences=getSharedPreferences(MyPREFERENCES,   
    Context.MODE_PRIVATE);  // ดึง share preference ชื่อ MyPrefs เก็บไว้ในตัวแปร sharedpreferences
    if (sharedpreferences.contains(name))   // ตรวจสอบ name ใน preference
    {  
    if(sharedpreferences.contains(pass)){  // ตรวจสอบ pass ใน preference
      Intent i = new Intent(this,com.example.sessionmanagement.  
      Welcome.class);  
      startActivity(i);  
    }  
    }  
    super.onResume();  
   }  
   public void login(View view){  
    Editor editor = sharedpreferences.edit();  
    String u = username.getText().toString();  
    String p = password.getText().toString();  
    editor.putString(name, u);  // preferance เก็บค่า name จาก edittext
    editor.putString(pass, p);  // preferance เก็บค่า pass จาก edittext
    editor.commit();  // ยืนยันการแก้ไข preferance
    Intent i = new Intent(this,com.example.  
    sessionmanagement.Welcome.class);  
    startActivity(i);  
   }  
   @Override  
   public boolean onCreateOptionsMenu(Menu menu) {  
   // Inflate the menu; this adds items to the action bar if it is present.  
   getMenuInflater().inflate(R.menu.main, menu);  
   return true;  
   }  
 }  

WelcomeActivity

หากมากถึงหน้า WelcomeActivity แล้ว แสดงว่า name และ pass อยู่ในShared preference (ระบบได้จดจำแล้วว่าผู้ใช้คนไหนใช้งานอยู่) หากผู้ใช้ต้องการออกจากระบบมี 2 function คือ logout() และ exit() โดย logout จะทำการลบค่าผู้ใช้ออกและปิดแอพพลิเคชั่น แต่ exit จะทำการออกจากแอพพลิเคชั่นโดยยังจำค่าผู้ใช้อยู่เมื่อเปิดใช้งานอีกครั้งแอพพลิเคชั่นจะยังคงเรียกใช้ค่าผู้ใช้เดิม

 package com.example.sessionmanagement;  
 import android.app.Activity;  
 import android.content.Context;  
 import android.content.SharedPreferences;  
 import android.content.SharedPreferences.Editor;  
 import android.os.Bundle;  
 import android.view.Menu;  
 import android.view.View;  
 public class Welcome extends Activity {  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState);  
    setContentView(R.layout.activity_welcome);  
   }  
   @Override  
   public boolean onCreateOptionsMenu(Menu menu) {  
    // Inflate the menu; this adds items to the action bar if it is present.  
    getMenuInflater().inflate(R.menu.welcome, menu);  
    return true;  
   }  
   public void logout(View view){  
    SharedPreferences sharedpreferences = getSharedPreferences  
    (MainActivity.MyPREFERENCES, Context.MODE_PRIVATE);  // ดึง share preference ชื่อ MyPrefs เก็บไว้ในตัวแปร sharedpreferences
    Editor editor = sharedpreferences.edit();  
    editor.clear();  // ทำการลบข้อมูลทั้งหมดจาก preferences
    editor.commit();  // ยืนยันการแก้ไข preferences
    moveTaskToBack(true);   
    Welcome.this.finish();  
   }  
   public void exit(View view){  
    moveTaskToBack(true);   
    Welcome.this.finish();  
   }  
 }  

——————– ถึงตรงนี้จะไม่อธิบายแล้วนะครับเป็นส่วนของ User Interface ——————–

activity_main.xml

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:tools="http://schemas.android.com/tools"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   android:paddingBottom="@dimen/activity_vertical_margin"  
   android:paddingLeft="@dimen/activity_horizontal_margin"  
   android:paddingRight="@dimen/activity_horizontal_margin"  
   android:paddingTop="@dimen/activity_vertical_margin"  
   tools:context=".MainActivity" >  
   <EditText  
    android:id="@+id/editText2"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:layout_alignRight="@+id/editText1"  
    android:layout_below="@+id/textView2"  
    android:ems="10"  
    android:inputType="textPassword" >  
   </EditText>  
   <TextView  
    android:id="@+id/textView1"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:layout_alignParentTop="true"  
    android:layout_marginTop="52dp"   
    android:text="@string/Username"  
    android:textAppearance="?android:attr/textAppearanceMedium" />  
   <EditText  
    android:id="@+id/editText1"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:layout_alignParentRight="true"  
    android:layout_alignTop="@+id/textView1"  
    android:layout_marginRight="16dp"  
    android:layout_marginTop="27dp"  
    android:ems="10" >  
    <requestFocus />  
   </EditText>  
   <TextView  
    android:id="@+id/textView2"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:layout_alignRight="@+id/textView1"  
    android:layout_below="@+id/editText1"  
    android:text="@string/Password"  
    android:textAppearance="?android:attr/textAppearanceMedium" />  
   <TextView  
    android:id="@+id/textView3"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:layout_above="@+id/editText1"  
    android:layout_centerHorizontal="true"  
    android:layout_marginBottom="22dp"  
    android:text="@string/Signin"  
    android:textAppearance="?android:attr/textAppearanceMedium" />  
   <Button  
    android:id="@+id/button1"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:layout_below="@+id/editText2"  
    android:layout_centerHorizontal="true"  
    android:layout_marginTop="45dp"  
    android:onClick="login"   // เรียกใช้ function login ไฟล์ MainActivity
    android:text="@string/Login" />  
 </RelativeLayout>  

activity_welcome.xml

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:tools="http://schemas.android.com/tools"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   android:paddingBottom="@dimen/activity_vertical_margin"  
   android:paddingLeft="@dimen/activity_horizontal_margin"  
   android:paddingRight="@dimen/activity_horizontal_margin"  
   android:paddingTop="@dimen/activity_vertical_margin"  
   tools:context=".Welcome" >  
   <Button  
    android:id="@+id/button1"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:layout_alignParentTop="true"  
    android:layout_centerHorizontal="true"  
    android:layout_marginTop="146dp"  
    android:onClick="logout"  // เรียกใช้ function logout หน้า WelcomActivity
    android:text="@string/logout" />  
   <TextView  
    android:id="@+id/textView1"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:layout_alignLeft="@+id/button1"  
    android:layout_alignParentTop="true"  
    android:layout_marginTop="64dp"  
    android:text="@string/title_activity_welcome"  
    android:textAppearance="?android:attr/textAppearanceLarge" />  
   <Button  
    android:id="@+id/button2"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:layout_below="@+id/button1"  
    android:layout_centerHorizontal="true"  
    android:layout_marginTop="43dp"  
    android:onClick="exit"  
    android:text="@string/exit" />  
 </RelativeLayout>  

string.xml

 <?xml version="1.0" encoding="utf-8"?>  
 <resources>  
   <string name="app_name">SessionManagement</string>  
   <string name="action_settings">Settings</string>  
   <string name="hello_world">Hello world!</string>  
   <string name="Username">Username</string>  
   <string name="Password">Password</string>  
   <string name="Signin">Sign In</string>  
   <string name="Login">Login</string>  
   <string name="logout">Logout</string>  
   <string name="title_activity_welcome">Welcome</string>  
   <string name="exit">Exit without logout</string>  
 </resources>  

AndroidManifest.xml

 <?xml version="1.0" encoding="utf-8"?>  
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
   package="com.example.sessionmanagement"  
   android:versionCode="1"  
   android:versionName="1.0" >  
   <uses-sdk  
    android:minSdkVersion="8"  
    android:targetSdkVersion="17" />  
   <application  
    android:allowBackup="true"  
    android:icon="@drawable/ic_launcher"  
    android:label="@string/app_name"  
    android:theme="@style/AppTheme" >  
    <activity  
      android:name="com.example.sessionmanagement.MainActivity"  
      android:label="@string/app_name" >  
      <intent-filter>  
       <action android:name="android.intent.action.MAIN" />  
       <category android:name="android.intent.category.LAUNCHER" />  
      </intent-filter>  
    </activity>  
    <activity  
      android:name="com.example.sessionmanagement.Welcome"  
      android:label="@string/title_activity_welcome" >  
    </activity>  
   </application>  
 </manifest>  

จบแล้วครับลอง copy ตัวอย่างไปทำความเข้าใจแล้วไปประยุกต์ใช้กับระบบของแต่ละคนนะครับ หวังว่าบทความนี้จะมีประโยชน์กับผู้ผ่านมาพบผมเห็นหากมีคำแนะนำอะไรคอมเม้นได้เลยนะครับ ในบทความต่อไปผมจะนำเสนอการเก็บ Object และ Collection ใน Shared preference ครับ

About octoboy


Android Developer, Study Master degree of Computer Engineering at Prince of Songkla university.

Related posts: