提问者:小点点

即使从服务器删除后,数据仍显示在房间数据库中


我正在从服务器获取数据并保存在房间数据库中,然后从房间显示在回收器中view.Data完美地保存在房间数据库中并显示在回收器视图中。

问题:当我从服务器数据库中删除一些数据时,它之前保存的旧副本仍然存在于房间中。

我想要的:我不想显示从服务器删除的数据在回收view.So如何根据服务器响应更新房间数据库。

这是我到目前为止所做的:

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

请告诉我如何才能得到想要的结果。任何帮助都将不胜感激。

谢谢


共1个答案

匿名用户

您可以在插入新数据之前删除表以实现它使用以下代码:

@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);
 }

}

现在您可以在List之后使用userDb. deleteAndInject(list)方法