[英]Android : Issue deleting last item from RecyclerView
我以以下方式使用RecyclerView
來顯示在SQLite DB中更新的Places項的列表。
當我輕掃它們時,這些項目將被刪除並更新。 但是,當我滑動以刪除最后一項時,它會再次出現在視圖中。 當我關閉該應用程序並重新打開該應用程序時,該項目將被刪除。
但是,當滑動項目以將其刪除時,在運行該應用程序的情況下,即使多次滑動該項目也不會從視圖中刪除。
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
int swipedPosition = viewHolder.getAdapterPosition();
PlaceListAdapter adapter = (PlaceListAdapter) mRecyclerView.getAdapter();
int pos = viewHolder.getAdapterPosition();
// Build appropriate uri with String row id appended
String stringId = places.get(pos).getId();
Log.d("testhro", stringId);
Uri uri = PlaceContract.PlaceEntry.CONTENT_URI;
uri = uri.buildUpon().appendPath(stringId).build();
Log.d("testhhd", uri.toString());
// COMPLETED (2) Delete a single row of data using a ContentResolver
getContentResolver().delete(uri, null, null);
mAdapter.notifyDataSetChanged();
refreshPlacesData();
}
refreshPlacesData()
private void refreshPlacesData() {
Uri uri = PlaceContract.PlaceEntry.CONTENT_URI;
Cursor data = getContentResolver().query(
uri,
null,
null,
null,
null);
if (data == null || data.getCount() == 0) return;
Log.d("countIs", String.valueOf(data.getCount()));
List<String> guids = new ArrayList<String>();
while (data.moveToNext()) {
guids.add(data.getString(data.getColumnIndex(PlaceContract.PlaceEntry.COLUMN_PLACE_ID)));
}
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi.getPlaceById(mClient,
guids.toArray(new String[guids.size()]));
placeResult.setResultCallback(new ResultCallback<PlaceBuffer>() {
@Override
public void onResult(@NonNull PlaceBuffer places) {
mAdapter.swapPlaces(places);
MainActivity.this.places = places;
mGeofencing.updateGeofencesList(places);
if (mIsEnabled) mGeofencing.registerAllGeofences();
}
});
}
我想念什么嗎? 謝謝。
編輯:我試圖更新適配器而不是mAdapter,但仍然沒有變化
編輯2
public void swapPlaces(PlaceBuffer newPlaces) {
mPlaces = newPlaces;
if (mPlaces != null) {
// Force the RecyclerView to refresh
this.notifyDataSetChanged();
}
}
注意:我還驗證了記錄器:
D / countIsZero:true(在refreshPlacesData()內部)
更改數據集后,應刷新View
。
MainActivity.this.places = places; // Data set changed
PlaceListAdapter adapter = (PlaceListAdapter) mRecyclerView.getAdapter();
adapter.notifyDataSetChanged();
否則您應該更改的順序
mAdapter.notifyDataSetChanged(); // Notify later
refreshPlacesData(); // Refresh first
首先更改數據集,然后通知適配器。
解決了..
當我刪除最后一項時,數據計數將變為0,在這種情況下,我當前正在返回。
因此,除此以外,下面是我在refreshPlacesData()中添加的內容:
if (data.getCount() == 0) {
Log.d("countIsZero","true");
mAdapter.swapPlaces(null);
return;
}
和
public void swapPlaces(PlaceBuffer newPlaces) {
mPlaces = newPlaces;
if(mPlaces==null)
{
Log.d("mPlaceNull","true");
this.notifyDataSetChanged();
return;
}
奇怪的是,這里唯一發生的事情是this.notifyDataSetChanged();
在適配器對象上被調用,但是如果我以這種方式使用它並且跳過對swapPlaces()
調用,它將無法正常工作,即
if (data.getCount() == 0) {
Log.d("countIsZero","true");
mAdapter.notifyDataSetChanged();
return;
}
不起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.