我有一个问题,我想用领域写数据库。我的数据是String,它们的数量超过500,我将它们写为String,我希望在第一次运行程序时按领域保存所有数据。 有没有办法我不单独输入所有信息? 你有什么建议? tnx
答案 0 :(得分:0)
然后将json文件复制到资产。
[
{
"Name": "Michael",
"Phone": 2525055
},
{
"Name": "Anthony",
"Phone": 665588
},
{
"Name": "Dana",
"Phone": 245244
}
]
模型类
public class People extends RealmObject {
private String Name;
private int Phone;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getPhone() {
return Phone;
}
public void setPhone(int Phone) {
this.Phone = Phone;
}
}
然后使用Realm导入数据
public class RealmImporter {
// From json to realm database
static void importFromJson(final Resources resources) {
Realm realm = Realm.getDefaultInstance();
//transaction timer
final TransactionTime transactionTime = new TransactionTime(System.currentTimeMillis());
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
InputStream inputStream = resources.openRawResource(R.raw.people);
try {
realm.createAllFromJson(People.class, inputStream);
transactionTime.setEnd(System.currentTimeMillis());
} catch (Exception e) {
e.printStackTrace();
} finally {
realm.close();
}
}
});
Log.d("Realm", "createAllFromJson Task completed in " + transactionTime.getDuration() + "ms");
}
}
更新
您可以使用findAll Like获取数据,
RealmResults<Person> details = realm.where(Person.class).equalTo("Name","Anthony").findAll();