android - 获取用户数据,用户根据使用 Kotlin 注册时提供的信息获取闪屏后的活动
问题描述
我正在做一个大学项目,学生和老师正在使用学校数据。我希望教师和学生能够访问不同的数据。我希望教师发送到家庭活动,而学生发送到主要活动。用户在注册时已经输入了他的类型。我希望用户根据用户类型获得特定活动。我正在获取用户类型的数据,但无法将其用于其他工作。
这是我的代码:
override fun onStart() {
super.onStart()
var usertype: String? = null
if (FirebaseAuth.getInstance().currentUser != null) {
var currentUser: String = FirebaseAuth.getInstance().currentUser.uid
val DataBaseReference = FirebaseDatabase.getInstance().getReference().child("Users")
DataBaseReference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(datasnapshot: DataSnapshot) {
usertype = datasnapshot.child(currentUser).child("type").getValue(String::class.java)
usertype?.let { Log.d("usertype", it) }
}
override fun onCancelled(error: DatabaseError) {
}
})
val utype = usertype.toString()
Log.i("utype", utype)
if (utype == "Student"){
val intent = Intent(this, MainActivity::class.java)
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
finish()
}
else {
val intent = Intent(this, home::class.java)
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
finish()
}
}
}
user-type的Log结果是student,utype的Log结果为null。现在我想从 onDatachange 获取用户类型的数据到其他函数。
解决方案
我正在获取用户类型的数据,但无法将其用于其他工作。
发生这种情况是因为您使用了以下 if 语句:
val utype = usertype.toString()
Log.i("utype", utype)
if (utype == "Student"){ ...}
回调外。Firebase API 是异步的。任何需要来自异步操作的数据的代码都需要在“onDataChange()”方法中,或者从那里调用。因此,在这种情况下,最简单的解决方案是将与上述代码行相关的所有逻辑移动到“onDataChange()”方法中,范围内let
:
usertype = datasnapshot.child(currentUser).child("type").getValue(String::class.java)
usertype?.let {
Log.d("usertype", it)
//Use your logic
}
}
推荐阅读
- python - TensorFlow 没有安装?
- python - Web3.eth:溢出错误:Python int 太大而无法转换为 C ssize_t
- linux - Linux 文件命令使用哪个系统调用?
- flutter - 颤振图表处理图例新闻
- ruby-on-rails - Rails reverse proxied by Nginx: change of origin problem
- node.js - Nodejs-cron for logging
- svelte - Svelte 获取当前 svelte 文件的所有属性
- android - 流星移动应用程序不适用于 android 9 和 10
- cmake - 如何使用命令行(CMake)跳过一些目标
- asp.net-core - child relationship not available in parent object