簡體   English   中英

無法將 Firebase 文檔 ID 添加到 dataClass

[英]Can't add Firebase document Id to dataClass

我有一個來自用戶條目的數據的數據類。 它正在將此數據傳輸到 Firebase。 該數據類還包括默認為空字符串的 documentId 變量。 我想添加 Firebase 自動創建的文檔 ID。 我嘗試了所有我能想到的方法。 但它以任何方式采用默認值。

以下是有關此問題的四個代碼片段。 數據類,添加數據活動,檢索數據活動及其視圖模型。

數據類:

data class AnalyzeModel(
var concept: String?="",
var reason: String?="",
var result: String?="",
var rrRatio: Double?=0.0,
var tarih: Timestamp=Timestamp.now(),
var tradingViewUrl: String="",
var id : String="")

AddAnalyzeActivity、addData 函數:

    fun addData(view: View) {

    val tarih = com.google.firebase.Timestamp.now()
    val rr = rrText.text.toString()
    var doubleRR = rr.toDoubleOrNull()
    if (doubleRR == null) { doubleRR = 0.0 }

    val analyzeDTO = AnalyzeModel(
        conceptText.text.toString(),
        reasonForText.text.toString(),
        resultAddingText.text.toString(),
        doubleRR,
        tarih,
        chartImage.text.toString()
    )
    viewModel.save(analyzeDTO)

    val intent = Intent(this, PairDetailActivity::class.java)
    startActivity(intent)
    finish()
}

AddAnalyze ViewModel,保存功能:

    fun save(data: AnalyzeModel) {

    database.collection(dbCollection!!).document("Specified").collection("Pairs")
        .document(chosenPair!!)
        .collection("Analysis")
        .add(data)
        .addOnFailureListener { exception ->
            exception.printStackTrace()
            Toast.makeText(getApplication(), exception.localizedMessage, Toast.LENGTH_LONG).show()
        }
}

PairViewModel、retrieveData 函數:

    private fun retrieveData() {

    val docRef = collectionRef.orderBy("tarih", Query.Direction.DESCENDING)
    docRef.addSnapshotListener { value, error ->
        try {
            if (value != null && !value.isEmpty) {
                val allAnalysis= ArrayList<AnalyzeModel>()
                val documents = value.documents
                documents.forEach {
                    val analyze = it.toObject(AnalyzeModel::class.java)
                    if (analyze!=null){

                        allAnalysis.add(analyze)
                    }
                }

                list.value = allAnalysis
            } else if (error != null) {
                Toast.makeText(Application(), error.localizedMessage, Toast.LENGTH_LONG).show()
            }
        } catch (e: Exception) {
            e.printStackTrace()
          }
    }
}

我想添加 Firebase 自動創建的文檔 ID。

要解決這個問題,您只需要使用@DocumentId注釋該字段。

data class AnalyzeModel(
    var concept: String?="",
    var reason: String?="",
    var result: String?="",
    var rrRatio: Double?=0.0,
    var tarih: Timestamp=Timestamp.now(),
    var tradingViewUrl: String="",
    @DocumentId 👈
    var id : String=""
)

還要確保擁有最新版本的 Firestore。

暫無
暫無

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

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