如果我的解释不太清楚,我深表歉意,但如果需要,我会添加并编辑这个问题以使其清晰。
我正在开发一个 Android 应用程序,它通过外部 API 接收数据并使用 ORMLite 在本地存储数据。在本地存储数据并使用 ORMLite 之前,我有一些模型从服务器检索 JSON 并通过以下方式解析它:
Gson gson = new Gson();
String result = ApiClient.httpPost("/user_route");
User user = gson.fromJson(result, User.class);
用户类已定义
public class User {
int id;
String name;
ArrayList<Image> media;
}
和图像类:
public class Image {
int id;
int creator_id;
String url;
}
这是模型和方法的简化表示,但我相信我已经保留了所有相关信息。顺便提一句,media
是一个 JSON 对象,其中包含Images
.
现在我也尝试将数据存储在本地。为了使用 ORMLite 建立用户和图像之间的关系,您似乎必须使用foreignCollection类和@ForeignCollectionField注释。我不相信Gson可以直接解析Jsonmedia
User 类中的字段作为ForeignCollection 对象,所以我认为我需要创建两个字段mediaCollection
and media
.
使用 ORMLite,User 类现在如下所示:
@DatabaseTable(tableName = "Users")
public class User {
@DatabaseField(generatedId = true)
int id;
@DatabaseField
String name;
@ForeignCollectionField
ForeignCollection<Image> mediaCollection;
ArrayList<Image> media;
}
ORMLite 的 Image 类如下所示:
@DatabaseTable(tableName = "Images")
public class Image {
@DatabaseField(generatedId = true)
int id;
@DatabaseField(foreign=true, foreignAutoCreate=true, foreignAutoRefresh=true)
private User user;
@DatabaseField
int creator_id;
@DatabaseField
String url;
}
应用程序的流程是如何工作的,首先我访问用户的本地数据库。我执行一些逻辑,然后确定是否需要实际访问服务器来“更新”或“刷新”用户数据。
无论数据来自本地还是来自远程服务器,我都需要显示Image
在同样的观点下。就目前而言,该 URL 为Image
根据数据是本地的还是远程的,存储在不同类型的对象中。我想做的是如果Image
存储在一个ForeginCollection
对象,将该对象转换为ArrayList
然后继续我的代码的其余部分,提取Image
URL 并显示它。
我想有两个问题。
这是一个好的计划还是我应该编写两种完全独立的方法来提取Image
来自数据的 URL,而不是从中转换对象ForeignCollection
to ArrayList
?
If it is一个好的计划,我该如何转换ForeginCollection
to an ArrayList
?