I am fetching data from server and saving in room database and then from room showing it in recycler view.Data is perfectly saving in room database and showing in recycler view.
Problem: When I am deleting some data from server database then its old copy that saved earlier still persists in room.
What I want: I don't want to show data deleted from server in recycler view.So how can I update room database based on server response.
This is what I have done so far:
UserDao.java
@Dao
public interface UserDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void Insert(User... users);
@Query("SELECT * FROM Users")
LiveData<List<User>> getRoomUsers();
}
User.java
@Entity(tableName = "Users")
public class User {
@NonNull
@PrimaryKey
private String id;
@ColumnInfo(name = "name")
@SerializedName("name")
@Expose
private String name;
@ColumnInfo(name = "age")
@SerializedName("age")
@Expose
private String age;
public User(String id,String name, String age) {
this.id = id;
this.name = name;
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
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;
}
}
UserRepository.java
public class UserRepository {
private Context context;
private UserDb userDb;
private LiveData<List<User>> listLiveData;
public UserRepository(Context context) {
this.context = context;
userDb = UserDb.getInstance(context);
listLiveData = userDb.userDao().getRoomUsers();
}
public void getUserList(){
Retrofit retrofit = RetrofitClient.getInstance();
ApiService apiService = retrofit.create(ApiService.class);
Call<List<User>> userList = apiService.getUser();
userList.enqueue(new Callback<List<User>>() {
@Override
public void onResponse(Call<List<User>> call, final Response<List<User>> response) {
Completable.fromAction(new Action() {
@Override
public void run() throws Exception {
if(response.body() != null) {
List<User> list = response.body();
for (int i = 0; i < list.size(); i++) {
String id = list.get(i).getId();
String names = list.get(i).getName();
String age = list.get(i).getAge();
User user = new User(id,names,age);
userDb.userDao().Insert(user);
}
}
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new CompletableObserver() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onComplete() {
Toast.makeText(context,"Data inserted",Toast.LENGTH_SHORT).show();
}
@Override
public void onError(Throwable e) {
Toast.makeText(context,e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onFailure(Call<List<User>> call, Throwable t) {
Toast.makeText(context,t.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
public LiveData<List<User>> getRoomUsers(){
return listLiveData;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
UserRepository userRepository;
RecyclerView recyclerView;
UserViewModel userModel;
List<User> userList;
UserAdapter adapter;
ProgressBar prg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
prg = findViewById(R.id.prg);
userRepository = new UserRepository(this);
userModel = ViewModelProviders.of(this).get(UserViewModel.class);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
userList = new ArrayList<>();
adapter = new UserAdapter(userList,this);
recyclerView.setAdapter(adapter);
userModel.getListLiveData().observe(this, new Observer<List<User>>() {
@Override
public void onChanged(List<User> users) {
prg.setVisibility(View.INVISIBLE);
adapter.setUserList(users);
}
});
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this,AddUser.class);
startActivity(i);
}
});
userRepository.getUserList();
}
Someone please let me know how can I get desired result. Any help would be appreciated.
THANKS
you can delete table before insert new data to achieve it use below code :
@Dao
public abstract UserDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
abstract void Insert(User... users);
@Query("SELECT * FROM Users")
abstract LiveData<List<User>> getRoomUsers();
@Insert(onConflict = OnConflictStrategy.IGNORE)
abstract void insert( List<Users> list);
@Query("DELETE FROM Users")
abstract void deleteAll();
@Transaction
void deleteAndInsert(List<Users> list){
deleteAll();
insert(list);
}
}
now you can use userDb.deleteAndInsert(list)
method after
List<User> list = response.body();
to sync data with server .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With