Firebase + RecyclerView:notifyItemRemoved无法正常工作

时间:2018-01-30 17:44:48

标签: android firebase firebase-realtime-database firebase-storage

我可以从Firebase存储和数据库中删除我的条目,但是当我调用notifyItemRemoved时,它无法正常工作。它不是删除条目,我认为这是因为它干扰了ValueEventListener,它也在更新时触发。当我离开活动并重新打开它时,条目(正确)消失了。

任何人都可以建议我在活动中为了正常工作而改变吗?

public class ImagesActivity extends AppCompatActivity implements ImageAdapter.OnItemClickListener {
private RecyclerView mRecyclerView;
private ImageAdapter mAdapter;

private ProgressBar mProgressCircle;

private DatabaseReference mDatabaseRef;
private List<Upload> mUploads;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show_images);

    mRecyclerView = findViewById(R.id.recycler_view);
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

    mProgressCircle = findViewById(R.id.progress_circle);

    mUploads = new ArrayList<>();

    mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");

    mDatabaseRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {               
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {  
                Upload upload = postSnapshot.getValue(Upload.class);        
                upload.setKey(postSnapshot.getKey());
                mUploads.add(upload);
            }

            mAdapter = new ImageAdapter(ImagesActivity.this, mUploads);

            mRecyclerView.setAdapter(mAdapter);

            mAdapter.setOnItemClickListener(ImagesActivity.this);

            mProgressCircle.setVisibility(View.INVISIBLE);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Toast.makeText(ImagesActivity.this, databaseError.getMessage(), Toast.LENGTH_LONG).show();
            mProgressCircle.setVisibility(View.INVISIBLE);
        }
    });
}

@Override
public void onDeleteClick(int position) {
    Upload selectedItem = mUploads.get(position);
    final String selectedKey = selectedItem.getKey();

    StorageReference imageRef = FirebaseStorage.getInstance().getReferenceFromUrl(selectedItem.getImageUrl());
    imageRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            mDatabaseRef.child(selectedKey).removeValue();
        }
    });

    mAdapter.notifyItemRemoved(position);
}
}

1 个答案:

答案 0 :(得分:1)

因为您的List填充了数据,无论您是从数据库中删除数据,它仍然在List内。因此,您首先需要从List中删除数据,然后通知适配器数据已被删除。例如:

mUploads.remove(position); mAdapter.notifyItemRemoved(position);

删除后播放动画尝试使用:

notifyItemRangeChanged(position, getItemCount());

考虑从onDataChange中删除适配器类,以防止一次又一次地重新创建适配器。此外,在使用Firebase数据库和RecyclerView时,请考虑使用:https://github.com/firebase/FirebaseUI-Android