اگر با چرخهی عمر کتیویتی آشنا باشید میدانید که، ()onPause همیشه قبل از قرار گرفتن اکتیویتی شما در Background یا Destroyed فراخوانی میشود، بنابراین برای اینکه دادهها به صورت مداوم ذخیره شوند، ترجیح میدهیم آنها را در ()onPause ذخیره کنیم، که میتواند در ()onCreate اکتیویتی بازیابی شود. دادههای ذخیره شده با استفاده از Shared Preferences در محدودهی (Scope) برنامه به صورت خصوصی حفظ میشوند.
SharedPreferences مخصوص برنامه است، یعنی دادهها با انجام یکی از گزینههای زیر از بین میروند:
getSharedPreferences (String PREFS_NAME, int mode)
برای ویرایش و ذخیرهی تغییرات در Shared Preferences، به یک ویرایشگر (Editor) نیاز داریم.
می توانید از کد زیر برای دریافت Shared Preferences استفاده کنید.
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
editor.commit(); // commit changes
pref.getString("key_name", null); // getting String
pref.getInt("key_name", -1); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean
editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
editor.commit(); // commit changes
برای پاک کردن همهی دادهها از ()clear استفاده میشود.
editor.clear();
editor.commit(); // commit changes
طرح activity_main.xml شامل دو ویوی EditText است که نام و ایمیل را ذخیره کرده و نمایش میدهد. این سه دکمه OnClickهای مربوطه را در MainActivity پیاده سازی میکنند.
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
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" >
<Button
android:id="@+id/btnSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="Save"
android:text="Save" />
<Button
android:id="@+id/btnRetr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:onClick="Get"
android:text="Retrieve" />
<Button
android:id="@+id/btnClear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/etEmail"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:onClick="clear"
android:text="Clear" />
<EditText
android:id="@+id/etEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Email"
android:inputType="textEmailAddress"
android:layout_below="@+id/etName"
android:layout_marginTop="20dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:id="@+id/etName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Name"
android:inputType="text"
android:layout_alignParentTop="true"
android:layout_alignLeft="@+id/etEmail"
android:layout_alignStart="@+id/etEmail" />
</RelativeLayout>
package com.journaldev.sharedpreferences;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
SharedPreferences sharedpreferences;
TextView name;
TextView email;
public static final String mypreference = "mypref";
public static final String Name = "nameKey";
public static final String Email = "emailKey";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(Email)) {
email.setText(sharedpreferences.getString(Email, ""));
}
}
public void Save(View view) {
String n = name.getText().toString();
String e = email.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Email, e);
editor.commit();
}
public void clear(View view) {
name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
name.setText("");
email.setText("");
}
public void Get(View view) {
name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(Email)) {
email.setText(sharedpreferences.getString(Email, ""));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
آموزش Shared Preferences در اندروید
جمعبندی
اندروید روشهای زیادی برای ذخیرهی دادههای یک برنامه فراهم میکند. یکی از این راهها Shared Preferences نامیده میشود. Shared Preferences به شما امکان میدهد دادهها را به صورت جفت کلید/مقدار ذخیره و بازیابی کنید. شما در این مقاله آموختید که Shared Preferences چیست و در آموزش Shared Preferences در اندروید با ما همراه بودید، امیدوار هستیم که این مقاله برای شما مفید بوده باشد. اگر در این زمینه تجربه یا سوالی دارید خوشحال میشویم آن را با ما و کاربران وب سایت سون لرن به اشتراک بگذارید.
منابع: