改进数据持久性

时间:2017-03-16 04:46:30

标签: android retrofit2 activeandroid sugarorm datapersistance

如何使用Retrofit库保留从服务器解析的数据。这样用户就可以在没有互联网连接的情况下查看它。

    final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.post_recycler_view);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    ApiInterface apiService =
            ApiClient.getClient().create(ApiInterface.class);

    Call<ArrayList<Post>> call = apiService.getAllPosts();
    call.enqueue(new Callback<ArrayList<Post>>() {
        @Override
        public void onResponse(Call<ArrayList<Post>> call, Response<ArrayList<Post>> response) {
            int statusCode = response.code();
            List<Post> posts = response.body();
            recyclerView.setAdapter(new PostListAdapter(posts, R.layout.activity_main, getApplicationContext()));

        }

        @Override
        public void onFailure(Call<ArrayList<Post>> call, Throwable t) {
            Log.e(TAG, t.toString());

        }
    });

我想保存响应,持久化并将数据显示到RecyclerView中。 我将不胜感激使用ORM保存,我尝试使用Sugar ORM和ActiveAndroid,但我无法成功:(

当我延长SugarRecord或Model App终止时,log cat

没有任何错误

1 个答案:

答案 0 :(得分:0)

经过大量的研究,我成功地坚持使用Retrofit解析的响应。我使用Realm来保存数据以供离线使用。我将描述我实施的方法,这可能有助于其他人遇到这类问题。

<强> 1。将领域依赖项添加到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()));
        }

按照上述方法帮助我解决问题,希望这也有助于解决您的问题。如果您在实施解决方案时遇到任何问题,可以向我发表评论