我在google codelabs教程之后使用LiveData
和Room
创建了一个数据库。
问题是我无法删除onClick
条目。
这是我的 Dao
@Dao
public interface PlacesDao {
@Query("SELECT * from places_table ORDER BY place ASC")
LiveData<List<Places>> getAllPlaces();
// LiveData<List<Word>> getAllWords();
@Insert
void insert(Places places);
@Query("DELETE FROM places_table")
void deleteAll();
@Delete
void deletePlace(Places places);
}
这是 ViewModel
public class PlacesViewModel extends AndroidViewModel {
private PlacesRepository mRepository;
private LiveData<List<Places>> mAllWords;
public PlacesViewModel (Application application) {
super(application);
mRepository = new PlacesRepository(application);
mAllWords = mRepository.getAllPlaces();
}
LiveData<List<Places>> getAllWords() { return mAllWords; }
public void insert(Places places) { mRepository.insert(places); }
}
这是适配器
public class PlacesAdapter extends RecyclerView.Adapter<PlacesAdapter.PlacesViewHolder> {
class PlacesViewHolder extends RecyclerView.ViewHolder {
public TextView place;
public TextView lati;
public TextView longi;
public ImageView delbutton;
private PlacesViewHolder(View itemView) {
super(itemView);
place = itemView.findViewById(R.id.placeLine);
longi = itemView.findViewById(R.id.longLine);
lati = itemView.findViewById(R.id.latiLine);
delbutton = itemView.findViewById(R.id.delicon);
}
}
private final LayoutInflater mInflater;
private List<Places> mPlaces; // Cached copy of words
PlacesAdapter(Context context) { mInflater = LayoutInflater.from(context); }
@Override
public PlacesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = mInflater.inflate(R.layout.places_list_item, parent, false);
return new PlacesViewHolder(itemView);
}
@Override
public void onBindViewHolder(PlacesViewHolder holder, final int position) {
Places current = mPlaces.get(position);
holder.place.setText(current.getPlace());
holder.lati.setText(current.getLati());
holder.longi.setText(current.getLongi());
holder.delbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "DelButton Clisked", Snackbar.LENGTH_LONG).show();
mPlaces.remove(position);
Log.e("Adapter", String.valueOf(position));
}
});
}
void setPlaces(List<Places> places){
mPlaces = places;
notifyDataSetChanged();
}
// getItemCount() is called many times, and when it is first called,
// mWords has not been updated (means initially, it's null, and we can't return null).
@Override
public int getItemCount() {
if (mPlaces != null)
return mPlaces.size();
else return 0;
}
}
我知道在BindView中做onClickListner
并不好,但这是我能走得最近的。
单击delbutton
后,Snackber和Log都会被激活,Log.e
显示预期值,但该项目不会被删除。
那么,有人可以帮助我如何做到这一点吗?
此致
更新视图正常运行,但我仍然无法从数据库中删除行。有什么帮助吗?
答案 0 :(得分:0)
在删除后的onClick中,只需拨打notifyItemRemoved(position);
即可。
我建议你不要在onClick中使用position,更好地使用holder.getAdapterPosition()
。