问题
I am not sure what is the fuss about Room as I find it very crappy. Almost nothing works as expected. To my issue I want to test the type converter thingy they have (so far disappointed). To test it I made a simple class from an example I saw online. I am sure it is something stupid not even related to the code but I will give it a try here anyway. So far I have:
@Entity
public class User {
@PrimaryKey
private int id;
private String name;
@TypeConverters(Converters.class)
List<String> pets = new ArrayList<>();
public User() { }
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getPets() {
return pets;
}
public void setPets(List<String> pets) {
this.pets = pets;
}
}
Then the converter:
public class Converters {
@TypeConverter
public static ArrayList<String> fromString(String value) {
Type listType = new TypeToken<ArrayList<String>>() {}.getType();
return new Gson().fromJson(value, listType);
}
@TypeConverter
public static String fromArrayList(ArrayList<String> list) {
Gson gson = new Gson();
String json = gson.toJson(list);
return json;
}
}
A simple dao:
@Dao
public interface UserDao {
@Insert(onConflict = REPLACE)
void insertUser(User user);
@Query("SELECT * FROM User")
List<User> getUsers();
}
And finally the db:
@Database(entities = { User.class,}, version = 1, exportSchema = false)
@TypeConverters({Converters.class})
public abstract class RoomDb extends RoomDatabase {
public abstract UserDao userDao();
}
And still I get "Cannot figure out how to save this field into database. You can consider adding a type converter for it" shit. No details why the converter is not working or what's so ever. To save the trouble I already tried to use the @Converters on the field it self like the alternative solution suggests.
Room has left me with disappointment so far for complicated problems, and I find Realm and ObjectBox to be more consistent when your model is fairly complicated.
Feel free to join the struggle with your insight.
回答1:
Instead of ArrayList in the Converters class. Try List. Your entity is using List as its declared class. There might be a problem with that.
That was the solution as suggested from Knossos above. I ended up testing it with ArrayList and worked.
回答2:
class Convertes {
@TypeConverter
fun fromSource(source: Source) :String{
return source.name
}
@TypeConverter
fun tvSource(name: String): Source {
return Source( name,name)
}
}
来源:https://stackoverflow.com/questions/53085704/room-typeconverter