首页 > 解决方案 > 获取用户数据,用户根据使用 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 获取用户类型的数据到其他函数。

标签: androidfirebasekotlinfirebase-realtime-database

解决方案


我正在获取用户类型的数据,但无法将其用于其他工作。

发生这种情况是因为您使用了以下 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
    }
}

推荐阅读