问题描述
我正在构建一个Android应用,该应用允许用户在广告牌前100名中的每首歌曲上进行评论(我从JSON fie解析了该信息).我该如何存储注释(最好使用Firebase),并在做出新注释后显示并刷新它们?
I am building an android app that allows users to comment on each song on the billboard top 100 (I parsed that info from a JSON fie). How would I go about storing the comments (preferably using Firebase) and displaying and refreshing them after a new comment is made?
推荐答案
我假设每首歌曲都有一个唯一的ID.因此,对于每首歌曲,您可以做的是-
I am assuming there is a unique ID for each song. So for each song what you can do is-
-
获取歌曲参考
Get the song reference
private DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference();
mSongRef = mDatabase.child("SongID");
每当有人评论一首歌时,将Comment类的对象push()作为该歌的子节点:
Whenever someone comment on a song, push() the object of Comment class as child node of that song:
String commentKey = mSongRef.push().getKey();
mSongRef.child(commentKey).setValue(comment);
现在获取新添加的评论
Now to fetch the newly added comment
mSongRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Comment comment = dataSnapshot.getValue(Comment.class);
Log.d(TAG, "Comment: " + comment.getCommentText() + ", User: " + comment.getUsername());
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}});
现在您有了最新数据,可以将注释添加到列表中并更新回收站/列表视图.
Now that you have recent data, you can add the comment to your list and update recycler/list view.
这篇关于Firebase-用户对事物的评论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!