gpt4 book ai didi

java - 更新 RecyclerView onChildChanged Firebase

转载 作者:行者123 更新时间:2023-12-01 21:58:56 24 4
gpt4 key购买 nike

我正在尝试更新我的回收 View ,但出现错误

java.lang.ArrayIndexOutOfBoundsException: length=12; index=-1

mDatabase.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Upload upload = dataSnapshot.getValue(Upload.class);
uploads.add(upload);
adapter = new MyAdapter(MainActivity.this, uploads);
recyclerView.setAdapter(adapter);
}

@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {

// uploads.clear();
String key=dataSnapshot.getKey();
Upload upload = dataSnapshot.getValue(Upload.class);
uploads.set(uploads.indexOf(key),upload);
adapter.notifyDataSetChanged();


}

@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {

}

@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {

}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});

帮我解释一下这个逻辑。如果我在 onChildChanged 中除了 Notify 之外没有做任何事情,那么它将创建重复的 child

最佳答案

好的,我明白了

您将需要两个数组来执行此操作。

// Lists
private final List<ChatModel> lIndividualChats = new ArrayList<>();
private ArrayList<String> mKeys = new ArrayList<>();

然后

public void onChildAdded(@NonNull DataSnapshot dataSnapshot,
@Nullable String s) {

ChatModel chatModel = dataSnapshot.getValue(ChatModel.class);
lIndividualChats.add(chatModel);
chatsAdapter.notifyDataSetChanged();

String key = dataSnapshot.getKey();
mKeys.add(key);

}

@Override
public void onChildChanged(@NonNull DataSnapshot dataSnapshot,
@Nullable String s) {

ChatModel chatModel = dataSnapshot.getValue(ChatModel.class);
String key = dataSnapshot.getKey();

int index = mKeys.indexOf(key);
lIndividualChats.set(index,
chatModel);
chatsAdapter.notifyDataSetChanged();

}

通过使用另一个简单字符串类型的数组,您将能够访问模型数组列表的索引。

关于java - 更新 RecyclerView onChildChanged Firebase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45985173/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com