به بخش Realtime Databaseکنسول Firebase بروید. از شما خواسته می شود که یک پروژه Firebase موجود را انتخاب کنید. گردش کار ایجاد پایگاه داده را دنبال کنید.
یک حالت شروع برای Firebase Security Rules خود انتخاب کنید:
حالت تست
برای شروع کار با کتابخانه های موبایل و کلاینت وب خوب است، اما به هر کسی اجازه می دهد داده های شما را بخواند و بازنویسی کند. پس از تست، حتما قسمت Understand Firebase Realtime Database Rules را مرور کنید.
برای شروع کار با وب، اپل یا اندروید SDK، حالت تست را انتخاب کنید.
حالت قفل شده
همه خواندن و نوشتن از مشتریان تلفن همراه و وب را رد می کند. سرورهای برنامه تأیید شده شما همچنان می توانند به پایگاه داده شما دسترسی داشته باشند.
مکانی را برای پایگاه داده انتخاب کنید.
بسته به موقعیت پایگاه داده ، URL پایگاه داده جدید به یکی از اشکال زیر خواهد بود:
DATABASE_NAME .firebaseio.com (برای پایگاههای داده در us-central1 )
DATABASE_NAME . REGION .firebasedatabase.app (برای پایگاههای داده در همه مکانهای دیگر)
روی Done کلیک کنید.
هنگامی که Realtime Database فعال می کنید، API را در Cloud API Manager نیز فعال می کند.
SDK Realtime Database به برنامه خود اضافه کنید
در فایل Gradle ماژول (سطح برنامه) خود (معمولا <project>/<app-module>/build.gradle.kts یا <project>/<app-module>/build.gradle )، وابستگی را برای کتابخانه Realtime Database برای Android اضافه کنید. توصیه میکنیم از Firebase Android BoM برای کنترل نسخهسازی کتابخانه استفاده کنید.
dependencies{// Import the BoM for the Firebase platformimplementation(platform("com.google.firebase:firebase-bom:34.2.0"))// Add the dependency for the Realtime Database library// When using the BoM, you don't specify versions in Firebase library dependenciesimplementation("com.google.firebase:firebase-database")}
با استفاده از Firebase Android BoM ، برنامه شما همیشه از نسخههای سازگار کتابخانههای Firebase Android استفاده میکند.
(جایگزین) وابستگی های کتابخانه Firebase را بدون استفاده از BoM اضافه کنید
اگر تصمیم گرفتید از Firebase BoM استفاده نکنید، باید هر نسخه کتابخانه Firebase را در خط وابستگی آن مشخص کنید.
توجه داشته باشید که اگر از چندین کتابخانه Firebase در برنامه خود استفاده می کنید، ما قویاً توصیه می کنیم از BoM برای مدیریت نسخه های کتابخانه استفاده کنید، که تضمین می کند همه نسخه ها سازگار هستند.
dependencies{// Add the dependency for the Realtime Database library// When NOT using the BoM, you must specify versions in Firebase library dependenciesimplementation("com.google.firebase:firebase-database:22.0.0")}
Realtime Database Security Rules پیکربندی کنید
Realtime Database یک زبان قواعد اعلامی را ارائه می دهد که به شما امکان می دهد نحوه ساختار داده های شما، نحوه فهرست بندی و زمان خواندن و نوشتن داده های شما را تعریف کنید.
در پایگاه داده خود بنویسید
نمونه ای از پایگاه داده خود را با استفاده از getInstance() بازیابی کنید و به مکانی که می خواهید در آن بنویسید ارجاع دهید.
Kotlin
// Write a message to the databasevaldatabase=Firebase.databasevalmyRef=database.getReference("message")myRef.setValue("Hello, World!")
// Write a message to the databaseFirebaseDatabasedatabase=FirebaseDatabase.getInstance();DatabaseReferencemyRef=database.getReference("message");myRef.setValue("Hello, World!");
از این طریق می توانید طیف وسیعی از انواع داده ها را در پایگاه داده ذخیره کنید، از جمله اشیاء جاوا. هنگامی که یک شی را ذخیره می کنید، پاسخ های دریافت کننده ها به عنوان فرزندان این مکان ذخیره می شوند.
از پایگاه داده خود بخوانید
برای بهروزرسانی دادههای برنامه خود در زمان واقعی، باید یک ValueEventListener به مرجعی که ایجاد کردهاید اضافه کنید.
متد onDataChange() در این کلاس یک بار هنگامی که شنونده متصل می شود و دوباره هر بار که داده ها از جمله فرزندان تغییر می کنند، راه اندازی می شود.
Kotlin
// Read from the databasemyRef.addValueEventListener(object:ValueEventListener{overridefunonDataChange(dataSnapshot:DataSnapshot){// This method is called once with the initial value and again// whenever data at this location is updated.valvalue=dataSnapshot.getValue<String>()Log.d(TAG,"Value is: $value")}overridefunonCancelled(error:DatabaseError){// Failed to read valueLog.w(TAG,"Failed to read value.",error.toException())}})
// Read from the databasemyRef.addValueEventListener(newValueEventListener(){@OverridepublicvoidonDataChange(@NonNullDataSnapshotdataSnapshot){// This method is called once with the initial value and again// whenever data at this location is updated.Stringvalue=dataSnapshot.getValue(String.class);Log.d(TAG,"Value is: "+value);}@OverridepublicvoidonCancelled(@NonNullDatabaseErrorerror){// Failed to read valueLog.w(TAG,"Failed to read value.",error.toException());}});
هنگام استفاده از Firebase Realtime Database در برنامه خود همراه با ProGuard، باید در نظر داشته باشید که چگونه اشیاء مدل شما پس از مبهم سازی سریالی و غیر سریالی می شوند. اگر از DataSnapshot.getValue(Class) یا DatabaseReference.setValue(Object) برای خواندن و نوشتن داده ها استفاده می کنید، باید قوانینی را به فایل proguard-rules.pro اضافه کنید:
تاریخ آخرین بهروزرسانی 2025-09-04 بهوقت ساعت هماهنگ جهانی.
[[["درک آسان","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-09-04 بهوقت ساعت هماهنگ جهانی."],[],[],null,["\u003cbr /\u003e\n\nIf you haven't already,\n[add Firebase to your Android project](/docs/android/setup).\n\nCreate a Database\n\n1. Navigate to the **Realtime Database** section of the\n [Firebase console](https://console.firebase.google.com/project/_/database).\n You'll be prompted to select an existing Firebase project.\n Follow the database creation workflow.\n\n2. Select a starting mode for your Firebase Security Rules:\n\n Test mode\n\n : Good for getting started with the mobile and web client libraries,\n but allows anyone to read and overwrite your data. After testing, **make\n sure to review the [Understand Firebase Realtime Database Rules](/docs/database/security)\n section.**\n\n :\n | **Note:** If you create a database in Test mode and make no changes to the default world-readable and world-writeable Rules within a trial period, you will be alerted by email, then your database rules will deny all requests. Note the expiration date during the Firebase console setup flow.\n\n : To get started with the web, Apple, or Android SDK, select testmode.\n\n Locked mode\n\n : Denies all reads and writes from mobile and web clients.\n Your authenticated application servers can still access your database.\n\n3. Choose a location for the database.\n\n Depending on the\n [location of the database](/docs/projects/locations#rtdb-locations), the\n URL for the new database will be in one of the following forms:\n - \u003cvar translate=\"no\"\u003eDATABASE_NAME\u003c/var\u003e`.firebaseio.com` (for\n databases in `us-central1`)\n\n - \u003cvar translate=\"no\"\u003eDATABASE_NAME\u003c/var\u003e`.`\u003cvar translate=\"no\"\u003eREGION\u003c/var\u003e`.firebasedatabase.app`\n (for databases in all other locations)\n\n4. Click **Done**.\n\nWhen you enable Realtime Database, it also enables the API in the\n[Cloud API Manager](https://console.cloud.google.com/projectselector/apis/api/firebasedatabase.googleapis.com/overview).\n\nAdd the Realtime Database SDK to your app In your **module (app-level) Gradle file** (usually `\u003cproject\u003e/\u003capp-module\u003e/build.gradle.kts` or `\u003cproject\u003e/\u003capp-module\u003e/build.gradle`), add the dependency for the Realtime Database library for Android. We recommend using the [Firebase Android BoM](/docs/android/learn-more#bom) to control library versioning.\n\n\u003cbr /\u003e\n\n```carbon\ndependencies {\n // Import the BoM for the Firebase platform\n implementation(platform(\"com.google.firebase:firebase-bom:34.2.0\"))\n\n // Add the dependency for the Realtime Database library\n // When using the BoM, you don't specify versions in Firebase library dependencies\n implementation(\"com.google.firebase:firebase-database\")\n}\n```\n\nBy using the [Firebase Android BoM](/docs/android/learn-more#bom),\nyour app will always use compatible versions of Firebase Android libraries.\n*(Alternative)*\nAdd Firebase library dependencies *without* using the BoM\n\nIf you choose not to use the Firebase BoM, you must specify each Firebase library version\nin its dependency line.\n\n**Note that if you use *multiple* Firebase libraries in your app, we strongly\nrecommend using the BoM to manage library versions, which ensures that all versions are\ncompatible.** \n\n```groovy\ndependencies {\n // Add the dependency for the Realtime Database library\n // When NOT using the BoM, you must specify versions in Firebase library dependencies\n implementation(\"com.google.firebase:firebase-database:22.0.0\")\n}\n```\n\n\u003cbr /\u003e\n\nConfigure Realtime Database Security Rules\n\nThe Realtime Database provides a declarative rules language that allows\nyou to define how your data should be structured, how it should be\nindexed, and when your data can be read from and written to.\n| **Note:** By default, read and write access to your database is restricted so only authenticated users can read or write data. To get started without setting up [Authentication](/docs/auth), you can [configure your rules for public access](/docs/rules/basics#default_rules_locked_mode). This does make your database open to anyone, even people not using your app, so be sure to restrict your database again when you set up authentication.\n\nWrite to your database\n\nRetrieve an instance of your database using `getInstance()` and\nreference the location you want to write to.\n| **Important** : To get a reference to a database other than a `us-central1` default database, you must pass the database URL to `getInstance()` (or for Kotlin `database()`). For a `us-central1` default database, you can call `getInstance()` (or `database`) without arguments.\n|\n| You can find your Realtime Database URL in the *Realtime Database* section of the\n| [Firebase console](//console.firebase.google.com/). Depending on the\n| [location of the database](/docs/projects/locations#rtdb-locations),\n| the database URL will be in one of the following forms:\n|\n| - `https://`\u003cvar translate=\"no\"\u003eDATABASE_NAME\u003c/var\u003e`.firebaseio.com` (for databases in `us-central1`)\n- `https://`\u003cvar translate=\"no\"\u003eDATABASE_NAME\u003c/var\u003e`.`\u003cvar translate=\"no\"\u003eREGION\u003c/var\u003e`.firebasedatabase.app` (for databases in all other locations) \n\nKotlin \n\n```kotlin\n// Write a message to the database\nval database = Firebase.database\nval myRef = database.getReference(\"message\")\n\nmyRef.setValue(\"Hello, World!\")https://github.com/firebase/snippets-android/blob/b694d4dbd411d31be39655f47691c3e9f3529b03/database/app/src/main/java/com/google/firebase/referencecode/database/kotlin/MainActivity.kt#L28-L32\n```\n\nJava \n\n```java\n// Write a message to the database\nFirebaseDatabase database = FirebaseDatabase.getInstance();\nDatabaseReference myRef = database.getReference(\"message\");\n\nmyRef.setValue(\"Hello, World!\");https://github.com/firebase/snippets-android/blob/b694d4dbd411d31be39655f47691c3e9f3529b03/database/app/src/main/java/com/google/firebase/referencecode/database/MainActivity.java#L42-L46\n```\n\nYou can save a range of data types to the database this way, including Java\nobjects. When you save an object the responses from any getters will be saved as\nchildren of this location.\n\nRead from your database\n\nTo make your app data update in realtime, you should add a\n[`ValueEventListener`](/docs/reference/android/com/google/firebase/database/ValueEventListener)\nto the reference you just created.\n\nThe `onDataChange()` method in this class is triggered once when the listener is\nattached and again every time the data changes, including the children. \n\nKotlin \n\n```kotlin\n// Read from the database\nmyRef.addValueEventListener(object : ValueEventListener {\n override fun onDataChange(dataSnapshot: DataSnapshot) {\n // This method is called once with the initial value and again\n // whenever data at this location is updated.\n val value = dataSnapshot.getValue\u003cString\u003e()\n Log.d(TAG, \"Value is: $value\")\n }\n\n override fun onCancelled(error: DatabaseError) {\n // Failed to read value\n Log.w(TAG, \"Failed to read value.\", error.toException())\n }\n})https://github.com/firebase/snippets-android/blob/b694d4dbd411d31be39655f47691c3e9f3529b03/database/app/src/main/java/com/google/firebase/referencecode/database/kotlin/MainActivity.kt#L36-L49\n```\n\nJava \n\n```java\n// Read from the database\nmyRef.addValueEventListener(new ValueEventListener() {\n @Override\n public void onDataChange(@NonNull DataSnapshot dataSnapshot) {\n // This method is called once with the initial value and again\n // whenever data at this location is updated.\n String value = dataSnapshot.getValue(String.class);\n Log.d(TAG, \"Value is: \" + value);\n }\n\n @Override\n public void onCancelled(@NonNull DatabaseError error) {\n // Failed to read value\n Log.w(TAG, \"Failed to read value.\", error.toException());\n }\n});https://github.com/firebase/snippets-android/blob/b694d4dbd411d31be39655f47691c3e9f3529b03/database/app/src/main/java/com/google/firebase/referencecode/database/MainActivity.java#L50-L65\n```\n\nOptional: Configure ProGuard\n\nWhen using Firebase Realtime Database in your app along with ProGuard, you need to\nconsider how your model objects will be serialized and deserialized after\nobfuscation. If you use `DataSnapshot.getValue(Class)` or\n`DatabaseReference.setValue(Object)` to read and write data, you will need to\nadd rules to the `proguard-rules.pro` file: \n\n # Add this global rule\n -keepattributes Signature\n\n # This rule will properly ProGuard all the model classes in\n # the package com.yourcompany.models.\n # Modify this rule to fit the structure of your app.\n -keepclassmembers class com.yourcompany.models.** {\n *;\n }\n\nTo get help for questions or issues related to ProGuard, visit the\n[Guardsquare Community forums](https://community.guardsquare.com/?utm_source=site&utm_medium=site-link&utm_campaign=firebase-install-community)\nto get assistance from an expert.\n\nPrepare for Launch\n\nBefore launching your app, we recommend walking through our\n[launch checklist](/support/guides/launch-checklist) to make sure your app is\nready to go!\n\nBe sure to enable [App Check](/docs/app-check/android) to help ensure that\nonly your apps can access your databases.\n\nNext Steps\n\n- Learn how to [structure data](/docs/database/android/structure-data) for Realtime Database\n- [Scale your data across multiple database instances](/docs/database/usage/sharding).\n- [Read and write data](/docs/database/android/read-and-write).\n- [View your database in the Firebase console](https://console.firebase.google.com/project/_/database/data)."]]