简体   繁体   中英

How to add data to the firebase firestore by generating different document id after hitting submit button again and again? Android Kotlin

I am trying to push the form data to the firebase-firestore. And I also did it successfully. But, the problem is that whenever I am trying to submit the form data again and again it just updates the last data with the current data.

Actually, my requirement is that whenever the user hit the submit button. It creates a document with a random id and stores the all data into that specific id that is generated.

在此处输入图像描述 在此处输入图像描述

You are specifying the document ID in .document() so it'll overwrite the same document. If you want a document with a random ID on every click, try using add() instead as shown below:

val collectionRef =  FirebaseFirestore.getInstance().collection("Maintainance")

collectionRef.add(user).addOnCompleteListener(...)

Alternatively, you can leave .document() empty to get a DocumentReference with a random ID:

val userDocument = FirebaseFirestore.getInstance().collection("Maintanance").document() // <-- don't pass an ID

In addition to @Dharmaraj answer:

CASE_1: In a case where you need to track each user's all submitted forms, probably from your explanation you may need to organize each user's form. Therefore if you need to organize each user's form then create another sub-collection [example: document( userId ).collection(" USER_FORMS ")] within userID document like this:

    val documentRef =  FirebaseFirestore.getInstance().collection("Maintainance").document(UserUtils.user?.id.toString()).collection("USER_FROMS").document();

CASE_2: In a case where you need to make your own custom document ID:

1- make a random number or string or any other data type.

2- The random number/string variable must be local to the code block/method that will execute the form submision function.

3- use the number/string generated as the form document Id like this:

    //This must be local so as user clicks submision button so as it generates new random number;
val randomFormId = "generateThenumberOrStringAndInitializeTheVariable";

Then use the random number as the form document Id like this:

    val documentRef =  FirebaseFirestore.getInstance().collection("Maintainance").document(UserUtils.user?.id.toString()).collection("USER_FROMS").document(randomFormId);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM