3

I want to upload data like this:

Image

Edited Questions

//I have ArrayList<FoodModel> arr;
ArrayList<FoodModel> arr = new ArrayList<>();
arr.add(new FoodModel("Hamburger"));
arr.add(new FoodModel("Pizza"));
arr.add(new FoodModel("Chicken"));
//and so on...

I want to upload that ArrayList to firestore it is Possible?

Tony Stark
  • 49
  • 12

1 Answers1

1

You just need add a list field in the hashmap:

Map<String, Object> docData = new HashMap<>();
docData.put("favFoods", Arrays.asList("Hamburger", "Vegetables"));

db.collection("data").document("one")
        .set(docData)
        .addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Log.d(TAG, "DocumentSnapshot successfully written!");
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.w(TAG, "Error writing document", e);
            }
        });

Alternatively, you can also use arrayUnion to add new items to an array.

DocumentReference docRef = db.collection("col").document("docId");
docRef.update("favFoods", FieldValue.arrayUnion("Pizza"));

You can add array of objects (and even nested maps) in Firestore. However, you should add the array as a list.

References:

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
  • Hello, @Dharmaraj I updated my question please check it out. – Tony Stark Aug 25 '21 at 05:23
  • @TonyStark you can add an array of objects... just put that `arr` in the hashmap. iirc you need to convert it to a list as in the documentation. – Dharmaraj Aug 25 '21 at 05:25
  • can you please edit your answer as you say in the comment. – Tony Stark Aug 25 '21 at 05:29
  • Updated the answer . – Dharmaraj Aug 25 '21 at 05:31
  • 1
    if I want to access it how can I do that? – Tony Stark Aug 25 '21 at 07:26
  • @TonyStark please refer to the [documentation](https://firebase.google.com/docs/firestore/query-data/get-data#get_a_document). They have sample function there. If you are facing issues with that, I'd recommend asking a new question a [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) – Dharmaraj Aug 25 '21 at 07:41
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/236383/discussion-between-tony-stark-and-dharmaraj). – Tony Stark Aug 25 '21 at 08:12