Android-session-management

提供:Dev Guides
移動先:案内検索

Android-セッション管理

セッションは、アプリケーションの外部にユーザーデータを保存するときに役立ちます。これにより、次回ユーザーがアプリケーションを使用するときに、詳細を簡単に取得して、それに応じて実行できます。

これはさまざまな方法で実行できます。 しかし、これを行う最も簡単で素晴らしい方法は、*共有設定*です。

共有設定

共有設定では、キーと値のペアの形式でデータを保存および取得できます。 共有設定を使用するには、設定の値を含むファイルを指すSharedPreferenceインスタンスを返すgetSharedPreferences()メソッドを呼び出す必要があります。

SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

SharedPreferences.Editorクラスを使用して、sharedpreferencesに何かを保存できます。 SharedPreferenceインスタンスの編集メソッドを呼び出し、エディターオブジェクトで受け取ります。 その構文は-

Editor editor = sharedpreferences.edit();
editor.putString("key", "value");
editor.commit();

putStringメソッドとは別に、エディタークラスで使用可能なメソッドがあり、共有設定内のデータを操作できます。 それらは次のようにリストされています-

Sr.No Mode & description
1

apply()

これは抽象メソッドです。 エディターから呼び出しているsharedPreferenceオブジェクトに変更をコミットします

2

clear()

エディターからすべての値を削除します

3

remove(String key)

キーがパラメーターとして渡された値を削除します

4

putLong(String key, long value)

設定エディターで長い値を保存します

5

putInt(String key, int value)

設定エディターに整数値を保存します

6

putFloat(String key, float value)

プリファレンスエディターにfloat値を保存します

共有設定によるセッション管理

共有設定からセッション管理を実行するには、 onResume メソッドで共有設定に保存されている値またはデータを確認する必要があります。 データがない場合は、新しくインストールされたアプリケーションを最初から開始します。 ただし、データを取得した場合は、ユーザーがデータを残したところから始めます。 それは以下の例で示されています-

以下の例は、セッション管理の使用方法を示しています。 初めてログインできる基本的なアプリケーションを作成します。 そして、ログアウトせずにアプリケーションを終了すると、アプリケーションを再度起動すると同じ場所に戻ります。 ただし、アプリケーションからログアウトすると、メインのログイン画面に戻ります。

この例を試すには、実際のデバイスまたはエミュレーターでこれを実行する必要があります。

Steps Description
1 You will use android studio IDE to create an Android application under a package com.example.sairamkrishna.myapplication.
2 Modify src/MainActivity.java file to add progress code to add session code.
3 Create New Activity and it name as second.java.Edit this file to add progress code to add session code.
4 Modify res/layout/activity_main.xml file to add respective XML code.
5 Modify res/layout/second_main.xml file to add respective XML code.
7 Run the application and choose a running android device and install the application on it and verify the results.
*MainActivity.java* のコンテンツは次のとおりです。
package com.example.sairamkrishna.myapplication;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
   EditText ed1,ed2,ed3;
   Button b1;
   Intent in;

   public static final String MyPREFERENCES = "MyPrefs" ;
   public static final String Name = "nameKey";
   public static final String Phone = "phoneKey";
   public static final String Email = "emailKey";
   SharedPreferences sharedpreferences;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      ed1=(EditText)findViewById(R.id.editText);
      ed2=(EditText)findViewById(R.id.editText2);
      ed3=(EditText)findViewById(R.id.editText3);

      b1=(Button)findViewById(R.id.button);
      sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

      b1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            String n  = ed1.getText().toString();
            String ph  = ed2.getText().toString();
            String e  = ed3.getText().toString();

            SharedPreferences.Editor editor = sharedpreferences.edit();

            editor.putString(Name, n);
            editor.putString(Phone, ph);
            editor.putString(Email, e);
            editor.commit();

            in = new Intent(MainActivity.this,second_main.class);
            startActivity(in);
         }
      });
   }
}
*second_main.java* の内容は次のとおりです。
package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class second_main extends Activity {
   Button bu=null;
   Button bu2=null;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.second_main);

      bu=(Button)findViewById(R.id.button2);
      bu2=(Button)findViewById(R.id.button3);
   }

   public  void logout(View view){
      SharedPreferences sharedpreferences = getSharedPreferences(MainActivity.MyPREFERENCES, Context.MODE_PRIVATE);
      SharedPreferences.Editor editor = sharedpreferences.edit();
      editor.clear();
      editor.commit();
   }

   public void close(View view){
      finish();
   }
}
*activity_main.xml* の内容は次のとおりです。
<?xml version="1.0" encoding="utf-8"?>
<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:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Shared Preference"
      android:id="@+id/textView"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:textSize="35dp"/>

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials Point"
      android:id="@+id/textView2"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true"
      android:textSize="35dp"
      android:textColor="#ff16ff01"/>

   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText"
      android:layout_below="@+id/textView2"
      android:layout_marginTop="67dp"
      android:hint="Name"
      android:layout_alignParentRight="true"
      android:layout_alignParentEnd="true"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true"/>

   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText2"
      android:layout_below="@+id/editText"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true"
      android:layout_alignParentRight="true"
      android:layout_alignParentEnd="true"
      android:hint="Pass"/>

   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText3"
      android:layout_below="@+id/editText2"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true"
      android:layout_alignParentRight="true"
      android:layout_alignParentEnd="true"
      android:hint="Email"/>

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="login"
      android:id="@+id/button"
      android:layout_below="@+id/editText3"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="50dp"/>

</RelativeLayout>
*second_main.xml* の内容は次のとおりです。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical" android:layout_width="match_parent"
   android:layout_height="match_parent">

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Logout"
      android:onClick="logout"
      android:id="@+id/button2"
      android:layout_gravity="center_horizontal"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="191dp"/>

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Close"
      android:onClick="close"
      android:id="@+id/button3"
      android:layout_below="@+id/button2"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="69dp"/>

</RelativeLayout>
*Strings.xml* の内容は次のとおりです。
<resources>
   <string name="app_name">My Application</string>
</resources>
*AndroidManifest.xml* のコンテンツは次のとおりです。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sairamkrishna.myapplication" >

   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >

      <activity
         android:name=".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=".second"></activity>

   </application>
</manifest>

アプリケーションを実行してみましょう。 環境のセットアップ中にAVDを作成したと思います。 Androidスタジオからアプリを実行するには、プロジェクトのアクティビティファイルの1つを開き、ツールバーの[画像の実行:/android/images/eclipse_run.jpg [Eclipse Run Icon]アイコンをクリックします。 AndroidスタジオはAVDにアプリをインストールして起動し、セットアップとアプリケーションで問題がなければ、次のエミュレータウィンドウが表示されます-

Androidセッション管理チュートリアル

ユーザー名とパスワードを入力します*(好きなものを入力しますが、入力した内容は覚えておいてください)*、ログインボタンをクリックします。 それは以下の画像に示されています-

Androidセッション管理チュートリアル

ログインボタンをクリックすると、このようこそ画面が表示されます。 これで、ログイン情報が共有設定に保存されます。

Androidセッション管理チュートリアル

[ログアウトせずに終了]ボタンをクリックすると、ホーム画面に戻り、設定ファイルの出力は次の画像のようになります。

Androidセッション管理チュートリアル

myPref.xmlファイルをメモファイルとして開くと、次のようになります。

Androidセッション管理チュートリアル

ログアウトボタンをクリックすると、設定値が消去されます。 入力として異なる値を入力した場合、それらの値をXMLの設定として入力します。