Sevban Bayır
Sevban Bayır

Reputation: 736

Adding document İD to firebase document as a field

I have a model with default values. My app gets the data from user through EditTexts and add them to Firebase Firestore. I hava an addData function (in AddAnalyzeActivity) and savefunction (in AddAnalyzeViewModel) for this operation. I'm getting EditText entries in AddAnalyzeActivity and adding them to my model but on this step ı want to add document id to my model but I can't access the documentIds properly in AddAnalyzeActivity. I can only access them with a forEach method when I try to retrieving the mentioned data with retrieveData function (in PairDetailVM) from Firestore but If I try to add document Ids in retrieveData method it only adds default value of documentId.

What I tried to:

  1. Using @DocumentId annotation in my model.

  2. Setting null default value of documentId in my model.

  3. Getting a list of all documents' ids but can't match them with actual items.

Here is the screenShot for logic:

enter image description here

AnalyzeModel:

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="")

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()
}

save :

    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()
        }
}

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()
          }
    }
}

Upvotes: 0

Views: 1435

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600116

If you want to save the document ID into the document itself, consider separating the creation of the new DocumentReference from writing to it, by using set instead of add.

fun save(data: AnalyzeModel) {

    val newRef = database.collection(dbCollection!!).document("Specified").collection("Pairs")
        .document(chosenPair!!)
        .collection("Analysis")
        .document()     // 👈 generates a new reference with a unique ID

    data.id = newRef.id // 👈 set the ID into your object

    newRef.set(data)    // 👈 writes the data to the new reference
        .addOnFailureListener { exception ->
            exception.printStackTrace()
            Toast.makeText(getApplication(), exception.localizedMessage, Toast.LENGTH_LONG).show()
        }
}

Also see the second snippet in the documentation on adding a document

Upvotes: 2

Related Questions