3.2 Add Shopping Items
1.Introduction3 lessons, 04:47
2.Material Design Widgets3 lessons, 16:34
3.Store and Retrieve Data4 lessons, 18:41
4.Conclusion1 lesson, 00:48
3.2 Add Shopping Items
Hello and welcome back. In this lesson, you're going to learn how to add data to their own database. We have already created the interface, which allows the users to type in an item name and quantity. So, all that remains to be done is actually saving those details in the database. Let's go to item activity.java now. Here, add the edit text of objects for the item name and item quantity as member radials. Inside the on create method, initialize both of them using findViewByID. Don't forget to type cast the result by a findViewByID to edit text. Next, add realm as a member variable of this class. To initialize the realm, you can directly use the get default instance method here, because we have already created the default instance configuration in the previous lesson. Inside the save buttons handler, we can now add code to actually write data to their own database. Before we do so, however, we must start a relevant transaction using the realm.beginTransaction method. And now we can create a new instance of the shopping item class, which represents our model. To create the instance, use that realm.createObject method. Pass the class of ShoppingItem, as an argument to it. We must now use the various setter methods to set all its member variables. So, call setName to set the itemName. You can get the value of ItemName using the getText method of data text. Make sure you also use the toString() method to convert it to a string. Call setQuantity in the same data set the item quantity. That's falls to the set completed method, because a newly created item will always be false. Next, call setID to set the ID. To generate a unique ID use, the UUID.random UUID method. This generates a random universally unique identifier. Convert its result to a string using toString. Call setTimestamp to set the time stamp. To get the time stamp, you can use the System.currentTimeMillis method. Now that we have written all the details, we can finish the transaction we started using the realm.commitTransaction method. At this point, item activity should close and the user should be taken back to the main activity. Therefore, call finish(). If you run that now, you will be able to add new shopping items to it. I will say, eggs and 1 dozen and then press the Save button. I will add one more item say, milk and 2 liters. You can't see the items yet, but you can be sure that they have been added to the database in the next lesson. You're going to learn how to point the adapter to the realm database, so that the recycler view can display the data inside it. Thanks for watching.