【问题标题】:How to run a function that was created in the class? Android Studio如何运行在类中创建的函数?安卓工作室
【发布时间】:2022-12-16 16:05:29
【问题描述】:

我正在 Android Studio 中制作一个项目。我遇到了一个问题,因为我不知道如何调用在类中创建的函数。我想在同一个文件中调用 test() 以便它会向我的 FireBase 数据库添加一些值,但是当我运行该程序时出现以下错误。 Errors

或者你能建议我如何运行我的函数来检查它是否向我的 Firestore 添加了一些东西吗?即使我没有其他代码来成功运行整个应用程序

package com.example.myapplication

import com.google.firebase.firestore.DocumentReference
import com.google.firebase.firestore.FirebaseFirestore

 class MyDataBase {

    lateinit var db: DocumentReference

    var isStudent = true

    fun initializeDbRef() {
        db = FirebaseFirestore.getInstance().document("Users")

    }

    fun writeNewUser(email: String, pass: String) {

        val items = HashMap<String, Any>()
        items.put("Password", pass)
        db.collection("Students").document("wIPzm1J5zZtVPksa1J8z").set(items)
    }

     fun test(name: String, email: String) {
         val database = FirebaseFirestore.getInstance()
         val myRef = database.collection("Users")

         val newUser = hashMapOf(
             "name" to name,
             "email" to email
         )

         myRef.add(newUser)

     }
 }

fun main() {
    val myObject = MyDataBase()
    val result = myObject.test("maks", "email.com")
}

我试图添加一个主要功能并运行该应用程序

fun main() {
    val myObject = MyDataBase()
    val result = myObject.test("maks", "email.com")
}

【问题讨论】:

  • 这可能需要使用 Android 单元测试来完成,因此您可以有一个主线程 Looper 的替代品。 developer.android.com/training/testing/fundamentals
  • 所以你基本上想知道你是否正在使用这条线db.collection("Students").document("wIPzm1J5zZtVPksa1J8z").set(items) 用户是否实际添加到数据库中?如果这是您需要的,请使用@AlexMamo 回复
  • @AlexMamo 不,我正在尝试在不同的函数 test() 中执行此操作。但它几乎是一样的。所以是的,我想知道用户是否真的添加到我的数据库中。

标签: android firebase kotlin google-cloud-platform google-cloud-firestore


【解决方案1】:

当您使用以下代码行时:

db.collection("Students").document("wIPzm1J5zZtVPksa1J8z").set(items)

这意味着您正在尝试将文档添加到 Firestore。但是,没有任何迹象表明操作是成功还是失败。要知道这一点,您必须附加 success listener 以查看操作何时成功,并附加 failure listener 以查看操作何时因异常而失败。所以在代码中是:

db.collection("Students").document("wIPzm1J5zZtVPksa1J8z").set(items)
    .addOnSuccessListener {
        Log.d(TAG, "You have added the document successfully.")
    }.addOnFailureListener { e ->
        Log.d(TAG, "Failed with: ${e.message}")
    }

【讨论】:

    猜你喜欢
    • 2019-03-27
    • 1970-01-01
    • 2018-11-06
    • 2019-04-24
    • 2017-02-09
    • 1970-01-01
    • 2015-12-31
    • 2016-06-11
    • 2018-01-29
    相关资源
    最近更新 更多