Android で SharedPreferences を使用して値を保存、取得、編集する方法 [終了]
-
26-09-2019 - |
質問
時間値を保存したいので、それを取得して編集する必要があります。どうすれば使えますか SharedPreferences
これをする?
解決
共有設定を取得するには、アクティビティで次の方法を使用してください。
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
設定を読み取るには:
String dateTimeKey = "com.example.app.datetime";
// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime());
設定を編集して保存するには
Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();
Android SDK のサンプル ディレクトリには、共有設定の取得と保存の例が含まれています。それは次の場所にあります。
<android-sdk-home>/samples/android-<platformversion>/ApiDemos directory
編集==>
の違いを書くことが重要であることに気づきました。 commit()
そして apply()
ここでも。
commit()
戻る true
値が正常に保存された場合、それ以外の場合 false
. 。値を SharedPreferences に保存します 同期的に.
apply()
2.3 で追加されたもので、成功しても失敗しても値を返しません。値はすぐに SharedPreferences に保存されますが、 非同期 専念。さらに詳しくは、 ここ.
他のヒント
共有設定で値を保存するには:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name","Harneet");
editor.apply();
共有設定から値を取得するには:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name", "");
if(!name.equalsIgnoreCase(""))
{
name = name + " Sethi"; /* Edit the value here*/
}
から編集 sharedpreference
からのデータ
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("text", mSaved.getText().toString());
editor.putInt("selection-start", mSaved.getSelectionStart());
editor.putInt("selection-end", mSaved.getSelectionEnd());
editor.apply();
sharedpreference
からへの を取得したデータ
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null)
{
//mSaved.setText(restoredText, TextView.BufferType.EDITABLE);
int selectionStart = prefs.getInt("selection-start", -1);
int selectionEnd = prefs.getInt("selection-end", -1);
/*if (selectionStart != -1 && selectionEnd != -1)
{
mSaved.setSelection(selectionStart, selectionEnd);
}*/
}
編集
私はAPI Demoサンプルから、このスニペットを取りました。それはそこにEditText
ボックスを持っていました。このcontext
ではrequired.Iが同じコメントしていない。
を書くために:の
SharedPreferences preferences = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Authentication_Id",userid.getText().toString());
editor.putString("Authentication_Password",password.getText().toString());
editor.putString("Authentication_Status","true");
editor.apply();
のへの読み取り:の
SharedPreferences prfs = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
String Astatus = prfs.getString("Authentication_Status", "");
最も簡単な方法:
保存するには、
getPreferences(MODE_PRIVATE).edit().putString("Name of variable",value).commit();
取得するには:
your_variable = getPreferences(MODE_PRIVATE).getString("Name of variable",default value);
プリファレンスの値を設定する:
// MY_PREFS_NAME - a static String variable like:
//public static final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.commit();
嗜好からデータを取得
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
}
詳細ます:
SharedPreferences preferences = getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("username", username.getText().toString());
editor.putString("password", password.getText().toString());
editor.putString("logged", "logged");
editor.commit();
あなたの好みをリセットするには、
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
シングルトン共有環境クラス。それは、将来的に他の人のために役立つことがあります。
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
public class SharedPref
{
private static SharedPreferences mSharedPref;
public static final String NAME = "NAME";
public static final String AGE = "AGE";
public static final String IS_SELECT = "IS_SELECT";
private SharedPref()
{
}
public static void init(Context context)
{
if(mSharedPref == null)
mSharedPref = context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
}
public static String read(String key, String defValue) {
return mSharedPref.getString(key, defValue);
}
public static void write(String key, String value) {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.putString(key, value);
prefsEditor.commit();
}
public static boolean read(String key, boolean defValue) {
return mSharedPref.getBoolean(key, defValue);
}
public static void write(String key, boolean value) {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.putBoolean(key, value);
prefsEditor.commit();
}
public static Integer read(String key, int defValue) {
return mSharedPref.getInt(key, defValue);
}
public static void write(String key, Integer value) {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.putInt(key, value).commit();
}
}
SharedPref.init()
上の単にコールMainActivity
SharedPref.init(getApplicationContext());
データを書き込むために、
SharedPref.write(SharedPref.NAME, "XXXX");//save string in shared preference.
SharedPref.write(SharedPref.AGE, 25);//save int in shared preference.
SharedPref.write(SharedPref.IS_SELECT, true);//save boolean in shared preference.
への読み取りデータ
String name = SharedPref.read(SharedPref.NAME, null);//read string in shared preference.
int age = SharedPref.read(SharedPref.AGE, 0);//read int in shared preference.
boolean isSelect = SharedPref.read(SharedPref.IS_SELECT, false);//read boolean in shared preference.
あなたがあなたのチームに他の開発者との大規模なアプリケーションを作り、よく散乱コードまたは異なるSharedPreferencesインスタンスなしに組織のすべてを持っているつもりされている場合、あなたはこのような何かを行うことがあります:
//SharedPreferences manager class
public class SharedPrefs {
//SharedPreferences file name
private static String SHARED_PREFS_FILE_NAME = "my_app_shared_prefs";
//here you can centralize all your shared prefs keys
public static String KEY_MY_SHARED_BOOLEAN = "my_shared_boolean";
public static String KEY_MY_SHARED_FOO = "my_shared_foo";
//get the SharedPreferences object instance
//create SharedPreferences file if not present
private static SharedPreferences getPrefs(Context context) {
return context.getSharedPreferences(SHARED_PREFS_FILE_NAME, Context.MODE_PRIVATE);
}
//Save Booleans
public static void savePref(Context context, String key, boolean value) {
getPrefs(context).edit().putBoolean(key, value).commit();
}
//Get Booleans
public static boolean getBoolean(Context context, String key) {
return getPrefs(context).getBoolean(key, false);
}
//Get Booleans if not found return a predefined default value
public static boolean getBoolean(Context context, String key, boolean defaultValue) {
return getPrefs(context).getBoolean(key, defaultValue);
}
//Strings
public static void save(Context context, String key, String value) {
getPrefs(context).edit().putString(key, value).commit();
}
public static String getString(Context context, String key) {
return getPrefs(context).getString(key, "");
}
public static String getString(Context context, String key, String defaultValue) {
return getPrefs(context).getString(key, defaultValue);
}
//Integers
public static void save(Context context, String key, int value) {
getPrefs(context).edit().putInt(key, value).commit();
}
public static int getInt(Context context, String key) {
return getPrefs(context).getInt(key, 0);
}
public static int getInt(Context context, String key, int defaultValue) {
return getPrefs(context).getInt(key, defaultValue);
}
//Floats
public static void save(Context context, String key, float value) {
getPrefs(context).edit().putFloat(key, value).commit();
}
public static float getFloat(Context context, String key) {
return getPrefs(context).getFloat(key, 0);
}
public static float getFloat(Context context, String key, float defaultValue) {
return getPrefs(context).getFloat(key, defaultValue);
}
//Longs
public static void save(Context context, String key, long value) {
getPrefs(context).edit().putLong(key, value).commit();
}
public static long getLong(Context context, String key) {
return getPrefs(context).getLong(key, 0);
}
public static long getLong(Context context, String key, long defaultValue) {
return getPrefs(context).getLong(key, defaultValue);
}
//StringSets
public static void save(Context context, String key, Set<String> value) {
getPrefs(context).edit().putStringSet(key, value).commit();
}
public static Set<String> getStringSet(Context context, String key) {
return getPrefs(context).getStringSet(key, null);
}
public static Set<String> getStringSet(Context context, String key, Set<String> defaultValue) {
return getPrefs(context).getStringSet(key, defaultValue);
}
}
あなたのアクティビティでは、SharedPreferencesを保存することがこの方法
//saving a boolean into prefs
SharedPrefs.savePref(this, SharedPrefs.KEY_MY_SHARED_BOOLEAN, booleanVar);
あなたはSharedPreferencesこの方法を検索することができると
//getting a boolean from prefs
booleanVar = SharedPrefs.getBoolean(this, SharedPrefs.KEY_MY_SHARED_BOOLEAN);
どのアプリケーションにも、 PreferenceManager
インスタンスとその関連メソッド getDefaultSharedPreferences(Context)
.
とともに SharedPreference
インスタンスでは、次のコマンドを使用して任意の設定の int 値を取得できます。 getInt(文字列キー、int defVal). 。この場合に関心がある設定は counter です。
私たちの場合、次のように変更できます。 SharedPreference
この例では edit() を使用してインスタンスを作成し、 putInt(String key, int newVal)
アプリケーションを超えて存在するアプリケーションの数を増やし、それに応じて表示しました。
これをさらにデモするには、アプリケーションを再起動して再度実行すると、アプリケーションを再起動するたびにカウントが増加することがわかります。
設定デモ.java
コード:
package org.example.preferences;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.TextView;
public class PreferencesDemo extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the app's shared preferences
SharedPreferences app_preferences =
PreferenceManager.getDefaultSharedPreferences(this);
// Get the value for the run counter
int counter = app_preferences.getInt("counter", 0);
// Update the TextView
TextView text = (TextView) findViewById(R.id.text);
text.setText("This app has been started " + counter + " times.");
// Increment the counter
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("counter", ++counter);
editor.commit(); // Very important
}
}
main.xml
コード:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
</LinearLayout>
SharedPreferences
により、ログイン値を格納する方法の簡単な解決策ます。
あなたは「あなたが残しておきたい何かの値を」保存するMainActivity
クラスまたは他のクラスを拡張することができます。作家と読者のクラスにこれを入れます:
public static final String GAME_PREFERENCES_LOGIN = "Login";
ここInputClass
入力とOutputClass
は、それぞれ、出力クラスである。
// This is a storage, put this in a class which you can extend or in both classes:
//(input and output)
public static final String GAME_PREFERENCES_LOGIN = "Login";
// String from the text input (can be from anywhere)
String login = inputLogin.getText().toString();
// then to add a value in InputCalss "SAVE",
SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0);
Editor editor = example.edit();
editor.putString("value", login);
editor.commit();
今、あなたは他のクラスのように、どこか別の場所にそれを使用することができます。以下はOutputClass
です。
SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0);
String userString = example.getString("value", "defValue");
// the following will print it out in console
Logger.getLogger("Name of a OutputClass".class.getName()).log(Level.INFO, userString);
のストアSharedPreferencesでの
SharedPreferences preferences = getSharedPreferences("temp", getApplicationContext().MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putString("name", name);
editor.commit();
の
のSharedPreferencesで取得SharedPreferences preferences=getSharedPreferences("temp", getApplicationContext().MODE_PRIVATE);
String name=preferences.getString("name",null);
注:「一時は」sharedpreferences名と「名前」が入力値です。その後、値does't出口がある場合はnull
を返します編集
SharedPreferences pref = getSharedPreferences("YourPref", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("yourValue", value);
editor.commit();
読む
SharedPreferences pref = getSharedPreferences("YourPref", MODE_PRIVATE);
value= pref.getString("yourValue", "");
基本的な考え方 共有設定 XML ファイルに内容を保存することです。
XML ファイルのパスを宣言します。(このファイルがない場合は、Android が作成します。このファイルがある場合、Android はそれにアクセスします。)
SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
共有設定に値を書き込む
prefs.edit().putLong("preference_file_key", 1010101).apply();
の
preference_file_key
共有設定ファイルの名前です。そしてその1010101
保存する必要がある値です。apply()
最後に変更を保存します。エラーが発生した場合apply()
, に変更しますcommit()
. 。したがって、この代替文は次のようになりますprefs.edit().putLong("preference_file_key", 1010101).commit();
共有設定から読み取る
SharedPreferences sp = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE); long lsp = sp.getLong("preference_file_key", -1);
lsp
になるだろう-1
もしpreference_file_key
価値がありません。「preference_file_key」に値がある場合は、その値を返します。
書くためのコード全体は次のとおりです
SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE); // Declare xml file
prefs.edit().putLong("preference_file_key", 1010101).apply(); // Write the value to key.
読み取り用のコードは、
SharedPreferences sf = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE); // Declare xml file
long lsp = sp.getLong("preference_file_key", -1); // Read the key and store in lsp
あなたは、このメソッドを使用して値を保存することができます:
public void savePreferencesForReasonCode(Context context,
String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
そして、あなたはSharedPreferencesから値を取得することができ、このメソッドを使用します:
public String getPreferences(Context context, String prefKey) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
return sharedPreferences.getString(prefKey, "");
}
ここprefKey
を使用すると、特定の値を保存するために使用するキーです。おかげます。
editor.putString("text", mSaved.getText().toString());
ここで、mSaved
は、我々は、文字列を抽出することができ、そこから任意のTextView
またはEditText
ことができます。あなたは、単に文字列を指定することができます。ここで、テキストはmSaved
(TextView
又はEditText
)から得られた値を保持する鍵となります。
SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
また、パッケージ名、すなわち、「com.example.app」を使用して設定ファイルを保存する必要はありません。あなたは、あなた自身の優先の名前を挙げることができます。この情報がお役に立てば幸い!
人々が推奨する使用方法はたくさんあります 共有設定. 。を作りました デモプロジェクトはこちら. 。サンプルの重要なポイントは、 ApplicationContext と単一のsharedpreferencesオブジェクト. 。これは使用方法を示しています 共有設定 次の機能を備えています:-
- singelton クラスを使用して SharedPreferences にアクセス/更新する
- SharedPreferences の読み取り/書き込みのために常にコンテキストを渡す必要はありません
- commit() の代わりに apply() を使用します
- Apply()はAsynchronus Saveで、何も返さず、最初にメモリで値を更新し、変更は後でDiskに書き込まれます。
- commit() は同期保存であり、結果に基づいて true/false を返します。変更は同期的にディスクに書き込まれます
- Android 2.3以降のバージョンで動作します
以下のような使用例:-
MyAppPreference.getInstance().setSampleStringKey("some_value");
String value= MyAppPreference.getInstance().getSampleStringKey();
ここからソースコードを入手してください& 詳細な API を見つけることができます ここ 開発者.android.com で
これまでのベストプラクティス
作成する インターフェース と名付けられた プリファレンスマネージャー:
// Interface to save values in shared preferences and also for retrieve values from shared preferences
public interface PreferenceManager {
SharedPreferences getPreferences();
Editor editPreferences();
void setString(String key, String value);
String getString(String key);
void setBoolean(String key, boolean value);
boolean getBoolean(String key);
void setInteger(String key, int value);
int getInteger(String key);
void setFloat(String key, float value);
float getFloat(String key);
}
使用方法 活動 / 断片:
public class HomeActivity extends AppCompatActivity implements PreferenceManager{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout_activity_home);
}
@Override
public SharedPreferences getPreferences(){
return getSharedPreferences("SP_TITLE", Context.MODE_PRIVATE);
}
@Override
public SharedPreferences.Editor editPreferences(){
return getPreferences().edit();
}
@Override
public void setString(String key, String value) {
editPreferences().putString(key, value).commit();
}
@Override
public String getString(String key) {
return getPreferences().getString(key, "");
}
@Override
public void setBoolean(String key, boolean value) {
editPreferences().putBoolean(key, value).commit();
}
@Override
public boolean getBoolean(String key) {
return getPreferences().getBoolean(key, false);
}
@Override
public void setInteger(String key, int value) {
editPreferences().putInt(key, value).commit();
}
@Override
public int getInteger(String key) {
return getPreferences().getInt(key, 0);
}
@Override
public void setFloat(String key, float value) {
editPreferences().putFloat(key, value).commit();
}
@Override
public float getFloat(String key) {
return getPreferences().getFloat(key, 0);
}
}
注記: SharedPreference のキーを次のものに置き換えます SP_TITLE.
例:
文字列を格納する で シェアペレンス:
setString("my_key", "my_value");
文字列を取得する から シェアペレンス:
String strValue = getString("my_key");
これがお役に立てば幸いです。
共有設定で値を保存するには:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Name","Jayesh");
editor.commit();
共有設定から値を取得するには:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString("Name", ""); // Second parameter is the default value.
の の
を保存するにはPreferenceManager.getDefaultSharedPreferences(this).edit().putString("VarName","your value").apply();
を盗んする:
のString name = PreferenceManager.getDefaultSharedPreferences(this).getString("VarName","defaultValue");
デフォルト値です。この設定が存在しない場合、値は返すために、
あなたは "の のこののの" の のgetActivity()のまたは のgetApplicationContext(と変更することができます)のの中 いくつかの例
の の使用は、この例では単純明快を使用してのの
確認しました<?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>
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();
}
});
}
}
は、このシンプルなライブラリを使用して、ここにあなたが作る方法ですSharedPreferencesの呼び出し..
TinyDB tinydb = new TinyDB(context);
tinydb.putInt("clickCount", 2);
tinydb.putString("userName", "john");
tinydb.putBoolean("isUserMale", true);
tinydb.putList("MyUsers", mUsersArray);
tinydb.putImagePNG("DropBox/WorkImages", "MeAtlunch.png", lunchBitmap);
//These plus the corresponding get methods are all Included
私はSharedPreferencesを使用している場合、この質問のためのスニペットのほとんどはMODE_PRIVATEのようなものを持っていることをここに追加したいです。まあ、MODE_PRIVATE手段は何でも、あなたがこの共有好みに書き込むことだけで、アプリケーションにのみます。
で読み取ることができますあなたはgetSharedPreferencesに渡すものは何でもキー()メソッドは、アンドロイドそれにその名前と保存嗜好データを持つファイルを作成します。 また、あなたのアプリケーション用に複数の設定ファイルを持つようにしようとするとき()を使用することを想定していることgetSharedPreferencesを覚えています。あなたは、単一の設定ファイルを使用すると、それにすべてのキーと値のペアを保存する場合は、getSharedPreference()メソッドを使用します。その奇妙な理由(私を含め)誰もが簡単にしても上記の二つの違いを理解せずgetSharedPreferences()の風味を使用します。
次のビデオチュートリアルが役立つはずです https://www.youtube.com/watch?v=2PcAQ1NBy98する
シンプルで手間いらず::「Android-SharedPreferences-Helper」ライブラリ
遅刻しないよりはマシです:わたしは作った 「Android-SharedPreferences-Helper」ライブラリ 使用の複雑さと労力を軽減するために SharedPreferences
. 。また、いくつかの拡張機能も提供します。それが提供するものは次のとおりです。
- 1 行の初期化とセットアップ
- デフォルトの環境設定を使用するかカスタム環境設定ファイルを使用するかを簡単に選択
- 各データ型の事前定義済み (データ型のデフォルト) およびカスタマイズ可能な (選択可能な) デフォルト値
- パラメータを追加するだけで、単一使用のために異なるデフォルト値を設定する機能
- OnSharedPreferenceChangeListener は、デフォルト クラスの場合と同様に登録および登録解除できます。
dependencies {
...
...
compile(group: 'com.viralypatel.sharedpreferenceshelper', name: 'library', version: '1.1.0', ext: 'aar')
}
SharedPreferencesHelper オブジェクトの宣言:(クラスレベルで推奨)
SharedPreferencesHelper sph;
SharedPreferencesHelper オブジェクトのインスタンス化:(oncreate()メソッドで推奨)
// use one of the following ways to instantiate
sph = new SharedPreferencesHelper(this); //this will use default shared preferences
sph = new SharedPreferencesHelper(this, "myappprefs"); // this will create a named shared preference file
sph = new SharedPreferencesHelper(this, "myappprefs", 0); // this will allow you to specify a mode
共有設定に値を設定する
かなりシンプルです!デフォルトの方法(SharedPreferences クラスを使用する場合)とは異なり、呼び出す必要はありません。 .edit()
そして .commit()
いつも。
sph.putBoolean("boolKey", true);
sph.putInt("intKey", 123);
sph.putString("stringKey", "string value");
sph.putLong("longKey", 456876451);
sph.putFloat("floatKey", 1.51f);
// putStringSet is supported only for android versions above HONEYCOMB
Set name = new HashSet();
name.add("Viral");
name.add("Patel");
sph.putStringSet("name", name);
それでおしまい!値は共有設定に保存されます。
共有設定から値を取得する
繰り返しますが、キー名を使用した単純なメソッド呼び出しは 1 つだけです。
sph.getBoolean("boolKey");
sph.getInt("intKey");
sph.getString("stringKey");
sph.getLong("longKey");
sph.getFloat("floatKey");
// getStringSet is supported only for android versions above HONEYCOMB
sph.getStringSet("name");
他にも拡張機能がたくさんあります
拡張機能の詳細、使用方法、インストール手順などは、 GitHub リポジトリ ページ.
私はsharedpreferencesのヘルパークラスを記述します:
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by mete_ on 23.12.2016.
*/
public class HelperSharedPref {
Context mContext;
public HelperSharedPref(Context mContext) {
this.mContext = mContext;
}
/**
*
* @param key Constant RC
* @param value Only String, Integer, Long, Float, Boolean types
*/
public void saveToSharedPref(String key, Object value) throws Exception {
SharedPreferences.Editor editor = mContext.getSharedPreferences(key, Context.MODE_PRIVATE).edit();
if (value instanceof String) {
editor.putString(key, (String) value);
} else if (value instanceof Integer) {
editor.putInt(key, (Integer) value);
} else if (value instanceof Long) {
editor.putLong(key, (Long) value);
} else if (value instanceof Float) {
editor.putFloat(key, (Float) value);
} else if (value instanceof Boolean) {
editor.putBoolean(key, (Boolean) value);
} else {
throw new Exception("Unacceptable object type");
}
editor.commit();
}
/**
* Return String
* @param key
* @return null default is null
*/
public String loadStringFromSharedPref(String key) throws Exception {
SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
String restoredText = prefs.getString(key, null);
return restoredText;
}
/**
* Return int
* @param key
* @return null default is -1
*/
public Integer loadIntegerFromSharedPref(String key) throws Exception {
SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
Integer restoredText = prefs.getInt(key, -1);
return restoredText;
}
/**
* Return float
* @param key
* @return null default is -1
*/
public Float loadFloatFromSharedPref(String key) throws Exception {
SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
Float restoredText = prefs.getFloat(key, -1);
return restoredText;
}
/**
* Return long
* @param key
* @return null default is -1
*/
public Long loadLongFromSharedPref(String key) throws Exception {
SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
Long restoredText = prefs.getLong(key, -1);
return restoredText;
}
/**
* Return boolean
* @param key
* @return null default is false
*/
public Boolean loadBooleanFromSharedPref(String key) throws Exception {
SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
Boolean restoredText = prefs.getBoolean(key, false);
return restoredText;
}
}
SharedPreferences.Editor editor = getSharedPreferences("identifier",
MODE_PRIVATE).edit();
//identifier is the unique to fetch data from your SharedPreference.
editor.putInt("keyword", 0);
// saved value place with 0.
//use this "keyword" to fetch saved value again.
editor.commit();//important line without this line your value is not stored in preference
// fetch the stored data using ....
SharedPreferences prefs = getSharedPreferences("identifier", MODE_PRIVATE);
// here both identifier will same
int fetchvalue = prefs.getInt("keyword", 0);
// here keyword will same as used above.
// 0 is default value when you nothing save in preference that time fetch value is 0.
あなたはAdapterClassやその他でSharedPreferencesを使用する必要があります。 その時は、ちょうどこの宣言を使用し、上記と同じお尻を使用します。
SharedPreferences.Editor editor = context.getSharedPreferences("idetifier",
Context.MODE_PRIVATE).edit();
SharedPreferences prefs = context.getSharedPreferences("identifier", Context.MODE_PRIVATE);
//here context is your application context
文字列やブール値のために
editor.putString("stringkeyword", "your string");
editor.putBoolean("booleankeyword","your boolean value");
editor.commit();
上記と同じデータをフェッチ
String fetchvalue = prefs.getString("keyword", "");
Boolean fetchvalue = prefs.getBoolean("keyword", "");
2.forの保存、共有prefrenceで
SharedPreferences.Editor editor =
getSharedPreferences("DeviceToken",MODE_PRIVATE).edit();
editor.putString("DeviceTokenkey","ABABABABABABABB12345");
editor.apply();
同じ使用を取り出す2.for
SharedPreferences prefs = getSharedPreferences("DeviceToken",
MODE_PRIVATE);
String deviceToken = prefs.getString("DeviceTokenkey", null);
ここで私のアンドロイドで設定を使用するヘルパークラスを作成しています。
このヘルパークラスです。
public class PrefsUtil {
public static SharedPreferences getPreference() {
return PreferenceManager.getDefaultSharedPreferences(Applicatoin.getAppContext());
}
public static void putBoolean(String key, boolean value) {
getPreference().edit().putBoolean(key, value)
.apply();
}
public static boolean getBoolean(String key) {
return getPreference().getBoolean(key, false);
}
public static void putInt(String key, int value) {
getPreference().edit().putInt(key, value).apply();
}
public static void delKey(String key) {
getPreference().edit().remove(key).apply();
}
}
。
テストするには、確認してくださいあなたのページ上のTextViewアイテム、コメントを解除コードと実行中の2行を持っています。その後、再び2行をコメントし、実行。
ここでのTextViewのIDは、ユーザー名とパスワードです。
は、あなたがそれを使用するすべてのクラスでは、最後にこれら2つのルーチンを追加します。 私は、このルーチンはグローバルのルーチンになりたいが、方法がわかりません。この作品ます。
variabelsはどこでも利用可能です。 これは、「MyFileの」内の変数を格納します。あなたは、あなたのようにそれを変更することがあります。
は、
を使用してそれを呼び出します storeSession("username","frans");
storeSession("password","!2#4%");***
変数名は「!2#4%」と「トランス」とパスワードを入力されます。でも、再起動後に彼らが用意されています。
あなたが使用してそれを取得し、
password.setText(getSession(("password")));
usernames.setText(getSession(("username")));
私のgrid.javaの全体のコードの下に
package nl.yentel.yenteldb2;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class Grid extends AppCompatActivity {
private TextView usernames;
private TextView password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
***// storeSession("username","frans.eilering@gmail.com");
//storeSession("password","mijn wachtwoord");***
password = (TextView) findViewById(R.id.password);
password.setText(getSession(("password")));
usernames=(TextView) findViewById(R.id.username);
usernames.setText(getSession(("username")));
}
public void storeSession(String key, String waarde) {
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyFile", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(key, waarde);
editor.commit();
}
public String getSession(String key) {
//http://androidexample.com/Android_SharedPreferences_Basics/index.php?view=article_discription&aid=126&aaid=146
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyFile", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
String output = pref.getString(key, null);
return output;
}
}
あなたはTextViewのアイテムを見つけるには、下記
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="usernames"
android:id="@+id/username"
android:layout_below="@+id/textView"
android:layout_alignParentStart="true"
android:layout_marginTop="39dp"
android:hint="hier komt de username" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="password"
android:id="@+id/password"
android:layout_below="@+id/user"
android:layout_alignParentStart="true"
android:hint="hier komt het wachtwoord" />
私は私の人生簡単に作るためにヘルパークラスを作成しました。これは、一般的なクラスであり、それらの一般的な共有の設定、Eメールの妥当性、日付時刻形式のようなアプリで使用されている方法の-たくさん持っています。あなたが必要な場所あなたのコードとアクセスそれの方法でこのクラスをコピーします。
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.support.v4.app.FragmentActivity;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* Created by Zohaib Hassan on 3/4/2016.
*/
public class Helper {
private static ProgressDialog pd;
public static void saveData(String key, String value, Context context) {
SharedPreferences sp = context.getApplicationContext()
.getSharedPreferences("appData", 0);
SharedPreferences.Editor editor;
editor = sp.edit();
editor.putString(key, value);
editor.commit();
}
public static void deleteData(String key, Context context){
SharedPreferences sp = context.getApplicationContext()
.getSharedPreferences("appData", 0);
SharedPreferences.Editor editor;
editor = sp.edit();
editor.remove(key);
editor.commit();
}
public static String getSaveData(String key, Context context) {
SharedPreferences sp = context.getApplicationContext()
.getSharedPreferences("appData", 0);
String data = sp.getString(key, "");
return data;
}
public static long dateToUnix(String dt, String format) {
SimpleDateFormat formatter;
Date date = null;
long unixtime;
formatter = new SimpleDateFormat(format);
try {
date = formatter.parse(dt);
} catch (Exception ex) {
ex.printStackTrace();
}
unixtime = date.getTime();
return unixtime;
}
public static String getData(long unixTime, String formate) {
long unixSeconds = unixTime;
Date date = new Date(unixSeconds);
SimpleDateFormat sdf = new SimpleDateFormat(formate);
String formattedDate = sdf.format(date);
return formattedDate;
}
public static String getFormattedDate(String date, String currentFormat,
String desiredFormat) {
return getData(dateToUnix(date, currentFormat), desiredFormat);
}
public static double distance(double lat1, double lon1, double lat2,
double lon2, char unit) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2))
+ Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2))
* Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
if (unit == 'K') {
dist = dist * 1.609344;
} else if (unit == 'N') {
dist = dist * 0.8684;
}
return (dist);
}
/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
/* :: This function converts decimal degrees to radians : */
/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
private static double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
/* :: This function converts radians to decimal degrees : */
/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
private static double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
public static int getRendNumber() {
Random r = new Random();
return r.nextInt(360);
}
public static void hideKeyboard(Context context, EditText editText) {
InputMethodManager imm = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
public static void showLoder(Context context, String message) {
pd = new ProgressDialog(context);
pd.setCancelable(false);
pd.setMessage(message);
pd.show();
}
public static void showLoderImage(Context context, String message) {
pd = new ProgressDialog(context);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setCancelable(false);
pd.setMessage(message);
pd.show();
}
public static void dismissLoder() {
pd.dismiss();
}
public static void toast(Context context, String text) {
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}
/*
public static Boolean connection(Context context) {
ConnectionDetector connection = new ConnectionDetector(context);
if (!connection.isConnectingToInternet()) {
Helper.showAlert(context, "No Internet access...!");
//Helper.toast(context, "No internet access..!");
return false;
} else
return true;
}*/
public static void removeMapFrgment(FragmentActivity fa, int id) {
android.support.v4.app.Fragment fragment;
android.support.v4.app.FragmentManager fm;
android.support.v4.app.FragmentTransaction ft;
fm = fa.getSupportFragmentManager();
fragment = fm.findFragmentById(id);
ft = fa.getSupportFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
}
public static AlertDialog showDialog(Context context, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// TODO Auto-generated method stub
}
});
return builder.create();
}
public static void showAlert(Context context, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Alert");
builder.setMessage(message)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
}).show();
}
public static boolean isURL(String url) {
if (url == null)
return false;
boolean foundMatch = false;
try {
Pattern regex = Pattern
.compile(
"\\b(?:(https?|ftp|file)://|www\\.)?[-A-Z0-9+&#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$]\\.[-A-Z0-9+&@#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$]",
Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher regexMatcher = regex.matcher(url);
foundMatch = regexMatcher.matches();
return foundMatch;
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
return false;
}
}
public static boolean atLeastOneChr(String string) {
if (string == null)
return false;
boolean foundMatch = false;
try {
Pattern regex = Pattern.compile("[a-zA-Z0-9]",
Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher regexMatcher = regex.matcher(string);
foundMatch = regexMatcher.matches();
return foundMatch;
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
return false;
}
}
public static boolean isValidEmail(String email, Context context) {
String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
return true;
} else {
// Helper.toast(context, "Email is not valid..!");
return false;
}
}
public static boolean isValidUserName(String email, Context context) {
String expression = "^[0-9a-zA-Z]+$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
return true;
} else {
Helper.toast(context, "Username is not valid..!");
return false;
}
}
public static boolean isValidDateSlash(String inDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
dateFormat.setLenient(false);
try {
dateFormat.parse(inDate.trim());
} catch (ParseException pe) {
return false;
}
return true;
}
public static boolean isValidDateDash(String inDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy");
dateFormat.setLenient(false);
try {
dateFormat.parse(inDate.trim());
} catch (ParseException pe) {
return false;
}
return true;
}
public static boolean isValidDateDot(String inDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.mm.yyyy");
dateFormat.setLenient(false);
try {
dateFormat.parse(inDate.trim());
} catch (ParseException pe) {
return false;
}
return true;
}
}