gpt4 book ai didi

java - Android Sugar ORM - 带列表的类模型

转载 作者:搜寻专家 更新时间:2023-11-01 08:29:45 24 4
gpt4 key购买 nike

我正在尝试将我的 android 项目与 SQLite 数据库集成,但我对这个数据库很陌生,所以我使用 Sugar ORM帮助我处理项目的数据库方面的问题。

问题是我的类模型之一包含列表:

public class MyObject extends SugarRecord implements Parcelable {

public String myString;
public List<String> myStringList;

public MyObject () { }

private MyObject (Parcel in) {
myString= in.readString();
myStringList= new ArrayList<>();
in.readList(myStringList, String.class.getClassLoader());
}

public static final Creator<MyObject> CREATOR = new Creator<MyObject>() {
public MyObjectcreateFromParcel(Parcel in) { return new MyObject(in); }
public MyObject[] newArray(int size) { return new MyObject[size]; }
};

@Override
public int describeContents() { return 0; }

@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(myString);
dest.writeList(myStringList);
}
}

当我尝试读取我的数据库时出现此错误:

Class cannot be read from Sqlite3 database. Please check the type of field myStringList(java.util.List)

我想在我的数据库中创建列的方式不支持列表。有什么解决方法吗?我应该如何处理这个问题?

最佳答案

SugarORM 不支持存储ArrayLists您可以使用一些策略来支持这一点,但需要您引入依赖项。

基本思想是将数据列表转换为JSON,然后将其存储为String

import com.google.gson.Gson;

public class MyObject extends SugarRecord implements Parcelable {
public String myString;
@Ignore //Sugar will ignore this field.
private List<String> myStringList; //Change to private (accessed via getter/setter method)
private String myStringListStore; //to store the list in JSON format.

public MyObject () { }

private MyObject (Parcel in) {
this.myString= in.readString();
this.myStringList= new ArrayList<>();
in.readList(myStringList, String.class.getClassLoader());
}

public static final Creator<MyObject> CREATOR = new Creator<MyObject>(){
public MyObjectcreateFromParcel(Parcel in) { return new MyObject(in); }
public MyObject[] newArray(int size) { return new MyObject[size]; }
};

public List<String> getMyStringList(){
//Convert from JSON string to List
myStringList = new Gson().fromJson(this.myStringListStore,new TypeToken<List<String>>(){}.getType());
return myStringList;
}

public setMyStringList(List<String> stringList){
this.myStringList = stringList;
}

//Override save to ensure the list is converted into JSON before saving.
@Override
public long save(){
this.myStringListStore = new Gson().toJson(stringList);
return super.save();
}

@Override
public int describeContents() { return 0; }

@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(myString);
dest.writeList(getMyStringList());
}
}

关于java - Android Sugar ORM - 带列表的类模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41811866/

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