问题
I have decided to use Realm for my project. I've gone through the documentation and cannot understand how to get all my phone contacts imported into my Realm database. Has anyone done this kind of project before? Please help.
I have used Sugar ORM which has a bulk insert option. Does Realm have the same or is there an alternative to that?
Here's what I've done till now:
package com.advisualinc.switchchat.Realm_DB;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
/**
* Created by Veeresh on 10/19/2015.
*/
public class R_ContactDB extends RealmObject {
private String name;
@PrimaryKey
private String phone;
private boolean matchedWithRecent;
private int status;
public R_ContactDB(String name, String phone, boolean matchedWithRecent, int status)
{
this.name = name;
this.phone = phone;
this.matchedWithRecent = matchedWithRecent;
this.status = status;
}
public R_ContactDB()
{
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public boolean isMatchedWithRecent() {
return matchedWithRecent;
}
public void setMatchedWithRecent(boolean matchedWithRecent) {
this.matchedWithRecent = matchedWithRecent;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
回答1:
With Realm there is no need for something which is directly adequate to bulk inserts available in SQLite. There is no overhead of a query language involved.
You can just insert multiple objects via Realm#copyToRealm batched in a single write transaction. If you need to import JSON data, there is Realm#createOrUpdateAllFromJson(JSONArray).
回答2:
in 2016 realm added a new api for insert bulk data
realm.insertOrUpdate(Collections datas);
try this method and for more, look at here. https://realm.io/blog/realm-java-1-1-0/
回答3:
full code in kotlin
fun insertList(list: MutableList<MenuItems>) {
val realm = AppDatabase.getRealmInstance() //get Realm Instance
try {
realm.executeTransaction { realmTr ->
realmTr.copyToRealm(list)
}
} catch (error: Exception) {
error.printStackTrace()
} finally {
realm.close()
}
}
来源:https://stackoverflow.com/questions/33229006/bulk-insert-in-realm