0

enter image description here

I want to add data to the existing array without overwriting. And inside each document, I have an array of HashMap. I am trying to add data to the existing one. Kindly check the below code and shed some light.

   public void createNewCase(){
     Map<String, String> caseInfo = new HashMap<String, String>();


    caseInfo.put("chief_complaint", chiefComplaintET.getText().toString());
        caseInfo.put("facility", facilityET.getText().toString());
        caseInfo.put("location", locationET.getText().toString());
        caseInfo.put("assigned_provider", assignProviderET.getText().toString());
        caseInfo.put("referring_provider", referringProviderET.getText().toString());
        caseInfo.put("admit_date", adminDateET.getText().toString());
        caseDictionary.add(caseInfo);
        final String patientID = sharedPrefHelper.getStr("patient_id");



        db.collection("patients").whereEqualTo("patient_id", patientID).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            private static final String TAG = "New Case Creation" ;

            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    List<HashMap<String,String>> list = new ArrayList<>();
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        patient patient = new patient();
                        list = (List) document.get("patient_case");
                        for (HashMap<String, String> item:list) {
                            caseDictionary.add(item);
                        }
                    }
                    System.out.println(caseDictionary);
                    HashMap<String, Object> uploadData = new HashMap<>();
                    uploadData.put("patient_case", caseDictionary);
                    DocumentReference caseRef = db.collection("patients").document(patientID); // am stuck here

                }else{
                    Log.w(TAG, "Error getting documents.", task.getException());
                    Toast.makeText(NewCase.this, "Something bad happened", Toast.LENGTH_SHORT).show();
                    Helper.m_Dialog.hide();
                }

            }
        });

}

Edit 1 Below code deleting old data and adding new data. I need to append.

   final String patientID = sharedPrefHelper.getStr("patient_id");
        final CollectionReference collectionReference = db.collection("patients");
    collectionReference.whereEqualTo("patient_id", patientID).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            Toast.makeText(NewCase.this, task.getResult().toString(), Toast.LENGTH_SHORT).show();
            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot document : task.getResult()) {

                    Map<Object, Object> map = new HashMap<>();
                    map.put("patient_case", caseInfo);

                    collectionReference.document(document.getId()).set(map, SetOptions.merge());
                }
            }else{
                Toast.makeText(NewCase.this, task.getResult().toString(), Toast.LENGTH_SHORT).show();
            }
        }
    });
Mac_Play
  • 302
  • 4
  • 21

2 Answers2

1

As I see in your screenshot, in your patients collection you have documents that contain an array that holds maps (objects). In order to be able to update those maps that exist within your array you should create a Map object that corresponde to your exact document structure and use DocumentReference's set(Object data, SetOptions options) method for that. So pass as the first argument the map and as the second argument SetOptions.merge(). You can find a simpler example in my answer from the following post:

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • I was on vacation. I am going to try today and will update you. For more clarity, let me tell you my scenario again, am having an array of hash maps, every time when I add data, it should append to array of hash maps. Can you please edit my code? – Mac_Play Sep 16 '19 at 12:21
  • Yes, an arrays of hash maps, it's correct. Ok, give it a try and tell me if it works. – Alex Mamo Sep 16 '19 at 12:26
  • Ok. where to mention the patient_case field? – Mac_Play Sep 16 '19 at 13:19
  • If you started to make your own attempt for solving this issue using the information provided in my answer, please consider ask another question if something else comes up. I cannot guide at every step in your development. – Alex Mamo Sep 16 '19 at 13:29
  • dude it's a same question. you have used document.getId() in your example, in my case I need to append data to the particular field. Your example doesn't show that. – Mac_Play Sep 16 '19 at 13:36
  • Hi Alex. I can able to add data, but it's not appending. It's deleting the existing maps in the array and adding the new map. I have edited the code. – Mac_Play Sep 17 '19 at 13:36
  • @Mac_Play Call `set()` and pass as the first argument the map and as the second argument `SetOptions.merge()`, so you can update the document and not overwrite it, right? Do it this way and tell me if it works. – Alex Mamo Sep 17 '19 at 13:41
  • I have edited the original question by adding new code. I have done the same way as you mentioned in the last text. But it's not appending, For example I have two maps in array already, when I add new data, it's removing the existing two data and adding the new data. – Mac_Play Sep 17 '19 at 13:44
  • You provided incomplete data. I cannot see any `patient_id` property in your database. Beside that, you aren't following recommenedations in my answer at all. You map doesn't have the same structure as your document. The `patient_case` property is actually a list of maps. If it would be easy for you, get the entire document, get the list of maps, add/remove data and write the document back. – Alex Mamo Sep 17 '19 at 13:51
  • @Mac_Play That's why I have asked you earlier, to make your own attempt and if you find hard times in solving it, post another fresh question using an [MCVE](https://stackoverflow.com/help/mcve) so me or other Firebase developers can help you. – Alex Mamo Sep 17 '19 at 13:52
  • 1
    Done @Alex Mamo – Mac_Play Dec 28 '20 at 12:26
0
  • This is one of my example

  • i have done it like this

     List<Map> history = List();  
    
     History historyObj = History(typee, name, timeStamp, pointsBefore, points, itemPoints);  
    
     history.add(historyObj.toMap());  
    
     //Firesore collection object  
    
     CollectionReference child = _firestore.collection('children');  
    
     //Firesore document object  
    
     DocumentReference docRef = child.doc(selectedChild.childId);  
    
     // "history" is your "patient_case"  
    
     docRef.update({"history": FieldValue.arrayUnion(history)}).then(
         (value) => print("Update done"));  
    
  • History is one of my class

  • History class includes method toMap() which converts all history class variables and its values to 'Key' : 'value' form like this

    Map<String, dynamic> toMap() => {  
         "type": type,
         "name": name,
         "timestamp": timestamp,
         "points_before": points_before,
         "points_after": points_after,
         "points_affected": points_affected,
       };