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!

6
  • Possible duplicate of Android Room Database: How to handle Arraylist in an Entity? Commented Mar 29, 2018 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 []" Commented Mar 29, 2018 at 23:54
  • 2
    I don't think that @TypeConverter handles the direct return value from a @Query method. Commented Mar 30, 2018 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. Commented Mar 30, 2018 at 14:09
  • FWIW, I filed an issue to try to add more clarity to the docs on this point. Commented Mar 30, 2018 at 14:15

0

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.