This example shows how to create and insert object data in Realm Database on Android. Below Java code uses Realm Java SDK / Library on Android.
1 2 3 4 5 6 7 |
// Define your model class by extending RealmObject public class User extends RealmObject { private String name; private String country; // getters and setters... } |
1 2 3 4 5 6 7 8 |
try (Realm realm = Realm.getDefaultInstance()) { // All changes to database must happen in transaction realm.executeTransaction(real -> { User user = realm.createObject(User.class); // Create a new object user.setName("Prasanna"); user.setCountry("India"); }); } |
To insert multiple objects, use insert or insertOrUpdate method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
try (Realm realm = Realm.getDefaultInstance()) { List userList = new ArrayList<>(); User user = new User(); user.setName("Prasanna"); user.setCountry("India"); userList.add(user); // All changes to database must happen in transaction realm.executeTransaction(real -> { real.insert(userList); }); } |