在我的Android应用程序中,我以这种方式在firebase数据库中插入VideoEntity对象:
@Override
protected void onCreate(Bundle savedInstanceState){
Log.d(TAG, " onCreate(Bundle) - Ini ");
super.onCreate(savedInstanceState);
database = FirebaseDatabase.getInstance();
String videoId = "";
for(VideoEntity video: videosList) {
videoId = video.getId();
DatabaseReference mRef = database.getReference().child("Videos").push();
mRef.setValue(video);
}
这是VideoEntity类:
package com.app.entities;
import android.os.Parcel;
import android.os.Parcelable;
import java.io.Serializable;
public class VideoEntity implements Parcelable{
private String id;
private String title;
private String description;
private String thumbnailURL;
private String category;
public VideoEntity() {
}
public VideoEntity(Parcel in) {
id = in.readString();
title = in.readString();
description = in.readString();
thumbnailURL = in.readString();
category = in.readString();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getThumbnailURL() {
return thumbnailURL;
}
public void setThumbnailURL(String thumbnail) {
this.thumbnailURL = thumbnail;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCategory() {return category;}
public void setCategory(String category) { this.category = category;}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(title);
dest.writeString(description);
dest.writeString(thumbnailURL);
dest.writeString(category);
}
public static final Creator<VideoEntity> CREATOR = new Creator<VideoEntity>() {
@Override
public VideoEntity createFromParcel(Parcel in) {
return new VideoEntity(in);
}
@Override
public VideoEntity[] newArray(int size) {
return new VideoEntity[size];
}
};
}
问题在于,每次我开始此活动时,相同的对象都会插入到数据库中,因此我在数据库中有重复的数据。
无论如何都要避免这种情况吗?
答案 0 :(得分:8)
如果您的数据具有自然键,请将其存储在其自然键下。在您的情况下,视频有id
字段,这可能是唯一的。因此,不是将视频存储在推送ID下,而是将它们存储在现有ID下:
DatabaseReference mRef = database.getReference().child("Videos").child(video.getId());
mRef.setValue(video);
下次运行该应用时,它会再次在同一位置中写入相同的数据。