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();
            }
        }
    });
2
  • Please add your database structure as a screenshot. Commented Aug 27, 2019 at 14:48
  • @AlexMamo added. Commented Aug 27, 2019 at 14:51

2 Answers 2

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:

Sign up to request clarification or add additional context in comments.

11 Comments

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?
Yes, an arrays of hash maps, it's correct. Ok, give it a try and tell me if it works.
Ok. where to mention the patient_case field?
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.
Done @Alex Mamo
|
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,
       };
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.