简体   繁体   中英

Insert multiple entities at a time: Room

I have an entities called BloodShareContact . I want to store list of this entities at a time. But it stores only one entity though it has more than one.

@Dao
public interface BloodShareDao {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    List<Long> insertAllBloodShareContact(List<BloodShareContact> contactList);

}

Repository Looks like.

public class BloodShareRepository {

private BloodShareDatabase bloodDatabase;

public BloodShareRepository(Context context) {
    bloodDatabase = BloodShareDatabase.getDataBaseInstance(context);
}

public void insertContacts(List<BloodShareContact> contactArrayList) {
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... voids) {

            bloodDatabase.bloodShareDao().insertAllBloodShareContact(contactArrayList);

            return null;
        }
    }.execute();
}

BloodShareContact Entity

@Entity
public class BloodShareContact {

    @PrimaryKey
    private int bid;

    private String blood_group;
    private String mobile;
    private String name;

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getMobile() {
        return mobile;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getBid() {
        return bid;
    }

    public void setBid(int bid) {
        this.bid = bid;
    }

    public void setBlood_group(String blood_group) {
        this.blood_group = blood_group;
    }

    public String getBlood_group() {
        return blood_group;
    }

    @Override
    public String toString() {
        return
                "BloodShareContact{" +
                        "mobile = '" + mobile + '\'' +
                        ",blood_group = '" + blood_group + '\'' +
                        "}";
    }
}

Am i missing something?

I would try setting the primary key to auto generate.

@PrimaryKey(autoGenerate = true)
private int bid

Then set all of the bid to 0. This will make sure all the primary keys are unique. https://developer.android.com/reference/android/arch/persistence/room/PrimaryKey.html#autoGenerate()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM