TransWikia.com

How to store list of model class objects in firestore?

Stack Overflow Asked by Ahsan Farooq on January 31, 2021

I have previously used firebase realtime database in which I simply stored list of objects in database. How to store arraylist of model class objects in firestore database?

One Answer

Make the model class objects one by one and add in a ArrayList as shown below:

City city1 = new City("Los Angeles", "CA", "USA",
    false, 5000000L, Arrays.asList("west_coast", "sorcal"));
City city2 = new City("Los Angeles", "CA", "USA",
        false, 5000000L, Arrays.asList("west_coast", "sorcal"));
City city3 = new City("Los Angeles", "CA", "USA",
        false, 5000000L, Arrays.asList("west_coast", "sorcal"));
ArrayList<City> list = new ArrayList<City>();
list.add(city1);
list.add(city2);
list.add(city3);

db.collection("cities").document("LA").set(list)
    .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);
        }
    });

Or You can also try below method

City city1 = new City("Los Angeles", "CA", "USA",
    false, 5000000L, Arrays.asList("west_coast", "sorcal"));
City city2 = new City("Los Angeles", "CA", "USA",
        false, 5000000L, Arrays.asList("west_coast", "sorcal"));
City city3 = new City("Los Angeles", "CA", "USA",
        false, 5000000L, Arrays.asList("west_coast", "sorcal"));
ArrayList<City> list = new ArrayList<City>();

list.add(city1);
list.add(city2);
list.add(city3);
Map<String, Object> docData = new HashMap<>();
docData.put("modalExample", list);
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);
            }
        });

Answered by Nadeem Shaikh on January 31, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP