0

我是android的新手,所以提前抱歉,我很喜欢在将数据发送到firebase数据库之前使用用户的输入并翻译它,我认为我对变量做错了,因为在循环中我可以得到语言文本“en”,但在它的 null 之后,所以翻译无法开始..

     println("SAVING DATABASE")

    var theLangue:String? = null
    var detect:String? = null

    val languageIdentifier = LanguageIdentification.getClient()
    languageIdentifier.identifyPossibleLanguages(userText)
        .addOnSuccessListener { identifiedLanguages ->

            for (identifedLanguage in identifiedLanguages) {

                detect = identifedLanguage.languageTag
                val confidence = identifedLanguage.confidence
                println(" LANGUAGE DETECTED: $detect , LANGUAGE CONFIDENCE: $confidence")

            }
            theLangue = detect

        }.addOnFailureListener {

        println("problem cant translate!")
    }



    println("Translate pre build ${theLangue.toString()} ++ $theLangue")   //todo NULL
    val options = TranslatorOptions.Builder()
        .setSourceLanguage(theLangue.toString()) // todo NULL
        .setTargetLanguage(Locale.getDefault().displayLanguage)
        .build()

    val theTranslator = Translation.getClient(options)
    val conditions = DownloadConditions.Builder()
        .requireWifi()
        .build()
    theTranslator.downloadModelIfNeeded(conditions)
        .addOnSuccessListener {
            println("succes downloading models languages.. going to translate wait..")
            theTranslator.translate(userText)
                .addOnSuccessListener {
                    // Translation successful.
                    println("Succes translated text")
                }
                .addOnFailureListener { exception ->
                    // Error.
                    // ...
                    println("there is a problem failed to transalte !")
                }
        }
        .addOnFailureListener { exception ->
            // Model couldn’t be downloaded or other internal error.
            // ...
            println(exception.message)
            println(exception.localizedMessage)
            println("cant download languages models !")
        }
4

1 回答 1

0

.addOnSuccessListener是一个异步调用,可能不会立即执行。

一个快速的解决方法是将翻译逻辑移动到addOnSuccessListener语言识别中的回调中。

` ... languageIdentifier.identifyPossibleLanguages(userText) .addOnSuccessListener {identifiedLanguages ->

        for (identifedLanguage in identifiedLanguages) {

            detect = identifedLanguage.languageTag
            val confidence = identifedLanguage.confidence
            println(" LANGUAGE DETECTED: $detect , LANGUAGE CONFIDENCE: $confidence")

        }
        theLangue = detect


      val options = TranslatorOptions.Builder()
        .setSourceLanguage(theLangue.toString()) // todo NULL
        .setTargetLanguage(Locale.getDefault().displayLanguage)
        .build()
      
      val theTranslator = Translation.getClient(options)
      ...

    }.addOnFailureListener {

    println("problem cant translate!")
}
...

`

为了提高代码的可读性,您可以使用continueWithTask

于 2020-06-26T20:26:03.150 回答