改造数据持久性 [英] Retrofit data persistence

查看:122
本文介绍了改造数据持久性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I persist the data that has been parsed from the server using Retrofit library. So that users can view it when there is no internet connection.

    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,但在此方面我无法成功:(

I want to save response, persist and show data into RecyclerView. Help to save using ORM will be appreciated, I try to use Sugar ORM and ActiveAndroid but I can not succeed on that :(

当我扩展SugarRecord或

When I extend SugarRecord or Model App terminate without any error on log cat

推荐答案

在经过大量研究后,我成功保留了使用Retrofit解析的响应。

After copious research, I succeed to persist the response parsed using Retrofit. I have used Realm to persist the data for offline use. I will describe the methods I had implemented which may help other to encounter this type of problems.

1。添加域,使用Realm保留数据以供脱机使用,我将描述我已经实现的方法,这些方法可能会帮助其他人遇到这类问题。领域对Gradle的依赖性

应用级Gradle文件

App-level Gradle file

`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()));
        }

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

这篇关于改造数据持久性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆