我正在使用jetpack的Room库,我想将arrayList保存在Room数据库中。
我正在使用typeConverter将arrayList转换为String,但是仍然出现错误。
Error Message : Cannot figure out how to save this field into database. You can consider adding a type converter for it.
这是我的typeConverter。
public class TypeConverterUtils {
@TypeConverter
public static String fromArray(ArrayList<CropData> arrayList) {
return GsonUtils.toGson(arrayList);
}
}
这是我的数据库类。
@TypeConverters({TypeConverterUtils.class})
public abstract class CheruvuDatabase extends RoomDatabase {
private static final String DATABASE_NAME = "Cheruvu.db";
public abstract OtpDAO otpDAO();
public abstract FarmerInfoDAO farmerInfoDAO();
// For Singleton instantiation
private static final Object LOCK = new Object();
private static volatile CheruvuDatabase sInstance;
public static CheruvuDatabase getInstance(Context context) {
if (sInstance == null) {
synchronized (LOCK) {
if (sInstance == null) {
context.getApplicationContext().deleteDatabase(CheruvuDatabase.DATABASE_NAME);
sInstance = Room.databaseBuilder(context.getApplicationContext(), CheruvuDatabase.class, CheruvuDatabase.DATABASE_NAME)
.fallbackToDestructiveMigration()
.allowMainThreadQueries()
.build();
}
}
}
return sInstance;
}
}
我要存储此ArrayList。
private ArrayList cropData = new ArrayList <>();
这是我的CropData类。
public class CropData {
private String cropName;
private Crop crop;
private Float cropAcres;
private Float cropYield;
private Float cropPrice;
public String getCropName() {
return cropName;
}
public void setCropName(String cropName) {
this.cropName = cropName;
}
public Crop getCrop() {
return crop;
}
public void setCrop(Crop crop) {
this.crop = crop;
}
public Float getCropAcres() {
return cropAcres;
}
public void setCropAcres(Float cropAcres) {
this.cropAcres = cropAcres;
}
public Float getCropYield() {
return cropYield;
}
public void setCropYield(Float cropYield) {
this.cropYield = cropYield;
}
public Float getCropPrice() {
return cropPrice;
}
public void setCropPrice(Float cropPrice) {
this.cropPrice = cropPrice;
}
}
答案 0 :(得分:1)
您是否已在ArrayList变量上添加@Embedded?因为您需要嵌入要转换的类。
例如,
ArrayList<CropData> cropData;
和CropData.class不同。所以只需添加
@Embedded
ArrayList<CropData> cropData;
您的问题将得到解决。