由于每次更新ValueEventListener
中的数据时都会触发Firebase Database
,因此在显示RecyclerView
时完成新的上载时也会调用它。现在,发生这种情况时,由于Upload
对象已经在mUploads List
中,因此它会导致重复条目。上传完成后,将再次查询整个数据库,并将所有项目添加到已经存在的ArrayList
中,我不知道该如何解决。我应该在每次触发ValueEventListener时创建一个新的Arraylist
还是需要一个完全不同的回调?
另外,ValueEventListener
会干扰我的mAdapter.notifyItemRemoved
调用,因为ValueEventListener
会在我删除某些内容后立即被触发。
public class ImagesActivity extends AppCompatActivity implements ImageAdapter.OnItemClickListener {
private RecyclerView mRecyclerView;
private ImageAdapter mAdapter;
private ProgressBar mProgressCircle;
private DatabaseReference mDatabaseRef;
private FirebaseStorage mStorage;
private List<Upload> mUploads;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_images);
mUploads = new ArrayList<>();
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mProgressCircle = findViewById(R.id.progress_circle);
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
mStorage = FirebaseStorage.getInstance();
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(final int position) {
Upload selectedItem = mUploads.get(position);
final String selectedKey = selectedItem.getKey();
StorageReference imageRef = mStorage.getReferenceFromUrl(selectedItem.getImageUrl());
imageRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
mDatabaseRef.child(selectedKey).removeValue();
mUploads.remove(position);
mAdapter.notifyItemRemoved(position);
}
});
}
}
最佳答案
清除mUploads
之前,先在addValueEventListener
中添加数据,如下所示
mDatabaseRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUploads.clear(); //change here
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);
}