gpt4 book ai didi

android - 为什么我从 firebase 数据库中获取重复数据?

转载 作者:行者123 更新时间:2023-11-30 00:33:50 25 4
gpt4 key购买 nike

public class Post {

private String title;
private String massage;

public Post() {
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getMassage() {
return massage;
}

public void setMassage(String massage) {
this.massage = massage;
}
}

public class Posts extends AppCompatActivity {

private DatabaseReference databaseReference, barRoomsCoordinates;
private FirebaseDatabase firebaseDatabase;
private List<Post> postList;
private List<String> list;

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

postList = new ArrayList<>();
list = new ArrayList<>();

showAllMyPosts();


}

private void getPosts(List<String> posts) {

for (int i = 0; i < posts.size(); i++) {
databaseReference = firebaseDatabase.getReference().child("Posts").child(posts.get(i));
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Post posts = dataSnapshot.getValue(Post.class);
Post post = new Post();

post.setTitle(posts.getTitle());
post.setMassage(posts.getMassage());
postList.add(post);



}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});
}
}

private void showAllMyPosts() {
FirebaseApp.initializeApp(Posts.this);

Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
barRoomsCoordinates = firebaseDatabase.getReference().child("Posts");
barRoomsCoordinates.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator iterator = dataSnapshot.getChildren().iterator();
while (iterator.hasNext()) {
list.add(((DataSnapshot) iterator.next()).getKey());
}
getPosts(list);
}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});
}
};
handler.post(runnable);
}
}

这是我的数据库结构

Posts
Post1
message1:
"abc + something"
title1:
"abc"
Post2
message2:
"def + something"
title2:
"def"
Post3
message3:
"ghi + something"
title3:
"ghi"

我得到了重复的数组,不明白为什么请帮我。我也尝试删除一个引用并进行调用,但这样我就无法访问 JSON 的子项。

最佳答案

发生这种情况是因为您的 for 循环。每次循环时,您都在创建一个新的 databaseReference。将 databaseReference 从循环中取出,它将解决您的问题或尝试更改从 Firebase 数据库获取数据的逻辑。

希望对您有所帮助。

关于android - 为什么我从 firebase 数据库中获取重复数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43766473/

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