Android-shared-preferences

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

Android-共有設定

Androidは、アプリケーションのデータを保存する多くの方法を提供します。 この方法の1つは、共有設定と呼ばれます。 共有設定では、キーと値のペアの形式でデータを保存および取得できます。

共有設定を使用するには、設定の値を含むファイルを指すSharedPreferenceインスタンスを返すgetSharedPreferences()メソッドを呼び出す必要があります。

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

最初のパラメーターはキーで、2番目のパラメーターはMODEです。 プライベートとは別に、以下にリストされている利用可能な他のモードがあります-

Sr.No Mode & description
1

MODE_APPEND

これにより、既存の設定に新しい設定が追加されます

2

MODE_ENABLE_WRITE_AHEAD_LOGGING

データベースオープンフラグ。 設定すると、デフォルトで先読みロギングが有効になります

3

MODE_MULTI_PROCESS

このメソッドは、sharedpreferenceインスタンスがすでにロードされている場合でも、設定の変更をチェックします

4

MODE_PRIVATE

このモードを設定することにより、ファイルは呼び出し側アプリケーションを使用してのみアクセスできます

5

MODE_WORLD_READABLE

このモードでは、他のアプリケーションが設定を読み取ることができます

6

MODE_WORLD_WRITEABLE

このモードでは、他のアプリケーションが設定を書き込むことができます

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値を保存します

この例は、共有設定の使用方法を示しています。 アプリケーションが閉じられたときに値が保存され、再び開かれたときに元に戻されるいくつかのテキストフィールドを含む画面を表示します。

この例を試すには、以下の手順に従ってアプリケーションを開発した後、実際のデバイスでこれを実行する必要があります-

Steps Description
1 You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication.
2 Modify src/MainActivity.java file to add progress code to display the spinning progress dialog.
3 Modify res/layout/activity_main.xml file to add respective XML code.
4 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.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

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

   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();
            Toast.makeText(MainActivity.this,"Thanks",Toast.LENGTH_LONG).show();
         }
      });
   }

}

変更されたメインアクティビティファイルの内容は次のとおりですres/layout/activiy_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="Save"
      android:id="@+id/button"
      android:layout_below="@+id/editText3"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="50dp"/>

</RelativeLayout>

以下は、ファイル* res/values/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>

   </application>
</manifest>

アプリケーションを実行してみましょう。 実際のAndroidモバイルデバイスをコンピューターに接続していると思います。 Androidスタジオからアプリを実行するには、プロジェクトのアクティビティファイルの1つを開き、ツールバーの[画像を実行:/android/images/eclipse_run.jpg [Eclipse Run Icon]アイコンをクリックします。 アプリケーションを開始する前に、Androidスタジオは次のウィンドウを表示して、Androidアプリケーションを実行するオプションを選択します。

Anroid SharedPreferences Tutorial

オプションとしてモバイルデバイスを選択し、次の画面を表示するモバイルデバイスを確認します-

次に、フィールドにテキストを入力します。 ランダムな名前やその他の情報を入れて、保存ボタンをクリックしてください。

Anroid SharedPreferences Tutorial

保存ボタンを押すと、テキストが共有設定に保存されます。 戻るボタンを押して、アプリケーションを終了します。 ここでもう一度開くと、アプリケーションに書き戻されたすべてのテキストが表示されます。

Anroid SharedPreferences Tutorial