简体   繁体   中英

How to store array in firestore database using Android?

I want to create an firestore model like below:

attendance_log (root collection)
|
|--- 001 (document ID)
|    |
|    |--- date : 20190310
|    |--- time : 1025
|    |--- subject : "Android Programming"
|    |--- present : {"MCA01", "MCA03", "MCA04"}
|    |--- absent : {"MCA02, "MCA05"}

I could store date, time and subject by passing the value in a Map as below :

Map<String, Object> attend = new HashMap<>();
attend.put("date", d) ;
attend.put("time", t) ;
attend.put("subject", subject) ;

db.collection("attendance_log")
    .document(docID)
    .set(attend)
    .addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid){
            Toast.makeText(TakeAttendance.this,"Attendance added sucessfully" , Toast.LENGTH_LONG).show();
        }
    }).addOnFailureListener(new OnFailureListener() {

    @Override
    public void onFailure(@NonNull Exception e) {
        Snackbar.make(findViewById(R.id.cdlayout) ,"Something went wrong!", Snackbar.LENGTH_LONG).show();
    }
});

But passing the array generates the error

java.lang.IllegalArgumentException: Could not serialize object. Serializing Arrays is not supported, please use Lists instead

The solution is in your error - you need to read your error and check what does it say - in your case, you will see that Arrays are not supported and you need to send list instead.


You can use Arrays.asList(yourArray) to convert your array and send it to your database.

Change this line:

attend.put("subject", subject) ;

To This line:

attend.put("subject", Arrays.asList(subject)) ;

No need to worry you are very near to the correct code. In firestore you can store array String[] instead you have to use List:

     //convert array to arraylist
      ArrayList<String> subjectsArrayList = getListOfSubjects(subjects);
      Map<String, Object> attend = new HashMap<>();
      attend.put("date", d) ;
      attend.put("time", t) ;
      attend.put("subject", subject) ;

      hashMap.put("subjects", subjectsArrayList);
      db.collection("attendance_log")
                .document(docId)
                .update(attend)
                .addOnCompleteListener(task -> {
                    //done
                });

Here is getListOfSubjects method

  public ArrayList<String> getListOfSubjects(String[] subjects){
        List<String> subjectsArrayList = new ArrayList<>();
        for (int i = 0; i < subjects.length; i++) {
            subjectsArrayList.add(subjects[i]);
        }
        return (ArrayList<String>) subjectsArrayList;
    }

Hope this will help you.

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