با مجموعهها، منظم بمانید
ذخیره و طبقهبندی محتوا براساس اولویتهای شما.
اگر مجموعه نسبتاً کوچکی از مقادیر کلیدی دارید که میخواهید ذخیره کنید، میتوانید از SharedPreferences API استفاده کنید. یک شی SharedPreferences به یک فایل حاوی جفت های کلید-مقدار اشاره می کند و روش های ساده ای برای خواندن و نوشتن آنها ارائه می دهد. هر فایل SharedPreferences توسط چارچوب مدیریت می شود و می تواند خصوصی یا اشتراکی باشد.
این صفحه به شما نشان می دهد که چگونه از API های SharedPreferences برای ذخیره و بازیابی مقادیر ساده استفاده کنید.
به تنظیمات برگزیده مشترک رسیدگی کنید
میتوانید با فراخوانی یکی از این روشها، یک فایل ترجیحی مشترک جدید ایجاد کنید یا به یک موجود موجود دسترسی پیدا کنید:
getSharedPreferences() : اگر به چندین فایل ترجیحی مشترک نیاز دارید که با نام مشخص شده اند، از این مورد استفاده کنید. میتوانید از هر Context در برنامه خود با آن تماس بگیرید.
getPreferences() : اگر نیاز به استفاده از یک فایل ترجیحی مشترک برای فعالیت دارید، از این مورد از یک Activity استفاده کنید. از آنجا که این یک فایل ترجیحی مشترک پیشفرض را که متعلق به فعالیت است بازیابی میکند، نیازی به ارائه نام ندارید.
به عنوان مثال، کد زیر به فایل ترجیحات مشترک که توسط رشته منبع R.string.preference_file_key شناسایی شده است دسترسی پیدا می کند و آن را با استفاده از حالت خصوصی باز می کند تا فایل فقط توسط برنامه شما قابل دسترسی باشد:
هنگام نامگذاری فایلهای ترجیحی مشترک خود، باید از نامی استفاده کنید که به طور منحصر به فرد برای برنامه شما قابل شناسایی باشد. یک راه خوب برای انجام این کار این است که نام فایل را با شناسه برنامه خود پیشوند قرار دهید. به عنوان مثال: "com.example.myapp.PREFERENCE_FILE_KEY"
از طرف دیگر، اگر فقط به یک فایل ترجیحی مشترک برای فعالیت خود نیاز دارید، می توانید از متد getPreferences() استفاده کنید:
اگر از SharedPreferences API برای ذخیره تنظیمات برنامه استفاده میکنید، در عوض باید از getDefaultSharedPreferences() برای دریافت فایل ترجیحی مشترک پیشفرض برای کل برنامه خود استفاده کنید. برای اطلاعات بیشتر، به راهنمای برنامهنویس تنظیمات مراجعه کنید.
در تنظیمات برگزیده مشترک بنویسید
برای نوشتن در یک فایل ترجیحات مشترک، یک SharedPreferences.Editor با فراخوانی edit() در SharedPreferences خود ایجاد کنید.
کلیدها و مقادیری را که می خواهید بنویسید با متدهایی مانند: putInt() و putString() ارسال کنید. سپس apply() یا commit() را برای ذخیره تغییرات فراخوانی کنید. به عنوان مثال:
apply() شی SharedPreferences در حافظه را بلافاصله تغییر می دهد اما به روز رسانی ها را به صورت ناهمزمان روی دیسک می نویسد. همچنین، میتوانید از commit() برای نوشتن دادهها روی دیسک به صورت همزمان استفاده کنید. اما از آنجایی که commit() همزمان است، باید از فراخوانی آن از رشته اصلی خود اجتناب کنید زیرا ممکن است رندر رابط کاربری شما را متوقف کند.
از تنظیمات برگزیده مشترک بخوانید
برای بازیابی مقادیر از یک فایل ترجیحی مشترک، متدهایی مانند getInt() و getString() را فراخوانی کنید، کلید مقدار مورد نظر خود را ارائه دهید، و در صورت عدم وجود کلید، یک مقدار پیشفرض را به صورت اختیاری برگردانید. به عنوان مثال:
محتوا و نمونه کدها در این صفحه مشمول پروانههای توصیفشده در پروانه محتوا هستند. جاوا و OpenJDK علامتهای تجاری یا علامتهای تجاری ثبتشده Oracle و/یا وابستههای آن هستند.
تاریخ آخرین بهروزرسانی 2025-07-29 بهوقت ساعت هماهنگ جهانی.
[[["درک آسان","easyToUnderstand","thumb-up"],["مشکلم را برطرف کرد","solvedMyProblem","thumb-up"],["غیره","otherUp","thumb-up"]],[["اطلاعاتی که نیاز دارم وجود ندارد","missingTheInformationINeed","thumb-down"],["بیشازحد پیچیده/ مراحل بسیار زیاد","tooComplicatedTooManySteps","thumb-down"],["قدیمی","outOfDate","thumb-down"],["مشکل ترجمه","translationIssue","thumb-down"],["مشکل کد / نمونهها","samplesCodeIssue","thumb-down"],["غیره","otherDown","thumb-down"]],["تاریخ آخرین بهروزرسانی 2025-07-29 بهوقت ساعت هماهنگ جهانی."],[],[],null,["# Save simple data with SharedPreferences\n\nIf you have a relatively small collection of key-values that you'd like to save,\nyou can use the [`SharedPreferences`](/reference/android/content/SharedPreferences) APIs. A `SharedPreferences` object\npoints to a file containing key-value pairs and provides simple methods to read\nand write them. Each `SharedPreferences` file is managed by the framework and\ncan be private or shared.\n\nThis page shows you how to use the `SharedPreferences` APIs to store and\nretrieve simple values.\n| **Caution:** `DataStore` is a modern data storage solution that you should use instead of `SharedPreferences`. It builds on Kotlin coroutines and Flow, and overcomes many of the drawbacks of `SharedPreferences`.\n|\n| Read the [DataStore guide](/topic/libraries/architecture/datastore) for more information.\n| **Note:** The `SharedPreferences` APIs are for reading and writing key-value pairs, and you shouldn't confuse them with the [`Preference`](/reference/android/preference/Preference) APIs, which help you build a user interface for your app settings (although they also use `SharedPreferences` to save the user's settings). For information about the [`Preference`](/reference/android/preference/Preference) APIs, see the [Settings developer guide](/guide/topics/ui/settings).\n\nGet a handle to shared preferences\n----------------------------------\n\nYou can create a new shared preference file or access an existing one by calling\none of these methods:\n\n- **[`getSharedPreferences()`](/reference/android/content/Context#getSharedPreferences(java.lang.String,%20int)):** Use this if you need multiple shared preference files identified by name, which you specify with the first parameter. You can call this from any [`Context`](/training/data-storage/shared-preferences#kotlin:%7E:text=this%20from%20any-,Context,-in%20your%20app) in your app.\n- **[`getPreferences()`](/reference/android/app/Activity#getPreferences(int)):** Use this from an [`Activity`](/reference/android/app/Activity) if you need to use only one shared preference file for the activity. Because this retrieves a default shared preference file that belongs to the activity, you don't need to supply a name.\n\nFor example, the following code accesses the shared preferences file that's\nidentified by the resource string `R.string.preference_file_key` and opens it\nusing the private mode so the file is accessible by only your app: \n\n### Kotlin\n\n```kotlin\nval sharedPref = activity?.getSharedPreferences(\n getString(R.string.preference_file_key), Context.MODE_PRIVATE)\n```\n\n### Java\n\n```java\nContext context = getActivity();\nSharedPreferences sharedPref = context.getSharedPreferences(\n getString(R.string.preference_file_key), Context.MODE_PRIVATE);\n```\n\nWhen naming your shared preference files, you should use a name that's uniquely\nidentifiable to your app. A good way to do this is prefix the file name with\nyour [application ID](/studio/build/configure-app-module#set_the_application_id). For example:\n`\"com.example.myapp.PREFERENCE_FILE_KEY\"`\n\nAlternatively, if you need just one shared preference file for your activity,\nyou can use the [`getPreferences()`](/reference/android/app/Activity#getPreferences(int)) method: \n\n### Kotlin\n\n```kotlin\nval sharedPref = activity?.getPreferences(Context.MODE_PRIVATE)\n```\n\n### Java\n\n```java\nSharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);\n```\n| **Caution:** The [`MODE_WORLD_READABLE`](/reference/android/content/Context#MODE_WORLD_READABLE) and [`MODE_WORLD_WRITEABLE`](/reference/android/content/Context#MODE_WORLD_WRITEABLE) modes have been deprecated since API level 17.\n|\n| Starting with Android 7.0 (API level 24), Android throws a\n| [`SecurityException`](/reference/java/lang/SecurityException) if you use them. If your app needs to share private\n| files with other apps, it may use a [`FileProvider`](/reference/androidx/core/content/FileProvider) with the\n| [`FLAG_GRANT_READ_URI_PERMISSION`](/reference/android/content/Intent#FLAG_GRANT_READ_URI_PERMISSION). For more information, also see\n| [Sharing Files](/training/secure-file-sharing).\n\nIf you're using the `SharedPreferences` API to save app settings, you\nshould instead use [`getDefaultSharedPreferences()`](/reference/android/preference/PreferenceManager#getDefaultSharedPreferences(android.content.Context)) to get the default\nshared preference file for your entire app. For more information, see the\n[Settings developer guide](/guide/topics/ui/settings).\n\nWrite to shared preferences\n---------------------------\n\nTo write to a shared preferences file, create a [`SharedPreferences.Editor`](/reference/android/content/SharedPreferences.Editor)\nby calling [`edit()`](/reference/android/content/SharedPreferences#edit()) on your `SharedPreferences`.\n\nPass the keys and values you want to write with methods such as:\n[`putInt()`](/reference/android/content/SharedPreferences.Editor#putInt()) and[`putString()`](/reference/android/content/SharedPreferences.Editor#putString()). Then call [`apply()`](/reference/android/content/SharedPreferences.Editor#apply()) or\n[`commit()`](/reference/android/content/SharedPreferences.Editor#commit()) to save the changes. For example: \n\n### Kotlin\n\n```kotlin\nval sharedPref = activity?.getPreferences(Context.MODE_PRIVATE) ?: return\nwith (sharedPref.edit()) {\n putInt(getString(R.string.saved_high_score_key), newHighScore)\n apply()\n}\n```\n\n### Java\n\n```java\nSharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);\nSharedPreferences.Editor editor = sharedPref.edit();\neditor.putInt(getString(R.string.saved_high_score_key), newHighScore);\neditor.apply();\n```\n\n`apply()` changes the in-memory `SharedPreferences` object immediately but\nwrites the updates to disk asynchronously. Alternatively, you can use `commit()`\nto write the data to disk synchronously. But because `commit()` is synchronous,\nyou should avoid calling it from your main thread because it could pause your UI\nrendering.\n\nRead from shared preferences\n----------------------------\n\nTo retrieve values from a shared preferences file, call methods such as\n[`getInt()`](/reference/android/content/SharedPreferences#getInt(java.lang.String,%20int)) and [`getString()`](/reference/android/content/SharedPreferences#getString(java.lang.String,%20java.lang.String)), providing the key for the value you\nwant, and optionally a default value to return if the key isn't present. For\nexample: \n\n### Kotlin\n\n```kotlin\nval sharedPref = activity?.getPreferences(Context.MODE_PRIVATE) ?: return\nval defaultValue = resources.getInteger(R.integer.saved_high_score_default_key)\nval highScore = sharedPref.getInt(getString(R.string.saved_high_score_key), defaultValue)\n```\n\n### Java\n\n```java\nSharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);\nint defaultValue = getResources().getInteger(R.integer.saved_high_score_default_key);\nint highScore = sharedPref.getInt(getString(R.string.saved_high_score_key), defaultValue);\n```"]]