gpt4 book ai didi

android - 在 Firebase RecyclerView 中添加或删除子项时重复列表行

转载 作者:搜寻专家 更新时间:2023-11-01 09:26:24 25 4
gpt4 key购买 nike

当在 firebase 实时数据库中添加或删除子项时,我得到一个重复的列表行。重复的是添加新 child 时的旧行。会是什么?

我避免直接​​到达目标 child ,因为我计划从不同部分检索更多数据,所以我循环遍历数据快照。我认为这对我来说是最佳选择。

DataSnapshot child : dataSnapshot.getChildren()

这是我的计划:

Os osData = child.child("StaticData").child("os").getValue(Os.class);
Ram ramData = child.child("StaticData")..child("RAM").getValue(Ram.class)
...
...

这是代码。

public class HomeActivity extends AppCompatActivity {

private static final String TAG = "HomeActivity";
SharedPreferences sharedPref;
private String uid;
private DatabaseReference databaseReference;
private RelativeLayout emptyListPlaceHolder;

List<Os> myList = new ArrayList<>();
RecyclerView rv;
HomeAdapter homeAdapter;



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ButterKnife.bind(this);
rv = findViewById(R.id.recycler_view);
databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.keepSynced(true);
emptyListPlaceHolder = findViewById(R.id.home_activity_empty_placeholder);

getSharedPref(); // Gets uid

getHomeData();

}

private void getHomeData() {

DatabaseReference userStatsRef = databaseReference.child("stats").child(uid);

userStatsRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {

int i = 0;

emptyListPlaceHolder.setVisibility(View.GONE);
for (DataSnapshot child : dataSnapshot.getChildren()) {
Os osData = child
.child("StaticData")
.child("os")
.getValue(Os.class);

myList.add(i, osData);

i++;

} // END for loop
rv.setVisibility(View.VISIBLE);
rv.setLayoutManager(new LinearLayoutManager(HomeActivity.this));
rv.setHasFixedSize(false);
homeAdapter = new HomeAdapter(myList);
rv.setAdapter(homeAdapter);

} // END onDataChange

@Override
public void onCancelled(DatabaseError error) {
Log.w(TAG, "Failed to read value.", error.toException());


}
});

}

}

最佳答案

找到解决方案。我需要添加的只是 onDataChange 覆盖方法中的 osList.clear();

 private void getHomeData() {

DatabaseReference userStatsRef = databaseReference.child("stats").child(uid);

userStatsRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
osList.clear(); // This line solved the issue.

int i = 0;
....
....

关于android - 在 Firebase RecyclerView 中添加或删除子项时重复列表行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50242675/

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