我正在尝试编辑 recyclerview 中的一个项目,该 View 显示来自 Firebase 的一些数据。但编辑后数据集并没有改变。它会显示以前以及新的更新项目,直到 Activity 重新加载。截图在最后给出。
我正在通过警报对话框编辑项目。代码如下:
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.MyViewHolder> {
ArrayList<User_Post> user_posts=null;
Context context;
public ListAdapter(@Nullable ArrayList<User_Post> posts, Context c) {
this.user_posts=posts; // the data set
this.context=c;
}
在项目的编辑按钮上单击AlertDialog
打开:
//'post' is an instance of type User_Post containing the current data item.
dialogBuilder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(isValid()) {
post.setWorkType(txtType.getSelectedItem().toString());
post.setWorkDescription(txtDetails.getText().toString());
user_posts.set(position,post);
updateDataSet(user_posts);
saveToFirebase(post,"edit");
Toast.makeText(context, "Post updated", Toast.LENGTH_SHORT).show();
}
}
}
更新 Firebase 数据的代码:
private void saveToFirebase(User_Post post, String task) {
String id=post.getPostID();
FirebaseDatabase database = FirebaseDatabase.getInstance();
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("gs://smart-worker-c73c4.appspot.com/gs:");
DatabaseReference myRef = database.getReference("posts");
if(task.equals("edit")) {
myRef.child(id).setValue(post);
}
else {
myRef.child(id).setValue(null);
storageRef.child(id).delete();
}
}
用于更新数据集:
private void updateDataSet(ArrayList<User_Post> posts){
this.user_posts=posts;
notifyDataSetChanged();
}
最佳答案
It shows previous as well as the new updated items, until the activity is reloaded
因此,当您重新加载 Activity 时,新数据将显示在 RecyclerView
上,因此数据已成功保存到 Firebase 中,并在重新加载 Activity 时抓取。因此,该问题与 firebase 无关。
此外,您决定不对 Firebase 提供持久事件监听器,而是在本地更新了 RecyclerView
:
private void updateDataSet(ArrayList<User_Post> posts){
this.user_posts = posts;
notifyDataSetChanged();
}
尽管我建议在通知更改之前清除并重建列表:
private void updateDataSet(ArrayList<User_Post> posts){
this.user_posts.clear();
this.user_posts.addAll(posts);
notifyDataSetChanged();
}
这不是最佳过程,因为调用 notifyDataSetChanged()
的成本很高;相反,我建议notifyItemInserted
()或notifyItemRangeChanged()
;仅部署对 RecyclerView
的更改。
例如,如果您只传递单个项目:
private void updateDataSet(User_Post post){
this.user_posts.add(post);
notifyItemInserted(this.user_posts.size()-1);
}
对于一系列项目:
private void updateDataSet(ArrayList<User_Post> posts){ // Pass only those items that are changed
int currentSize = this.user_posts.size();
this.user_posts.addAll(posts);
int newSize = this.user_posts.size();
notifyItemInserted(currentSize, newSize - 1);
}
关于Android recyclerview 数据更改后显示更多值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69425872/