如何从房间数据库中删除回收者视图项

时间:2019-07-29 05:30:18

标签: java android android-room

我正在使用MVVM体系结构模型来创建应用程序。我在MainActivity中具有回收站视图,并且在回收站视图项中单击删除按钮后,应将其从房间数据库中删除。我知道可以在适配器类中将其删除我正在使用要在存储库类中执行删除操作的MVVM模型。

这是我的下面的代码:

UserDao.java

@Dao
public interface UserDao {

@Insert(onConflict = OnConflictStrategy.REPLACE)
void Insert(User... users);

@Query("SELECT * FROM Users")
LiveData<List<User>> getRoomUsers();

@Delete
void Delete(User... user);
}   

UserAdapter.java

public class UserAdapter extends 
RecyclerView.Adapter<UserAdapter.ViewHolder> {

List<User> userList;
Context context;

public UserAdapter(List<User> userList, Context context) {
    this.userList = userList;
    this.context = context;
}

@NonNull
@Override
public UserAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_row_layout,parent,false);

    ViewHolder viewHolder = new ViewHolder(v);

    return viewHolder;
}

@Override
public void onBindViewHolder(@NonNull UserAdapter.ViewHolder holder, int position) {

    final User users = userList.get(position);

    holder.row_name.setText(users.getName());
    holder.row_age.setText(users.getAge());

    holder.delete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {


        }
    });
}

@Override
public int getItemCount() {
    return userList.size();
}

public void setUserList(List<User> userList) {
    this.userList = userList;
    notifyDataSetChanged();
}

public class ViewHolder extends RecyclerView.ViewHolder {

    TextView row_name,row_age;
    ImageView delete;

    public ViewHolder(@NonNull View itemView) {
        super(itemView);

        row_name = itemView.findViewById(R.id.row_name);
        row_age = itemView.findViewById(R.id.row_age);
        delete = itemView.findViewById(R.id.delete);
      }
   }
}

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_LONG).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;
  }
}

UserViewModel.java

public class UserViewModel extends AndroidViewModel {

private UserRepository repo;
private LiveData<List<User>> listLiveData;

public UserViewModel(@NonNull Application application) {
    super(application);

    repo = new UserRepository(application);
    listLiveData = repo.getRoomUsers();

}

public LiveData<List<User>> getListLiveData() {
    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();
 }

请让我知道如何执行删除操作。任何帮助将不胜感激。

谢谢

2 个答案:

答案 0 :(得分:0)

尝试观察具有实时数据的数据库的变化,无论何时执行任何操作(在数据库中添加或删除),在观察者中刷新数据以供回收者视图使用

设置适配器的点击监听器

Rectangle{
    activeFocusOnTab: true
    Control{
       focus: true
    }
}

在适配器类中

public interface OnListInteractionListener {
        // TODO: Update argument type and name
        void onListInteraction(User user);
    }

和视图绑定持有人

private final OnListInteractionListener mListener;

    public UserAdapter(List<User> users, OnListInteractionListener listener,Context context) {

        mListener = listener;
    }

在活动/片段中实现该侦听器,然后您就可以访问Viewmodel并进行回购

答案 1 :(得分:0)

首先,像在UserViewModel中一样,在适配器类中初始化MainActivity,然后调用delete函数。

holder.delete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
             userModel.deleteItem(users);  
        }
    });

UserModel类中添加此功能。

public void deleteItem(User user) = repo.deleteItem(user);

UserRepository类中,调用Delete函数。

public void deleteItem(User user) {
        userDb.userDao().Delete(user);
    }