حفظ البيانات في قاعدة بيانات محلية باستخدام Room
جزء من Android Jetpack.
يمكن للتطبيقات التي تتعامل مع كميات كبيرة من البيانات المنظَّمة الاستفادة بشكل كبير من تخزين هذه البيانات على الجهاز. وأكثر حالات الاستخدام شيوعًا هي تخزين مقتطفات البيانات ذات الصلة مؤقتًا لكي يظل بإمكان المستخدم تصفّح هذا المحتوى بلا إنترنت عندما يتعذّر على الجهاز الوصول إلى الشبكة.
توفّر مكتبة Room للحفاظ على البيانات طبقة تجريدية فوق SQLite للسماح بالوصول إلى قاعدة البيانات بسلاسة مع الاستفادة من الإمكانات الكاملة لـ SQLite. على وجه الخصوص، يقدّم Room المزايا التالية:
- التحقّق من طلبات لغة الاستعلامات البنيوية (SQL) في وقت الترجمة
- التعليقات التوضيحية الملائمة التي تقلّل من النصوص النموذجية المتكرّرة والمعرضة للأخطاء
- مسارات نقل قاعدة البيانات المبسّطة
وبناءً على هذه الاعتبارات، ننصحك بشدة باستخدام Room بدلاً من استخدام واجهات برمجة تطبيقات SQLite مباشرةً.
ضبط إعدادات الجهاز
لاستخدام Room في تطبيقك، أضِف الملحقات التالية إلى ملف
build.gradle
في تطبيقك.
dependencies { val room_version = "2.6.1" implementation("androidx.room:room-runtime:$room_version") // If this project uses any Kotlin source, use Kotlin Symbol Processing (KSP) // See Add the KSP plugin to your project ksp("androidx.room:room-compiler:$room_version") // If this project only uses Java source, use the Java annotationProcessor // No additional plugins are necessary annotationProcessor("androidx.room:room-compiler:$room_version") // optional - Kotlin Extensions and Coroutines support for Room implementation("androidx.room:room-ktx:$room_version") // optional - RxJava2 support for Room implementation("androidx.room:room-rxjava2:$room_version") // optional - RxJava3 support for Room implementation("androidx.room:room-rxjava3:$room_version") // optional - Guava support for Room, including Optional and ListenableFuture implementation("androidx.room:room-guava:$room_version") // optional - Test helpers testImplementation("androidx.room:room-testing:$room_version") // optional - Paging 3 Integration implementation("androidx.room:room-paging:$room_version") }
dependencies { def room_version = "2.6.1" implementation "androidx.room:room-runtime:$room_version" // If this project uses any Kotlin source, use Kotlin Symbol Processing (KSP) // See KSP Quickstart to add KSP to your build ksp "androidx.room:room-compiler:$room_version" // If this project only uses Java source, use the Java annotationProcessor // No additional plugins are necessary annotationProcessor "androidx.room:room-compiler:$room_version" // optional - RxJava2 support for Room implementation "androidx.room:room-rxjava2:$room_version" // optional - RxJava3 support for Room implementation "androidx.room:room-rxjava3:$room_version" // optional - Guava support for Room, including Optional and ListenableFuture implementation "androidx.room:room-guava:$room_version" // optional - Test helpers testImplementation "androidx.room:room-testing:$room_version" // optional - Paging 3 Integration implementation "androidx.room:room-paging:$room_version" }
المكونات الأساسية
هناك ثلاثة مكوّنات رئيسية في Room:
- فئة قاعدة البيانات التي تحتوي على قاعدة البيانات وتعمل بمثابة نقطة الوصول الرئيسية للاتصال الأساسي ببيانات تطبيقك الثابتة
- كيانات البيانات التي تمثّل الجداول في قاعدة بيانات تطبيقك
- عناصر الوصول إلى البيانات (DAO) التي توفّر methods يمكن لتطبيقك استخدامها لطلب طلبات بحث عن data في قاعدة البيانات وتعديلها وإدراجها وحذفها
توفّر فئة قاعدة البيانات لتطبيقك مثيلات لـ DAO المرتبطة بقاعدة البيانات هذه. في المقابل، يمكن للتطبيق استخدام واجهة DAO لاسترداد البيانات من قاعدة بيانات كمثيلات لكائنات عناصر البيانات المرتبطة. يمكن للتطبيق أيضًا استخدام كيانات البيانات المحدّدة لتعديل الصفوف من الجداول المقابلة، أو لإنشاء صفوف جديدة لإدراجها. يوضّح الشكل 1 العلاقة بين المكوّنات المختلفة لـ Room.

مثال على التنفيذ
يقدّم هذا القسم مثالاً على تنفيذ قاعدة بيانات Room باستخدام كينان data واحد وDAO واحد.
عنصر البيانات
تحدِّد التعليمة البرمجية التالية عنصر بيانات User
. يمثّل كل مثيل من User
صفًا في جدول user
في قاعدة بيانات التطبيق.
@Entity data class User( @PrimaryKey val uid: Int, @ColumnInfo(name = "first_name") val firstName: String?, @ColumnInfo(name = "last_name") val lastName: String? )
@Entity public class User { @PrimaryKey public int uid; @ColumnInfo(name = "first_name") public String firstName; @ColumnInfo(name = "last_name") public String lastName; }
لمزيد من المعلومات عن عناصر البيانات في Room، اطّلِع على مقالة تحديد البيانات باستخدام عناصر Room.
كائن الوصول إلى البيانات (DAO)
تحدِّد التعليمة البرمجية التالية DAO باسم UserDao
. يوفّر UserDao
methods التي تستخدمها بقية أجزاء التطبيق للتفاعل مع البيانات في جدول user
.
@Dao interface UserDao { @Query("SELECT * FROM user") fun getAll(): List<User> @Query("SELECT * FROM user WHERE uid IN (:userIds)") fun loadAllByIds(userIds: IntArray): List<User> @Query("SELECT * FROM user WHERE first_name LIKE :first AND " + "last_name LIKE :last LIMIT 1") fun findByName(first: String, last: String): User @Insert fun insertAll(vararg users: User) @Delete fun delete(user: User) }
@Dao public interface UserDao { @Query("SELECT * FROM user") List<User> getAll(); @Query("SELECT * FROM user WHERE uid IN (:userIds)") List<User> loadAllByIds(int[] userIds); @Query("SELECT * FROM user WHERE first_name LIKE :first AND " + "last_name LIKE :last LIMIT 1") User findByName(String first, String last); @Insert void insertAll(User... users); @Delete void delete(User user); }
لمزيد من المعلومات عن DAO، اطّلِع على مقالة الوصول إلى البيانات باستخدام DAO Room.
قاعدة البيانات
تحدِّد التعليمة البرمجية التالية فئة AppDatabase
لتخزين قاعدة البيانات.
تحدِّد AppDatabase
إعدادات قاعدة البيانات وتُستخدَم كنقطة
وصول التطبيق الرئيسية إلى البيانات الثابتة. يجب أن تستوفي فئة قاعدة البيانات الشروط التالية:
- يجب أن يكون الصفّ مُعلَقًا بتعليق توضيحي
@Database
يحتوي على مصفوفةentities
تسرد جميع كيانات البيانات المرتبطة بقاعدة البيانات. - يجب أن تكون الفئة فئة مجردة تمديدًا لمحاولة
RoomDatabase
. - بالنسبة إلى كل فئة DAO مرتبطة بقاعدة البيانات، يجب أن تحدِّد فئة قاعدة البيانات طريقة مجردة لا تحتوي على أيّ وسيطات وتُعيد مثيلًا لفئة DAO.
@Database(entities = [User::class], version = 1) abstract class AppDatabase : RoomDatabase() { abstract fun userDao(): UserDao }
@Database(entities = {User.class}, version = 1) public abstract class AppDatabase extends RoomDatabase { public abstract UserDao userDao(); }
ملاحظة: إذا كان تطبيقك يعمل في عملية واحدة، عليك اتّباع
نمط التصميم للعنصر الفردي عند إنشاء مثيل لعنصر AppDatabase
. إنّ كلّ نسخة من RoomDatabase
باهظة التكلفة إلى حدٍّ ما، وقلّما تحتاج
إلى الوصول إلى نُسخ متعدّدة ضمن عملية واحدة.
إذا كان تطبيقك يعمل في عمليات متعددة، أدرِج enableMultiInstanceInvalidation()
في استدعاء enableMultiInstanceInvalidation()
لإنشاء قاعدة البيانات. بهذه الطريقة، عندما يكون لديك مثيل من AppDatabase
في كل عملية، يمكنك إلغاء صلاحية ملف قاعدة البيانات المشترَكة في عملية واحدة،
ويتم نشر هذا الإلغاء تلقائيًا إلى نُسخ AppDatabase
في العمليات الأخرى.
الاستخدام
بعد تحديد عنصر البيانات وDAO وعنصر قاعدة البيانات، يمكنك استخدام الرمز البرمجي التالي لإنشاء مثيل لقاعدة البيانات:
val db = Room.databaseBuilder( applicationContext, AppDatabase::class.java, "database-name" ).build()
AppDatabase db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "database-name").build();
يمكنك بعد ذلك استخدام الطرق المجردة من AppDatabase
للحصول على مثيل
لـ DAO. بدورك، يمكنك استخدام الطرق من مثيل DAO للتفاعل
مع قاعدة البيانات:
val userDao = db.userDao() val users: List<User> = userDao.getAll()
UserDao userDao = db.userDao(); List<User> users = userDao.getAll();
مصادر إضافية
لمزيد من المعلومات عن Room، يُرجى الاطّلاع على المراجع الإضافية التالية:
نماذج
تتيح Microsoft للمستخدمين والمؤسسات العمل والتعلّم والتنظيم والتواصل والابتكار من خلال تطبيقاتهم الرائدة في Microsoft 365. ولتحقيق ذلك، تدرك الشركة أنّه من الضروري توفير تجربة إنتاجية مثالية لعملائها على جميع الأجهزة التي يستخدمونها. تساعد منصّة Square ملايين البائعين في إدارة
نشاطك التجاري، بدءًا من المعالجة الآمنة لبطاقات الائتمان ووصولاً إلى حلول نقاط البيع
إعداد متجر مجاني على الإنترنت. تم نقل المربع إلى واجهة المستخدم التعريفية
لفترة من الوقت ولكن بدلاً من الاستمرار في بناء Monzo هو مصرف وتطبيق يقدّمان
الخدمات المالية الرقمية. مهمتهم هي تحقيق الأرباح
للجميع. بدأ نظام تصميم مونزو ينحرف عن Material Design بحيث
أرادوا طريقة سهلة لكتابة المكوّنات المخصصة وصيانتها تتطوّر باستمرار، لذا اختارت Jetpack Compose. باستخدام منصة Twitter هي واحدة من أكثر وسائل التواصل الاجتماعي استخدامًا
ومنصات الوسائط التي تتيح للمستخدمين رؤية ما يحدث في العالم في أي وقت
اللحظة. بدأ الفريق الهندسي باستخدام Jetpack Compose لتجديد
نظام التصميم. بما أنّه تم تطوير مكونات واجهة المستخدم شركة Cuvva تحسّن التأمين بشكل كبير
من خلال منحك طريقة مرنة حقًا لإدارة الغلاف، كل ذلك من خلال هاتفك.
كان على مهندسي Android في Cuvva قضاء بعض الوقت في إعادة هندسة تطبيقاتهم
وقررت اعتماد تدفق بيانات أحادي الاتجاه وJetpack Compose. بهذه الطريقة
يمكنهم ShareChat is a leading social media platform in India that allows users to share their opinions, document their lives, and make new friends in their native language. The standard Red Up Green Down color scheme that many wealth management app users take for granted can be very problematic for colorblind users and those with color vision deficiency.The Futubull team is embracing users’ needs by making concrete improvements so that everyone can grasp the key to wealth. TikTok, the world’s community-driven entertainment destination, brings over 1 billion people together from around the world to discover, create and share content they love. OkCredit is a credit account management app for millions of shop owners and their customers in India. With 140M transactions month over month, and 50M+ downloads, last year alone saw OkCredit recording $50 billion worth of transactions on the app. Operating at such a huge scale scale, OkCredit created a smooth and seamless experience for all their users by focusing on reducing ANRs and improving the app startup time. Lyft is committed to app excellence. They have to be. For a rideshare app — providing a vital, time-sensitive service to millions of drivers and riders every day — a slow or unresponsive app adds unacceptable friction. Josh is a short-video app from India, launched in 2020. One of the fastest growing short-video apps with over 124 million MAUs, optimizing it across a range of devices (high, mid, low end) and maintaining a standard experience across all of them is critical for their success. Improving app startups time and making the app responsive helped them achieve success. Microsoft Lens increases developer productivity using CameraX Zomato is an Indian multinational restaurant aggregator and food delivery company serving customers across 500 cities in India alone. In order to launch new features on their Android app, Headspace spent 8 months refactoring their architecture and rewriting in Kotlin. Learn how this reboot helped their business grow. Google Photos is the home for your memories, and their development team believes people should be able to enjoy those memories across all devices. Learn how Duolingo made the business decision to focus on Android performance and how they improved developer productivity and scaled their business. Mercari allows millions of people to shop and sell almost anything. The company was founded in 2013 in Japan, and it now is the largest smartphone-focused C2C marketplace in Japan. Google Duo is a simple, high quality video calling app for everyone. With the increase of people being at home during the Covid-19 pandemic, the Duo team saw a significant increase in people using the app to stay connected with friends & family, school and work. Headspace drive business growth by investing in Android app quality. SmartNews helps millions of people discover their world everyday by sharing timely news from a diverse set of news sources. Twitter is one of the most widely used social media platforms where users can see what’s happening in the world at any given moment. Delight Room Alarmy is an alarm app that can be turned off only when the pre-selected activities, such as taking a photo, solving a math problem, shaking phone, etc., are performed by the user. The Google Home app helps set up, manage, and control your Google Home, Google Nest, and Chromecast devices—plus thousands of connected home products like lights, cameras, thermostats, and more. Truecaller is an app that offers caller identification, call blocking, chat messaging and organized inbox. The app has a basic offering and a premium version which is ad-free and has a variety of unlocked features like advanced spam blocking and call recording.تمكّنت Microsoft Outlook وTeams وOffice من زيادة عدد المستخدمين النشطين والاحتفاظ بالمستخدمين باستخدام الشاشات الكبيرة.
يحقّق المربع زيادة في الإنتاجية باستخدام Compose
تنشئ Monzo تطبيقًا أكثر فعالية وجودة باستخدام Compose
شركة Twitter تحقّق زيادة في كفاءة وسرعة المطوّرين باستخدام Compose
تنشئ شركة Cuvva أكثر سرعة وبجودة أعلى من خلال Compose.
ShareChat addresses Jank issues to increase feed scrolling by 60%
The Key to Wealth for Everyone
TikTok Optimizes User Experience with Android Tools
OkCredit’s average merchant transaction goes up by 30% after reducing ANR
Lyft improves Android app startup time for drivers by 21%
Josh sees increased customer retention by improving app startup time by 30%
Microsoft Lens increases developer productivity using CameraX
Increasing app speed by 30%: a key ingredient in Zomato’s growth recipe
Headspace's Android reboot increases monthly active users by 15%
Google Photos increased daily active users by building for large screens
Duolingo refactors on Android with MVVM and Jetpack libraries
Mercari improves UI development productivity by 56% with Jetpack Compose
Google Duo sees increased engagement and improved ratings by optimizing for larger screens
Headspace drive business growth by investing in Android app quality
SmartNews reduces lines of code by 20% and improves team morale with Kotlin
Twitter increases developer productivity and code reliability with Kotlin
Delight Room increased 90% of its organic US users with Play Console
Google Home reduces #1 cause of crashes by 33%
Truecaller brings ~40% subscribers back with real time developer notifications