首先感謝您的時間。我正在嘗試在我的應用程式中添加兩個選項登錄。一份給醫生,一份給病人。我實作了將它們都存盤在實時資料庫中,如下所示。
患者/醫生 --> 實時資料庫
正如您所看到的,我有一個標簽(“isDoctor”),其值為 true o false 以區分兩個用戶。我想要的是檢查這個“isDoctor”標簽的值,以將用戶發送到相應的活動。如果 isDoctor 為真,我想將用戶發送到 Doctor 活動,如果是相應的患者。認為一旦用戶登錄,此檢查應進入“State.Succes”,但我不知道如何執行。
這是我來自 RemoteDataSource 類和登錄活動的登錄代碼。我正在為這個專案使用帶有流的 mvvm。
mBinding.btnLogin.setOnClickListener {
if (areFieldsReady()) {
lifecycleScope.launchWhenStarted {
loginViewModel.login(email, password).collect { loginResult ->
when (loginResult) {
is State.Loading -> {
if (loginResult.flag == true) loadingDialog.startLoading()
}
is State.Succes -> {
loadingDialog.stopLoading()
Snackbar.make(
mBinding.root,
loginResult.data.toString(),
Snackbar.LENGTH_SHORT
).show()
}
is State.Failed -> {
loadingDialog.stopLoading()
Snackbar.make(
mBinding.root,
loginResult.error,
Snackbar.LENGTH_SHORT
).show()
}
}
}
}
}
}
fun login(email: String, password: String): Flow<State<Any>> = flow<State<Any>> {
emit(State.loading(true))
val auth = Firebase.auth
val data = auth.signInWithEmailAndPassword(email, password).await()
//if the task was performend in backend
data?.let {
if (auth.currentUser?.isEmailVerified!!) {
emit(State.succes(R.string.login_succes)) //emiting the class directly by using the function
} else {
auth.currentUser?.sendEmailVerification()?.await()
emit(State.failed(R.string.verify_email_first.toString()))
}
}
}.catch {
emit(State.failed(it.message!!))
}.flowOn(Dispatchers.IO)
當然,在登錄之前,我對這個道具有一個“唱歌”方法。我沒有在這里添加,因為我認為它沒有添加有關代碼和問題的更多資訊
uj5u.com熱心網友回復:
由于“醫生”和“患者”節點存在于資料庫中的不同層次結構中,因此您無法執行查詢來過濾它們。實時資料庫中的查詢在節點的平面串列上作業,其中要對其執行過濾的值必須位于每個直接子節點下的固定路徑中。話雖如此,您應該使用更簡單的資料庫模式,它可以讓您執行所需的查詢。
請注意,我們正在根據要執行的查詢構建實時資料庫資料庫。由于醫生和患者都可以被視為您的應用程式的用戶,并且您已經使用布爾欄位“醫生”區分了他們,因此無需在您的資料庫中創建兩個不同的節點。因此,構建此類架構的更簡單的解決方案是:
Firebase-root
|
--- users
|
--- $uid
| |
| --- doctor: true
| |
| --- email: "[email protected]"
|
--- $uid
|
--- doctor: false
|
--- email: "[email protected]"
因此,為了能夠將用戶重定向到相應的活動,State.Succes您應該在您的內部使用以下代碼行:
val uid = FirebaseAuth.getInstance().currentUser?.uid
val db = FirebaseDatabase.getInstance().reference
val uidRef = db.child("users").child(uid)
val valueEventListener = object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val doctor = snapshot.child("doctor").getValue(Boolean.class)
if(doctor) {
startActivity(Intent(context, DoctorActivity::class.java));
} else () {
startActivity(Intent(context, PatientActivity::class.java));
}
}
override fun onCancelled(databaseError: error) {
Log.d("TAG", error.getMessage()) //Don't ignore potential errors!
}
}
uidRef.addListenerForSingleValueEvent(valueEventListener)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/372865.html
