gpt4 book ai didi

Android 房间持久库 - 错误 : Cannot figure out how to save field to database"的 TypeConverter 错误

转载 作者:IT老高 更新时间:2023-10-28 22:05:50 27 4
gpt4 key购买 nike

由于错误,我无法在房间中创建 typeConverter。我似乎遵循文档中的所有内容。我想将列表转换为 json 字符串。让我们看看我的实体:

      @Entity(tableName = TABLE_NAME)
public class CountryModel {

public static final String TABLE_NAME = "Countries";

@PrimaryKey
private int idCountry;
/* I WANT TO CONVERT THIS LIST TO A JSON STRING */
private List<CountryLang> countryLang = null;

public int getIdCountry() {
return idCountry;
}

public void setIdCountry(int idCountry) {
this.idCountry = idCountry;
}

public String getIsoCode() {
return isoCode;
}

public void setIsoCode(String isoCode) {
this.isoCode = isoCode;
}

public List<CountryLang> getCountryLang() {
return countryLang;
}

public void setCountryLang(List<CountryLang> countryLang) {
this.countryLang = countryLang;
}

}

country_lang 是我想转换为字符串 json 的内容。所以我创建了以下转换器:转换器.java:

public class Converters {

@TypeConverter
public static String countryLangToJson(List<CountryLang> list) {

if(list == null)
return null;

CountryLang lang = list.get(0);

return list.isEmpty() ? null : new Gson().toJson(lang);
}}

那么问题出在我放置@TypeConverters({Converters.class}) 的任何地方,我一直收到错误消息。但正式这是我放置注释以注册 typeConverter 的地方:

@Database(entities = {CountryModel.class}, version = 1 ,exportSchema = false)
@TypeConverters({Converters.class})
public abstract class MYDatabase extends RoomDatabase {
public abstract CountriesDao countriesDao();
}

我得到的错误是:

Error:(58, 31) error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.

最佳答案

这是我在 Room 发布后遇到的常见问题。 Room 不支持直接存储列表的能力,也不支持与列表相互转换的能力。支持POJO的转换和存储。

在这种情况下,解决方案很简单。而不是存储 List<CountryLang>你想存储CountryLangs (注意's')

我在这里做了一个简单的解决方案示例:

public class CountryLangs {
private List<String> countryLangs;

public CountryLangs(List<String> countryLangs) {
this.countryLangs = countryLangs;
}

public List<String> getCountryLangs() {
return countryLangs;
}

public void setCountryLangs(List<String> countryLangs) {
this.countryLangs = countryLangs;
}
}

这个 POJO 是你之前的对象的反转。它是一个存储语言列表的对象。而不是存储您的语言的对象列表。

public class LanguageConverter {
@TypeConverter
public CountryLangs storedStringToLanguages(String value) {
List<String> langs = Arrays.asList(value.split("\\s*,\\s*"));
return new CountryLangs(langs);
}

@TypeConverter
public String languagesToStoredString(CountryLangs cl) {
String value = "";

for (String lang :cl.getCountryLangs())
value += lang + ",";

return value;
}
}

此转换器获取字符串列表并将它们转换为逗号分隔的字符串以存储在单个列中。当它从 SQLite 数据库中获取字符串以转换回来时,它会用逗号分割列表,并填充 CountryLangs。

确保在进行这些更改后更新您的 RoomDatabase 版本。您的其余配置正确。与您余下的 Room 持久性工作一起愉快地狩猎。

关于Android 房间持久库 - 错误 : Cannot figure out how to save field to database"的 TypeConverter 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44582397/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com