یک تمرین برای اموزش shared preference
کلاسی به اسم UserManger ساختیم و فایل خود به اسم user_information را در سازنده آن ایجاد کردیم
public UserManager(Context context) { sharedPreferences = context.getSharedPreferences("user_information", context.MODE_PRIVATE); }
و تابع به اسم saveInformation را ساختیم که در shared preference ایجاد شده اطلاعات را ذخیره کند
public boolean saveInformation(String fullName, String email, String gender) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("full_name", fullName); editor.putString("email", email); editor.putString("gender", gender); editor.apply(); return true; }
اگر بخواهیم به عنوان مثال به داده full_name دسترسی داشته داشته باشیم
public String getFullName() { return sharedPreferences.getString("full_name", ""); }
اگر بخواهیم همه داده ها را پاک کنیم به روش زیر عمل میکنیم
SharedPreferences.Editor editor = sharedPreferences.edit(); editor.clear(); editor.apply();
اگر بخواهیم مقدار مشخصی را حذف کنیم به روش زیر عمل میکنیم
public void removeKey(String key){ SharedPreferences.Editor editor = sharedPreferences.edit(); editor.remove(key); editor.apply(); }