【问题标题】:Uploading data in Firestore Database using Kotlin. Unable to store data使用 Kotlin 在 Firestore 数据库中上传数据。无法存储数据
【发布时间】:2018-03-20 20:53:48
【问题描述】:

我不知道是什么问题,但来自 Edittext 的字符串没有存储在我的 Firestore 数据库中。请帮助我也是 Firestore 和 kotlin 的新手

MainActivity.java

class MainActivity : AppCompatActivity() {

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

    val mFirestore: FirebaseFirestore = FirebaseFirestore.getInstance()

    val name = findViewById<EditText>(R.id.nameText)//nameText.text.toString()
    val user = findViewById<EditText>(R.id.userText)
    val occ = "Student"

    val usermap = HashMap<String, Any>()
    usermap.put("Name", name.text.toString())
    usermap.put("Occupation", occ)
    usermap.put("Type", user.text.toString())

    button.setOnClickListener() {

        mFirestore.collection("Users").add(usermap).addOnSuccessListener() {
            Toast.makeText(this, "Data Stored", Toast.LENGTH_SHORT).show()
        }.addOnFailureListener() {
            Toast.makeText(this, "Data Not Stored", Toast.LENGTH_SHORT).show()
        }
    }
}
}

这是我的 Firestore 数据库截图,请检查并帮助我

Image

【问题讨论】:

    标签: android firebase kotlin google-cloud-firestore


    【解决方案1】:

    当您创建 EditTexts 中的值时,您会立即(并且仅一次)读取它们 - 此时它们仍然是空的。相反,每次都在侦听器的回调中读取它们的值,如下所示:

    button.setOnClickListener() {
        val usermap = HashMap<String, Any>()
        usermap.put("Name", name.text.toString())
        usermap.put("Occupation", occ)
        usermap.put("Type", user.text.toString())
    
        mFirestore.collection("Users").add(usermap).addOnSuccessListener() {
            Toast.makeText(this, "Data Stored", Toast.LENGTH_SHORT).show()
        }.addOnFailureListener() {
            Toast.makeText(this, "Data Not Stored", Toast.LENGTH_SHORT).show()
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-29
      • 2014-06-01
      相关资源
      最近更新 更多