简体   繁体   中英

How to seed a Realm database with standard data?

I'm working on a basic project for fitness tracking. I want to initialize the app with an exercise library prepared for the user. How do you provide the data and set up the transaction to populate the database? I've seen the answer below, but I can't find how to actually set up the example, defined in the answer as MyInitialDataRealmTransaction .

Thanks in advance for any insight.

How can I create a Realm database with initial data for my android app?

The initial data takes a transaction as a parameter which runs if the Realm was first created or the Realm was deleted because migration was needed and the config for that was set.

Here is a basic example.

public class RealmInitialData implements Realm.Transaction {
    @Override
    public void execute(Realm realm) {
        Book book = new Book();
        book.setId(1);
        book.setAuthor("Reto Meier");
        book.setTitle("Android 4 Application Development");
        book.setImageUrl("http://api.androidhive.info/images/realm/1.png");
        realm.insertOrUpdate(book);

        book.setId(2);
        book.setAuthor("Itzik Ben-Gan");
        book.setTitle("Microsoft SQL Server 2012 T-SQL Fundamentals");
        book.setImageUrl("http://api.androidhive.info/images/realm/2.png");
        realm.insertOrUpdate(book);

        book.setId(3);
        book.setAuthor("Magnus Lie Hetland");
        book.setTitle("Beginning Python: From Novice To Professional Paperback");
        book.setImageUrl("http://api.androidhive.info/images/realm/3.png");
        realm.insertOrUpdate(book);

        book.setId(4);
        book.setAuthor("Chad Fowler");
        book.setTitle("The Passionate Programmer: Creating a Remarkable Career in Software Development");
        book.setImageUrl("http://api.androidhive.info/images/realm/4.png");
        realm.insertOrUpdate(book);

        book.setId(5);
        book.setAuthor("Yashavant Kanetkar");
        book.setTitle("Written Test Questions In C Programming");
        book.setImageUrl("http://api.androidhive.info/images/realm/5.png");
        realm.insertOrUpdate(book);
    }

    @Override
    public int hashCode() {
        return RealmInitialData.class.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        return obj != null && obj instanceof RealmInitialData;
    }
}

Check out this java library for generating fake data. It's well organized and it also saves a lot of time.

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