3

I have seen tons of example saving and retrieving ArrayList in Room, Android. But I can't find how to store the classical array [] objects as a field in Room. When I use a type Converter I get the errors:

"Error:(55, 18) error: Not sure how to convert a Cursor to this method's return type" "Error:(61, 38) error: Query method parameters should either be a type that can be converted into a database column or a List / Array that contains such type. You can consider adding a Type Adapter for this."

Here is the code:

Database file:

@Database(entities = {UserModel.class}, version = 4)
@TypeConverters({TutorsModelArrayConverter.class})
public abstract class AppDatabase extends RoomDatabase {
   .... Database methods
}

Model File:

@Entity(primaryKeys = {"user_id"})
public class UserModel {
    private String user_id;  
    private TutorModel[] tutors;
    .... Other parameters

}

Converter file:

public class TutorsModelArrayConverter {

@TypeConverter
public static TutorModel[] toListTutor(String tutorModel) {
    if (tutorModel == null) {
        return null;
    }
    Gson gson = new Gson();
    Type type = new TypeToken<TutorModel[]>() {}.getType();
    return gson.fromJson(tutorModel, type);
}

@TypeConverter
public static String tutorModelToString(TutorModel[] tutorModels) {
    if (tutorModels != null) {
        return new Gson().toJson(tutorModels);
    }else
        return null;
}

}

DAO file:

@Dao
public interface DAO_DBHelper {

    @Query("SELECT tutors FROM AppData WHERE fake_id = 1")
    TutorModel[] getTutorList();

    ... Other methods
}

My question is how can I store an array [] of objects in Room and get around the Errors before mentioned. Any clue is welcome! Thanks in advance!

xyz
  • 524
  • 10
  • 22
  • Possible duplicate of [Android Room Database: How to handle Arraylist in an Entity?](https://stackoverflow.com/questions/44986626/android-room-database-how-to-handle-arraylist-in-an-entity) – Martin Marconcini Mar 29 '18 at 23:46
  • That questions refers to objects in ArrayList, I have tried it myself and it works great. My question is different, I am refering to the classical [] array objects in Java: for example "int []" – xyz Mar 29 '18 at 23:54
  • 2
    I don't think that `@TypeConverter` handles the direct return value from a `@Query` method. – CommonsWare Mar 30 '18 at 11:03
  • Thank you @CommonsWare, I wasn't able to find any explanation regarding limitations of the TypeConverter in the official docs, but you got to be right. I will make it a separte table to get around this issue. – xyz Mar 30 '18 at 14:09
  • FWIW, I filed [an issue](https://issuetracker.google.com/issues/77307836) to try to add more clarity to the docs on this point. – CommonsWare Mar 30 '18 at 14:15
  • That's great, thanks! – xyz Mar 30 '18 at 14:16

0 Answers0