Retrofit data persistence

2019-04-17 03:56发布

问题:

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

        }
    });

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 :(

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

回答1:

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. Add Realm Dependencies to 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. Extends 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. Create Realm Configuration if not exist

if (realmConfiguration == null) {
            realmConfiguration = new RealmConfiguration.Builder(this)
                    .build();
        }
        realm = Realm.getInstance(realmConfiguration);

4. Save parsed Data

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. Query and Inflate data saved by Realm

RealmResults<Post> posts = realm.where(Post.class).findAll();
            mRecyclerView.setAdapter(new PostAdapter(posts, R.layout.activity_main, getApplicationContext()));
        }

Following the above methods help me to solve my problem and I hope this will help to solve your problem too. If you get any problem implementing the solution, you can ask me on comment