How to store data in room database after fetching from server
Asked Answered
I

1

6

I am using Retrofit2 and Rxjava2 in my android app as a networking library and NodeJS and MongoDB as a backend service.I want to fetch data from server and store data in room database in order to if user open app again it fetches data from room and not from server until some new data is added on server.

So far I have successfully fetched data from server and showing it in recycler view.

What I want to achieve:

1) Store data in room database after fetching from server.

2) Show data from room database until some new data updated on server.

This is my code below:

ApiService.java

public interface ApiService {

@POST("retrofitUsers")
@FormUrlEncoded
Observable<String> saveData(@Field("name") String name,
                             @Field("age") String age);

@GET("getUsers")
Observable<List<BioData>> getData();

}

RetrofitClient.java

public class RetrofitClient {

private static Retrofit retrofit = null;

public static Retrofit getInstance(){

    if(retrofit == null)
        retrofit = new Retrofit.Builder()
                .baseUrl("https://bookbudiapp.herokuapp.com/")
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setLenient().create()))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

    return retrofit;

}

private RetrofitClient(){

}
}

BioData.java

public class BioData {

@SerializedName("name")
@Expose
private String name;

@SerializedName("age")
@Expose
private String age;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getAge() {
    return age;
}

public void setAge(String age) {
    this.age = age;
}
}

MainActivity.java

public class Users extends AppCompatActivity {

RecyclerView recycle;
UserAdapter adapter;
List<BioData> list;
CompositeDisposable compositeDisposable;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    recycle = findViewById(R.id.recycle);
    recycle.setHasFixedSize(true);
    recycle.setLayoutManager(new LinearLayoutManager(this));

    list  = new ArrayList<>();

    compositeDisposable = new CompositeDisposable();

    fetchData();
}

    private void fetchData(){

    Retrofit retrofit  = RetrofitClient.getInstance();
    ApiService myApi = retrofit.create(ApiService.class);

    Disposable disposable = myApi.getData().subscribeOn(Schedulers.io())
                                           .observeOn(AndroidSchedulers.mainThread())
                                           .subscribe(new Consumer<List<BioData>>() {
                                               @Override
                                               public void accept(List<BioData> bioData) throws Exception {

                                                   adapter = new UserAdapter(bioData,getApplicationContext());
                                                   recycle.setAdapter(adapter);
                                               }
                                           });


    compositeDisposable.add(disposable);

}

@Override
protected void onStop() {
    super.onStop();

   compositeDisposable.clear();

  }
}

How can I add Room database in my app let me know I have no idea of it any help would be appreciated.

THANKS

Intenerate answered 4/6, 2019 at 11:22 Comment(2)
Have you taken a look at the official documentation and code samples? developer.android.com/topic/libraries/architecture from there you have access to various samples. Even the Basic Sample (github.com/googlesamples/android-architecture-components/tree/…) talks about this and simulates an artificial delay (networking) before serving results from Room.Christie
check this codelabs.developers.google.com/codelabs/…Hazy
T
1

Android developers has a good start tutorial for Room: https://developer.android.com/training/data-storage/room/index.html

For the functionallity you want to add would be good for you to use Repository Pattern. To keep it simple, the Repository Pattern is like a class between the app and the server where you ask some data (for example user name) and the app doesn't know where that data is coming from (database or server). The repository the will do something like this:

class UserRepository {

  public User getUser() {
     User user = db.userDao().getUser() //Room sintax
      if(user==null){
         //access to server and get user object
         db.userDao().insert(user)
      }
      return db.userDao().getUser()
  }
}

This allows the app to decouple, and if you for example want to change server in a future, you would only have to change repository classes and the rest of the app will be the same. I recommend you to investigate it. You also should use an interface that the repository sould implement, this decouple a bit more

Theseus answered 4/6, 2019 at 11:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.