Android: 使用 Room 和 Firestore?
创始人
2024-10-05 10:30:53
0

在Android中,可以使用Room和Firestore来进行数据存储和同步。Room是一个SQLite对象映射库,用于本地数据库存储,而Firestore是Google提供的云存储解决方案。

首先,确保在项目的build.gradle文件中添加以下依赖项:

dependencies {
    // Room
    implementation "androidx.room:room-runtime:2.4.0"
    kapt "androidx.room:room-compiler:2.4.0"

    // Firestore
    implementation 'com.google.firebase:firebase-firestore:24.0.0'
}

接下来,创建一个Room数据库:

@Database(entities = [User::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao

    companion object {
        @Volatile
        private var INSTANCE: AppDatabase? = null

        fun getInstance(context: Context): AppDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    AppDatabase::class.java,
                    "my_database"
                ).build()
                INSTANCE = instance
                instance
            }
        }
    }
}

然后,创建一个Room实体类和DAO(数据访问对象):

@Entity
data class User(
    @PrimaryKey val id: String,
    val name: String,
    val age: Int
)

@Dao
interface UserDao {
    @Query("SELECT * FROM user")
    fun getAllUsers(): LiveData>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertUser(user: User)

    @Delete
    suspend fun deleteUser(user: User)
}

接下来,创建一个FirestoreHelper类,用于处理与Firestore的交互:

class FirestoreHelper {
    private val db = FirebaseFirestore.getInstance()

    fun addUser(user: User) {
        val userMap = hashMapOf(
            "id" to user.id,
            "name" to user.name,
            "age" to user.age
        )

        db.collection("users")
            .document(user.id)
            .set(userMap)
            .addOnSuccessListener { Log.d(TAG, "User added to Firestore") }
            .addOnFailureListener { e -> Log.w(TAG, "Error adding user", e) }
    }

    fun deleteUser(user: User) {
        db.collection("users")
            .document(user.id)
            .delete()
            .addOnSuccessListener { Log.d(TAG, "User deleted from Firestore") }
            .addOnFailureListener { e -> Log.w(TAG, "Error deleting user", e) }
    }

    fun getAllUsers(listener: (List) -> Unit) {
        db.collection("users")
            .get()
            .addOnSuccessListener { result ->
                val userList = ArrayList()
                for (document in result) {
                    val id = document.getString("id") ?: ""
                    val name = document.getString("name") ?: ""
                    val age = document.getLong("age")?.toInt() ?: 0
                    userList.add(User(id, name, age))
                }
                listener(userList)
            }
            .addOnFailureListener { e -> Log.w(TAG, "Error getting users", e) }
    }

    companion object {
        private const val TAG = "FirestoreHelper"
    }
}

最后,在你的Activity或Fragment中,使用Room和Firestore进行数据存储和同步:

class MainActivity : AppCompatActivity() {
    private lateinit var db: AppDatabase
    private lateinit var userDao: UserDao
    private lateinit var firestoreHelper: FirestoreHelper

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        db = AppDatabase.getInstance(applicationContext)
        userDao = db.userDao()
        firestoreHelper = FirestoreHelper()

        val usersLiveData = userDao.getAllUsers()
        usersLiveData.observe(this, { users ->
            // 更新UI显示用户列表
            Log.d(TAG, "Users: $users")
        })

        val user = User("1", "John Doe", 25)

        // 添加用户到Room数据库
        GlobalScope.launch {
            userDao.insertUser(user)
        }

        // 添加用户到Firestore
        firestoreHelper.addUser(user)

        // 从Firestore获取所有用户
        firestoreHelper.getAllUsers { userList ->
            // 将所有用户添加到Room数据库
            GlobalScope.launch {
                for (user in userList) {
                    userDao.insertUser(user)
                }
            }
        }

        // 删除用户
        GlobalScope.launch {
            userDao.deleteUser(user)
            firestoreHelper.deleteUser(user)
        }
    }

    companion object {

相关内容

热门资讯

Android Recycle... 要在Android RecyclerView中实现滑动卡片效果,可以按照以下步骤进行操作:首先,在项...
安装apache-beam==... 出现此错误可能是因为用户的Python版本太低,而apache-beam==2.34.0需要更高的P...
Android - 无法确定任... 这个错误通常发生在Android项目中,表示编译Debug版本的Java代码时出现了依赖关系问题。下...
Android - NDK 预... 在Android NDK的构建过程中,LOCAL_SRC_FILES只能包含一个项目。如果需要在ND...
Alertmanager在pr... 首先,在Prometheus配置文件中,确保Alertmanager URL已正确配置。例如:ale...
Akka生成Actor问题 在Akka框架中,可以使用ActorSystem对象生成Actor。但是,当我们在Actor类中尝试...
Agora-RTC-React... 出现这个错误原因是因为在 React 组件中使用,import AgoraRTC from “ago...
Aksnginxdomainb... 在AKS集群中,可以使用Nginx代理服务器实现根据域名进行路由。以下是具体步骤:部署Nginx i...
Alertmanager中的基... Alertmanager中可以使用repeat_interval选项指定在一个告警重复发送前必须等待...
AddSingleton在.N... 在C#中创建Singleton对象通常是通过私有构造函数和静态属性来实现,例如:public cla...