经过大量研究,我成功地坚持使用 Retrofit 解析的响应。我使用 Realm 来保存数据以供离线使用。我将描述我实施的方法,这些方法可能有助于其他人遇到此类问题。
1. 将 Realm 依赖添加到 Gradle
应用级 Gradle 文件
`apply plugin: 'realm-android'`
repositories {
maven { url "https://jitpack.io" }
}
classpath "io.realm:realm-gradle-plugin:1.2.0" --> on project level gradle file
2.扩展RealmObject
public class Post extends RealmObject {
@SerializedName("userId")
@Expose
private Integer userId;
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("title")
@Expose
private String title;
@SerializedName("body")
@Expose
private String body;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
3.如果不存在则创建领域配置
if (realmConfiguration == null) {
realmConfiguration = new RealmConfiguration.Builder(this)
.build();
}
realm = Realm.getInstance(realmConfiguration);
4. 保存解析数据
Call<List<Post>> call = apiService.getAllPosts();
call.enqueue(new Callback<List<Post>>() {
@Override
public void onResponse(Call<List<Post>> call, Response<List<Post>> response) {
closeProgress();
if (response.isSuccessful()) {
List<Post> posts = response.body();
mRecyclerView.setAdapter(new PostAdapter(posts, R.layout.activity_main, getApplicationContext()));
for (int i = 0; i < posts.size(); i++) {
realm.beginTransaction();
Post post = realm.createObject(Post.class);
post.setUserId(posts.get(i).getUserId());
post.setId(posts.get(i).getId());
post.setTitle(posts.get(i).getTitle());
post.setBody(posts.get(i).getBody());
realm.commitTransaction();
}
mRecyclerView.setVisibility(View.VISIBLE);
}
}
@Override
public void onFailure(Call<List<Post>> call, Throwable t) {
t.printStackTrace();
}
});
5. Realm 保存的查询和膨胀数据
RealmResults<Post> posts = realm.where(Post.class).findAll();
mRecyclerView.setAdapter(new PostAdapter(posts, R.layout.activity_main, getApplicationContext()));
}
遵循上述方法可以帮助我解决我的问题,我希望这也有助于解决您的问题。如果您在实施解决方案时遇到任何问题,可以在评论中问我