لبدء استخدام حزمة تطوير البرامج (SDK) على الويب أو Apple أو Android، اختَر testmode.
وضع القفل
يتم رفض جميع عمليات القراءة والكتابة من تطبيقات الأجهزة الجوّالة وعملاء الويب. سيظل بإمكان خوادم التطبيقات التي تمّت المصادقة عليها الوصول إلى قاعدة البيانات.
اختَر موقعًا جغرافيًا لقاعدة البيانات.
استنادًا إلى موقع قاعدة البيانات، سيكون عنوان URL لقاعدة البيانات الجديدة بأحد الأشكال التالية:
DATABASE_NAME.firebaseio.com (لقواعد البيانات في us-central1)
DATABASE_NAME.REGION.firebasedatabase.app (لقواعد البيانات في جميع المواقع الجغرافية الأخرى)
انقر على تم.
عند تفعيل Realtime Database، يتم أيضًا تفعيل واجهة برمجة التطبيقات في 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.1.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متعدّدة في تطبيقك، ننصحك بشدة باستخدام 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!");
يمكنك حفظ مجموعة من أنواع البيانات في قاعدة البيانات بهذه الطريقة، بما في ذلك عناصر Java. عند حفظ عنصر، سيتم حفظ الردود من أي دوال جلب كعناصر فرعية لهذا الموقع.
قراءة البيانات من قاعدة البيانات
لإجراء تعديل على بيانات تطبيقك في الوقت الفعلي، عليك إضافة 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-08-21 (حسب التوقيت العالمي المتفَّق عليه)
[[["يسهُل فهم المحتوى.","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-08-21 (حسب التوقيت العالمي المتفَّق عليه)"],[],[],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.1.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/391c1646eacf44d2aab3f76bcfa60dfc6c14acf1/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/391c1646eacf44d2aab3f76bcfa60dfc6c14acf1/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/391c1646eacf44d2aab3f76bcfa60dfc6c14acf1/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/391c1646eacf44d2aab3f76bcfa60dfc6c14acf1/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)."]]