Unlimited Plugins, WordPress themes, videos & courses! Unlimited asset downloads! From $16.50/m
  • Overview
  • Transcript

3.1 Database and Data Model

In this lesson, you’ll learn how to create a new Realm database as well as a data model for the shopping items.

Related Links

3.1 Database and Data Model

Hello and welcome back to this course about building a material design Android app. In the previous lessons, we set up both a recycler view and an adapter. However, without a source of data they're both useless. In this lesson, we are going to create a source of data for them and it's gonna be a relevant database. Creating our own database takes only a few lines of code. First, create a new member variable of type realm inside MainActivity.java. This variable is going to represent the realm database, you can collapse that after for now. To create a new realm database, you must first create a new configuration for it. So create a new variable of type realm configuration. We will be using a realm configuration.builder instance to generate the configuration. Pass this as the context to its constructor and then call its build method. This generates a configuration using just the default values. Make this configuration the default configuration using Realm.setDefaultConfiguration. You can now create the realm database using the Realm.getDefaultInstance method. Our database is now ready to be used. We are going to be storing shopping items inside this database. So let us create a model for our shopping item now. If you're familiar with SQL databases like SQLite or MySQL, you can think of this model as a table in the database. Because realm models are nothing but Java classes. Create a new class for the shopping item model, I'm gonna call it shopping item. To make this class behave as a realm model, you must make it a subclass of the RealmObject class. We can now specify what we want to store inside this model. We will obviously store the item name and item quantity both as string objects. We will also store a boolean to know whether the item has been completed or not. Additionally, let us add an ID field that we can use to uniquely identify the shopping items. You can use the @PrimaryKey annotation to make this the primary key. To make it easy for us to display the recently completed items, let us also add a timestamp of type long. Finally, we need to add getters and setters for all of these variables. Select all the variables here and press OK. Our data model is now ready. In this lesson, you learned how to create both a new realm database and a data model for it. I'll be waiting for you in the next lesson where I show you how to add data to the database.

Back to the top