firebase - Firestore 从集合字段中获取一个值然后返回(Kotlin)
问题描述
如何获取集合字段的值然后返回它?它可以currentUser
用来获取uid
等,但我需要获取另一个字段值。我在菜单上有一个按钮,并且仅当用户是 admin (usertype=1) on 时才显示onPrepareOptionsMenu
。当我将具有函数的对象传递给oncreate
. 但是onPrepareOptionsMenu
之前加载oncreate
所以我得到用户未初始化错误。我需要从“用户”集合中返回“用户类型”字段。
编辑:我发现从 firebase 获取数据是异步的,所以我需要其他方式。
获取用户详细信息
fun getUserDetails(activity: Activity) {
// pass the collection name from which we wants the data.
mFireStore.collection(Constants.USERS)
// The document id to get the Fields of user.
.document(getCurrentUserID())
.get()
.addOnSuccessListener { document ->
// Here we have received the document snapshot which is converted into the User Data model object.
val user = document.toObject(User::class.java)!!
val sharedPreferences =
activity.getSharedPreferences(
Constants.MYSHOPPAL_PREFERENCES,
Context.MODE_PRIVATE
)
// Create an instance of the editor which is help us to edit the SharedPreference.
val editor: SharedPreferences.Editor = sharedPreferences.edit()
editor.putString(
Constants.LOGGED_IN_USERNAME,
"${user.firstName} ${user.lastName}"
)
editor.apply()
when (activity) {
is **ProductDetailActivity**-> {
// Call a function of base activity for transferring the result to it.
**activity.userDetailsSuccess(user)**
}
}
}
.addOnFailureListener { e ->
// Hide the progress dialog if there is any error. And print the error in log.
when (activity) {
is ProductDetailsActivity -> {
activity.hideProgressDialog()
}
}
}
}
产品详情活动
class ProductDetailsActivity : BaseActivity(), View.OnClickListener {
private lateinit var mProductDetails: Product
private lateinit var mUserDetails: User
// A global variable for product id.
private var mProductId: String = ""
/**
* This function is auto created by Android when the Activity Class is created.
*/
override fun onCreate(savedInstanceState: Bundle?) {
//This call the parent constructor
super.onCreate(savedInstanceState)
// This is used to align the xml view to this class
setContentView(R.layout.activity_product_details)
if (intent.hasExtra(Constants.EXTRA_PRODUCT_ID)) {
mProductId =
intent.getStringExtra(Constants.EXTRA_PRODUCT_ID)!!
}
var productOwnerId: String = ""
if (intent.hasExtra(Constants.EXTRA_PRODUCT_OWNER_ID)) {
productOwnerId =
intent.getStringExtra(Constants.EXTRA_PRODUCT_OWNER_ID)!!
}
if (intent.hasExtra(Constants.EXTRA_PRODUCT_DETAILS)) {
mProductDetails= intent.getParcelableExtra(Constants.EXTRA_PRODUCT_DETAILS)!!
}
setupActionBar()
showProgressDialog(resources.getString(R.string.please_wait))
// Call the function of FirestoreClass to get the userdetails.
FirestoreClass().getUserDetails(this@ProductDetailsActivity)
}
override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
//admin can edit all products, seller can edit own products (i'm trying to get usertype BUT mUserDetails IS INITIALIZING AFTER onPrepareOptionsMenu
var productOwnerId: String = ""
if (intent.hasExtra(Constants.EXTRA_PRODUCT_OWNER_ID)) {
productOwnerId =
intent.getStringExtra(Constants.EXTRA_PRODUCT_OWNER_ID)!!
}
if (FirestoreClass().getCurrentUserID() != productOwnerId) {
val menu1 = menu?.findItem(R.id.action_edit_product)
if (menu1 != null) { //null check
menu1.setVisible(false) //menuyu gizle
}
}
return true
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.product_details_menu, menu)
return true
}
ProductDetailsActivity 上的函数
fun userDetailsSuccess(user: User) {
mUserDetails = user
}
示例:getCurrentUserID 用于返回 currentUserID(我想从“users”集合返回“usertype”字段)
fun getCurrentUserID(): String {
// An Instance of currentUser using FirebaseAuth
val currentUser = FirebaseAuth.getInstance().currentUser
// A variable to assign the currentUserId if it is not null or else it will be blank.
var currentUserID = ""
if (currentUser != null) {
currentUserID = currentUser.uid
}
return currentUserID
}
解决方案
推荐阅读
- android - 在我更改 AndroidManifest 文件中的主题后,应用程序不断崩溃
- python-3.x - 使用 Cartopy 和 Pyproj 重新投影 GOES16 卫星数据
- reactjs - 如何测试别名导入
- android - 对 Tokbox/Opentok 应用程序使用 CallKit (iOS) 或 ConnectionService (Android)
- postgresql - PostgreSQL 日期函数输出到法语
- python - 在python中将meshgrid点转换为邻接矩阵
- powerbi - Power BI中KPI在线趋势
- linux - 与作为变量传递给 awk 的正则表达式进行比较
- javascript - 基于用户代理重定向用户
- vba - VBA Excel - “.Find” 从上到下按 K 列的顺序搜索