簡體   English   中英

錯誤“必需:找到字符串:字符串?” Kotlin和Android Studio

[英]Error “Required:String Found:String?” Kotlin and Android Studio

如標題所示,我在“ var myNote = Note(id,title,note,ServerValue.TIMESTAMP)”行的“ id”下獲得紅色下划線。錯誤“ Required:String Found:String?” Kotlin和Android Studio

class MainActivity : AppCompatActivity() {
    var mRef:DatabaseReference? = null

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

        val database = FirebaseDatabase.getInstance()
        mRef = database.getReference("Notes")

        add_new_note.setOnClickListener {
            showDialogAddNote()
        }
    }

    fun showDialogAddNote() {
        val alertBuilder = AlertDialog.Builder(this)

        val view = layoutInflater.inflate(R.layout.add_note, null)

        alertBuilder.setView(view)

        val alertDialog = alertBuilder.create()
        alertDialog.show()

        view.btnSaveNote.setOnClickListener {
            val title = view.etTitle.text.toString()
            val note = view.etNote.text.toString()

            if (title.isNotEmpty() && note.isNotEmpty()) {
                var id = mRef!!.push().key

                var myNote = Note(id, title, note, ServerValue.TIMESTAMP)
                mRef!!.child(id).setValue(myNote)
                alertDialog.dismiss()    
            } else {
                Toast.makeText(this, "Empty", Toast.LENGTH_LONG).show()
            }
        }
    }
}

這是我的Notes.kt類

package com.example.gearoidodonovan.books

import java.util.*

class Note (var id:String, var title:String, var note:String, var timestamp: MutableMap<String, String>) {
}

Kotlin迫使您對可空性保持高度的意識。

您的Note實體說它需要一個不可為空的id:String ,並且顯然, mRef!!.push().key返回一個String? 表示它是一個可為空的字符串。 您可以通過雙擊它來解決它,即mReff!!.push().key!!

另一個提示是要ALT+ENTER這些與Kotlin相關的錯誤,它將為您提供雙重提示。

您在Note id屬性被聲明為非null String ,而您擁有的鍵可能是null String? 您需要彌合這一差距。

  1. 最簡單但最危險的方法就是使用!! ,如果key為null,即會產生異常,即

     var id = mRef!!.push().key!! 
  2. 更好的方法是以某種方式處理空值情況,例如通過執行空值檢查:

     var id = mRef!!.push().key if (id != null) { var myNote = Note(id, title, note, ServerValue.TIMESTAMP) mRef!!.child(id).setValue(myNote) alertDialog.dismiss() } else { // handle the case where key is null somehow } 
  3. 您還可以將自己的類中的屬性設置為可空,並在以后處理ID值(可能為null):

     class Note (var id: String?, var title: String, var note: String, var timestamp: MutableMap<String, String>) 

注意所有的mRef!! 通話也是有問題的。 例如,在Kotlin中通常不鼓勵使用匈牙利符號( m前綴),而!! 操作員也是危險的。 您最好盡早處理該引用的空值,然后您可以更方便地使用它,而不必在代碼中加!!

我也鼓勵您通讀正式文檔此答案中的 null安全性。

您可以使用:

@Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM