Kotlin Andriod MVVM CURD APP Tutorial : Room + Coroutines + DataBinding + LiveData + ViewModel

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
during this tutorial we will create a complete Kotlin android crud application for loving Amy VM architecture you will be able to learn about room data persistence library data binding vu murder live data code link co-routines and recyclerview you will also be able to learn about Amy via miss practices for data validations data verifications and display messages I have also added the download link of the final code project below I hope this tutorial will be very useful to you so this is that [Music] you let's start by creating a new Android studio project I am naming this s problema now let's open the app lever dreidel file for this project we are going to use libraries such as data binding via model loaded true and goroutines so let's start by enabling data binding we should enable data binding inside this Android block data binding enabled equals true and sink then we will add required dependencies for view model and live data we can copy them from this page until last month we had this lifecycle extensions dependency which is used commonly for both view model and live data but it is duplicated now so we had to add dependencies for view model and live data separately you we also need great Kotlin kept plugging kept plugging is coding annotation processor especially with room library we need to do a lot of annotation processing we can get kept plugging details from this katli documentation this add kept plug-in to our App level Gradle file you now we can at this annotation processor dependency for the life cycles next for the pro library let's add these dependencies you here we need to change this to cap since we are going to score routines to handle background threats for room we need to add the core routines support for room dependency then I am going to add required dependencies for Co Rudy's we need to add both Co and Android dependencies you could find them from this all roadies get up you this sink the project will also need research early and cardio dependencies but we don't have to manually add them under the studio will automatically add them when we are using those components for the first time for a small demo project we need to create this table in our database table name is subscriber data table and we will have three columns subscriber ID name and email subscriber ID should be the primary key so I am going to create a data class with these properties and annotate it with entity annotation room library creates a table for each class and dated with entity annotation so let's create a new could link us I am creating a new package for database related classes first let's name this glass as subscribe I am going to make this a cuddly dataries now we will add three properties ID of type in name and email of type string you first of all we need to annotate this class with anti generation here we can mention the database table name we want room to you when room creates a table response to this data class if we do not give any name like this room we'll just use the class name subscriber as the table name we can also use column info annotation to specify the name of the corresponding column in the table we want it to be different from the name of the member variable giving separate names for the database table then just using the names of the data cross is the best practice because in a larger project we might need to use this same data class for other tasks and with other libraries you next we need to specify a primary key for this database table we can set the primary key by adding primary key annotation to this subscriber ID failed we want this primary key to auto-generate so let's set the auto generate property s true so that's how we create an entity class for a room database data access object interface or dau interface is where we define the functions that access the database we were using SQLite directly we had to write larger database queries in a separate file we had to write complex code logics to work with curse objects but now room does hold the hardware for us reading the information we provide using annotations I'm going to create a new interface let's name this as subscriber Dao and annotate with the dowel annotation Rome will recognize this interface as data access object interface up the scene this dowel annotation now let's write a function to insert a subscriber object to the database suspend fun insert subscribe object APIs subscriber now most importantly we need to annotate this with the insert annotation here I wrote the name of the function as insert this name is not important you can provide any meaningful name you like the most important thing is this insert annotation room library recognizes this function by rating the insert annotation not the function name since we have added a subscriber object as the function parameter Rome will recognize that we need to insert a subscriber object to the database and room will generate required codes for that task in the background why do we have this suspend modifier Rome doesn't support database access on the main three because it might look the UI for a long period of time therefore we need to execute these functions in a background thread for that we can use async task rx Java will execute us but the most advanced easiest and the most efficient ways puddling co-routines since room provides direct support for Cortland co-routines room facilitates us to write these functions as suspending functions with suspend modifier a suspending function is simply a function that can be paused and resumed at a later time I believe you all have learnt fundamentals of code in co-routines and suspending functions during previous introduction to go routines section of this course now if somehow you are determined not to use coroutines you can write these functions without suspend modifier it will also work if you are using another way of background processing in the coding class also we can write different versions of these insert functions we can write a function like this to it multiple SUBSCRIBE objects to add a list of objects function would be like this we can also add a single object and a list sometimes for a verification we might need to get a return value we can actually get the new row ID or IDs as the return value of type long the type should be either legume or an array or desktop long values if we are expecting to get the inserted row ID as the written value of these functions they should be modified like this you on conflict strategy is another important property we can set for these functions if we make one conflict its Prodigy not replaced this will try to insert the entity and if there is an existing role that has the same ID value it will delete the old entity and replace the row with the new entity if we set it as ignore it will ignore the complicit but for the simple demo project we don't need them we all innate the basic instead function during other later sections of this course when we are developing more complex projects little lives different variations of this insert function now let's declare a function to update a row of the subscriber data table suspend fun update subscribe function parameter should be an instance of subscribe objet in this with the update annotation is the most important thing function name is not important we can also write this function adding a list of subscribers as the parameter to update and in the list at once we can also write this function with an int return type we'll return the number of pros updated in the database for now escape these functions in their simplest form now let's define a function to delete a subscriber suspend fun delete subscriber function parameter should be an instance of a subscribe object then annotate this with the believed annotation delete function can also have different variations we can add more than one entities as parameters we can also add stop entities as a parameter same as the update this period function can also return an int the value would be the number of rows deleted now with query annotation room allows us to include ask you a query that would run when the function is called most importantly this query will be verified at compile time by room to ensure that it works well with the database so there will be no database queries rated at runtime errors this is a major advantage of using room data persistence library I am going to create a function to delete all the rows from the table suspend fun delete old then annotate this with the korean tation then SQL query delete boom subscriber data table this is the table name we have given in this subscriber entity class next I am going to write a function to get over the data from the subscriber data table today's us to get data from a database table as a live data of list of entities these quarries are called asynchronous Cory's because for these queries which as a live data as a return value room always run them when a background it by itself so we don't have to write special codes to run them in the background set so we don't have to use co-routines is in task or executors to execute these functions let me show you how to write a function to get the list of all subscriber entities from the database as lab data fun let's say get tour subscribers return type is a live data of list of subscribers then query silly all from subscriber data table you so what are the differences of this function and other functions we define we didn't add a suspend modifier for this function why is that because we don't need to execute this function in a background thread using co-routines since this function returns to routed from library to its work from a background thread so this is our detects the subject interface I hope you understood everything I explained clearly if you have any question any not clear area please ask questions from me I'm always a bit supportive so far in this section we created an entity class for a database table and a Dao interface to manage its data now to represent the actual database of the app is create an abstract class which is a subclass of from database class I am naming this as subscriber database this should be abstract and extends from database we should annotate this with database rotation here we need to provide the list of entity classes you we have only one entity class then the version number of the database this version number is important when we are migrating the database from one version to another let's talk more about database migrations in another listen then we need to declare an abstract reference for the DAO interface you and this is small demo project we have only one entity class and the corresponding bow interface if we had more entity classes we would have listed them all here and define the references for corresponding dowse now we can just create a new object and use this database class in other places of the project but that is not the best practice usually we should only use one instance of a room database for the entire app to avoid unexpected errors and performance issues we should not let multiple instances of database opening at the same time therefore it's great a singleton here in Kirtland we create Singleton's as companion objects companion object then the reference to the subscriber database you let's annotate this with volatize annotation Walter's annotation makes the field immediately made visible to other threats about this boilerplate code part you don't have to remember this you can copy paste this code part to all your database classes and change the class name and the database name fun with distance Parham it is context-- this returns a subscriber database then here we add a synchronized look look is this subscriber database class wha is does equal is thus which we defined above if instance is equal to null instance equals room not database builder here we need to provide the application context as the context then the name of this class then the name of the database we want to create let's name the database as subscriber data database built finally returned the instance you so don't worry about this single delectation caught part we use the same boilerplate code for all bloom projects only by changing the class and database names for this project we are going to follow a medium architecture he may be amazed the recommended best architecture for Android development by Google MeV M stands for model wave and view model model means oh data management related components model has local database rated components remote data sources related components and repository for this small project we are not going to use remote data sources we have already created an entity class a dau interface and database class which completes this part of the MA VM architecture now during this lesson we are going to create a repository class for this project the purpose of a repository class is to provide a clean API for view models to easily get done Sint data as Google documentation says you can consider repositories to be mediators between different data sources such as local databases web services and caches in our simple project we only have a local database some of you might think why should we create an intermediate repository cross country directly communicate with the DAO from the view model yes that is possible but our goal here is to teach you about my VM architecture to learn a medium architecture to learn about this coding patterns this create a repository class for this project I'm naming this s subscriber repository I am adding an instance of subscriber Java interface as a constructor parameter for this class because we are going to go to the functions of the Dao from the repository first I am defining a variable for Loudred of disturb subscribers well subscribers equals this should be aha dot get all subscribers as we discussed during the previous lesson there's no requirement to go to this yet told subscribers function from like grounded because room library automatically process these functions with live data as the return type in a background thread all other dowel functions should be cold from background thread we will loose go routines in the view model class to execute them but to support that we need to define these functions as suspending functions let's create a function to insert subscriber data suspend fun insert barometer should be an instance of subscribe then inside the function diode would insert subscribe bastard subscriber instance as an argument now let's create a similar function for update you then another function for bolete you finally let's create a function for delete or subscriber data you this is the app we are going to create in this main activity we will have two text input fields to insert subscribers name and email address then we will have two buttons see and clear old we will have a recycler view to display the desktop subscribers text on the buttons should change for updates and deletes when the user clicks on the list item so let's open the to demand that XML file and start designing this layout I am deleting this big space and to make this simple I am changing this layout to a linear layout width and height should be match parent set the orientation as vertical I am going to sit atributes easily from here this is much easier than writing XML is at a margin of 15 DP now an e-text for subscribers name askew the ID s name next which should be match parent how it should be redundant let's add a margin of 15 dB but for the bottom 15 DP might be too much let's change it to Phi D P I am adding subscribers name for the hint let's keep the text size s 18 s P and change the text style to bold let's also remove this text value okay now we can see the hint let's just copy paste this for the email text input you did the ideas email text then change the hint s subscribers email also change the top margin s 5dp you now for these two buttons this add another linear layout and set the orientation as horizontal you by default orientation has it thunder the heart should be prepped content let's add the button I am sitting this IDs sale or update button with an height should be rep content I am setting the text size as 18 SP and text his style as bold then this add another button I am giving the ID as clear or or delete button with an height should be grab content and I am setting the deck size as 18 SP and takes this type s bold then let's track a research review to the bottom of this main DNA layout hundred the student needs to download the library this click on ok now if you check the trader you will see that under the study has automatically added the greater dependency required for recyclerview actually we need this recycle we located in the main being a layout so I'm going to cut this and paste it below this also remove his weight property set the height as wrap content and I am giving an ID to this as subscriber reset review this said the Martins you so our main layout is ready now let's create a view middle class for lives create a new cutting class name this as subscriber murder this should extend the view model class you to use functions defined in the repository class we need to have a reference to subscriber repository so let's add an instance of subscriber repository as a constructor parameter to this project now for the subscribers name and email I am going to define to me to be live data variables you pipe should be Street you let's annotate this with bindable annotation you now let's switch back to activity main.xml file to use data binding is add layer Tex asked outermost text of this way out you then more namespace declarations next I am going to add diuretics here let's define a reference variable for the subscriber view model you now for the values of text properties of these two text input fields I am going to bind input name and input email mutable data values defined in the via murder as you have learned during previous sections of this course we are using two-way data-binding here you now for the text display on these patterns I am going to define another two mutable lab data in the view model class you I am creating an init block here inside the network we should define initial display names to those two buttons this should be save and this one should be clear all why am I doing this because according to our plan the text on these buttons should change dynamically when the user clicks on the recyclerview list item the selected subscribers name and the image should display on input fields and Save button should change as update and clear all button should change yes delete now this bind these live data values for the text properties of buttons you then in the view model I am going to create two functions fun say update [Music] and fun clear or Oh delete you now in the activity main.xml file let's bind those functions to the unclick events of the buttons you now let's complete other functions of the view model class we don't need to create a special function to get the list of subscribers as Larry data he can just call repositories subscribers variable you let's create a function to ease it a subscriber fun insert but ammeter should be a subscribe business from here we can call to the insert function of the repository passing the subscriber instance as they discussed earlier we should do this function call from a background thread we could use leave Moodle is curved the torch for that you since we are using Kotlin we can even make this function more concise like this now let's create similar functions for update delete and clear you for now in this delete or Creole function let's just add a code to coal to clear old function in this sale or update function let's write codes to insert the subscriber entity to the database well name data type is string equals input name dot value these values should not be null well email he may not value insert subscriber zero name email since we set the primary key subscriber ID as auto incremental value we can just add zero as the ID for all subscriber entities Rome will just ignore it end at the Auto incremental value let's write codes to clear the input fields after saving is done input name depressive equals null and inputting multiple vehicles since overview model has a constructor parameter as we learned during a previous lesson of this course we need to create a view model factory class for this blue model let's create a new cut link class Namie des subscriber view model Factory since the Vavi middle class is an instance of subscriber repository as a constructor parameter the spectra class should also has an instance of subscriber repository as a constructor parameter you this should extend the muder provided at the factory you it's over a decade function this next code part is just boilerplate code we use for every viewmodel Factory I just copied it from a previous human factor example and change the view model name and constructor parameter name you now let's move to mainactivity and right course to use the view murder first of all I am going to write codes to get the data binding object you then let's define a reference variable for a subscriber wave model instance but before get the view model instance using the factory class we need to create a factory instance to create a subscriber of a malefactor instance we need to pass a dao instance as an argument so let's start by creating a dao instance well thou during a previous lesson we created a room database class which provides singleton database instance we are going to use it here subscriber database protocol distance we need to pass the application here good subscribe Dow next I am going to it repository instance using this dau instance you then let's create a subscriber B model factor instance using that repository instance you now we can write codes to get subscriber v-model is dis you then I am going to assign the view model instance to the data binding object since we are intending to use live data with databinding we need to provide a life cycle owner now I am going to create a function to observe the list of subscribers data in the database table private fun let's say Display subscribers list for now we will just look the result but later he will write codes to display this data on a recyclerview let's right course here to observe the list of subscribers which is in live data format here in the DAO interface we have this gate or subscribers function which returns a list of subscribers s value data we go to that now function from the repository and assign loaded to the subscribers property then here in the video model we get that loaded from the repository now I am going to write coerced of so that live data from the main activity subscriber view Mona but subscribers dot of sir lifecycle owner is this observer this and look here you there is one last thing to do to use this bindable text in wave model this view model class should implement the observer interface this should be Android X dot data bind inner observer not the Java util dot observable we also need to implement its two functions let's just keep them empty and from the main activities on a great function we need to call to this display subscribers list function all right now it's good time to run them and see these in action to see the look results let's use the tech name I'm going to run that now this and fake subscriber you we need to change this these are the live data results you can see the subscriber we just added have persisted in the database I said as a subscriber you can see here he got automatic it appears and look at the subscribe IDs they are to implementing as we intended so that means insert and query function it is working well now let's test the delete tool functionality you can see here our subscriber date has been deleted from the database they said that you won you yes you've subscriber data persisted to the database as we intended I'm going to add two more subscribers to the database you now during this lesson we are going to display subscribers theta in a recyclerview to do that as the first step let's create an XML layout resource file for the recycler view is better select the resource type as layout let's name this says this data sister next to you I'm changing this layout to linear layout set the orientation s vertical you I'm sitting the bottom margin s 20 dB let's keep the layout width as my parent and change height into prep content now to provide a much better design to the recyclerview list item I'm going to add a card wave here under the studio is going to at cardboard dependency to the trader and download the Cardew library for us let's speak okay if you check your level little file you will see this automatically edit card leave dependency now we need to give an ID to the cardview let's keep the layout with as much parent and change the height into prep content then this set layout gravity as sinned then let's it drinkable property and focusable property as true you next let's set the primary color as got background color then I am going to set the card radius as 10 dB and the card innovation also s 10 DP we need to add an ID to this layout a textview display the subscribers name let's provide an ID to this s named x2 set the width and height SRAM content and this add the margin of 10 dB they said Disko you it's said that text is tied as bold and text size as 30 SP now I am going to duplicate say code for email Dexter change the IDS email Dex do and change the text size as 24s B right now our research revealed list item is ready now during this lesson I am going to show you how to display this subscriber data on a recycler view first up were to use data binding I am going to add layout text as the outermost X of this list item protects ml file you also take the namespace declarations to the layout text now let's create a class for the recyclerview adapter I'm naming this as my recyclable adapter as you have learned during the recyclerview fundamentals section this class should extend the recycling waves adept across when we are extending we need to provide an adapter class as the object type therefore we need to create another class which extends three circular roofs adapter grass you could create this lesson in a grass or a separate grass in the same file I am going to create this as a separate class let's name this s my wheel holder since we are going to use data binding we need to add the data binding object of the list item layout as the constructor parameter layout name is list item so this should be listed and binding then extend recyclerview tot we hold bus line ended route as an argument we mainly use this class to bind values to each list item for that let's create the function I am naming this s bite since we are going to have a subscriber instance to this is added as a parameter I am going to also write codes to bind values to the view of the list item our list item has two textures named extreme and email text to you by ending that name display order text equals subscriber dot name binding good email text reader text equals subscribe edit email all right now let's go back to the main a replicas Here I am going to define a list of subscribers as the constructor parameter let's name this s subscribers now this adapter class should extend recycle leaves adapted to us pipe should be the grass we created below then we need to implement these three functions on create we hold that item count and unbind reward now I am going to implement the one create we hold function this is where we create the list item to do that we will use the list item XML layout template we created earlier first of all let's get an instance of layout invader then we need to get the data binding object of the list item layer you next I am going to return an instance of my view holder class passing this data binding object as an argument the data binding object will be used here this get tied up count function returns the total number of items in the dataset held by the adapter so this should be subscribers list dot size then we will implement this unbind we hold a function we use unbind we hold display data on the list item considering the int value returned from this debt item count function recyclerview library will create separate rows for each list item this position represents that account value of each list item so here we will get the relevant subscriber object from the subscribers list using this position value and pass it to the bind function of the my recyclerview plus so our adapter class is ready for now let's go back to main activity and write codes to display the data in the recycler view using this adapter let's create a function here named in it reset levy you I'm going to set the layout manager for the recyclerview here IDs subscribe and disco reset levy you we need to add the context now from here let's go to the display subscribers list function and from the mainactivity let's go to this unitary circular view function then we can set the adapter bypassing disturb subscribers you now it's time to end up and see this in action you it's clear or data and handsome did a test how this works you good rep is working as we intended during the previous lesson being remaindered the recyclerview now during this lesson we are going to firstly add a click listener to the recyclerview and after that we will implement update and delete functionalities here in the main activity I am going to create a function for the click current this should take a subscriber instance as a parameter this subscriber instance will be the corresponding subscriber instance of clicked list item for now let's add let those message context is this let's display the name of the clicked subscribe you to implement click event we are going to use Kirtland higher-order functions and lambda expressions here we are going to use a lambda expression to pass the function as an argument selected item object I paste subscribe then the name of the function we just cleared bust business now let's go back to adapter class and change it's constructed for this new change private well with listener required object type is subscriber since this function does not return anything we should add unit here right so now we have a clip listener as a constructor parameter now let's add the save click listener to this bind function of this my V holder class as a parameter you then from here let's pass this click listener reference variable as an argument next inside this bind function I am going to implement the set down quick listener function of the layout layout ID is list item layout binding dot list item layout got set on good Krishna inside this function we will write codes to past the selected subscriber instance this will pass to the stratum clicked function defined in the main activity alright now let's run that and see how this works let's click on a list item a toast message shown with the selected subscribers name so other paste working as intended actually we added this click listener to implement update and the eight functionalities with a user click on a list item name and email of the selected subscriber display on the text input fields and Save button should change into Update button and clear all button should change into delete button to do that let's go back to subscribe every model and create a new function there named in it update and delete we should enter subscriber instance as a parameter [Music] so we will pass the selected subscriber instance to this function now I am going to write codes to display the selected name and email on the text input fields you input name and email uh the live data values binded to those fields then I am going to define two variables which we will use later to implement update and delete functionalities first one is a boolean value private Wow is update or delete equals false next private late in it bah subscriber to update or delete object AP subscriber since this is a latent variable with how to define the object type then here let's set is update or delete as true and let's assign this subscriber instance to the subscriber to update or delete variable now I am going to write course to change the display text relative of the buttons you let's go back to main activity again from here this core to newly-created in it update and delete function now let's run deep and see how these new genius work good selected subscribers details were displayed on text input fields and buttons also changed as update and delete now let's go back to main activity view model and implement clear all and delete functionalities we have already created this function here now I am going to add an if-else look if is updated is it let's go to digit function passing the subscriber to update to delete distance is it's good clear old function now insert this delete function let's copy from here input name and email values should empty you this should change to force and these button values should change as save and clear all now we will implement save Oh update Here I am going to add another first look let's go to update function here inside update function we can add same codes we added for the delete but for update we need to set new updated values to the properties of the subscriber object let's do it here you under this to do shows and either hmm okay well cannot be reassigned this is a good lesson for us not like Java in Gatlin we have two modifiers to define a variable well and power if we are willing to update properties of an object all those properties should be defined as well so let's open up a subscriber entity class and change all variable definitions from well - Wow this should be our ID this should be ba name and this should be wha email all right let's go back to be middle class now in to distribute as much to a redundant line let's also update the email value now this is the good time to run there and see this in action let's select a subscriber I'm literate in this one yes it worked as we intended then I'm going to update this good about miss working as expected so let's have a implement update and delete functions in different situations we might need to communicate with the view from the wave model to inform the user about the result we might need to show a toast message or a snack bar as an example if we consider this project we might need to show a toast message to inform you sir after successfully inserting a new subscriber data to the database one way of doing that is creating a separate interface with some functions then make the activity implement that interface and invoking those functions from the view model but that is not the correct approach because that violates the fundamentals of a Myriam architecture in M EVM the view model should not know about the views the view model should not have any reference to a leave we can use loaded for events by creating a single live event class the problem with single live event is that it's restricted to one observe this Loudred will only send an update once use an event wrapper is the recommended best practice and even wrapper class allows us to explicitly consider the state of the event so now I am going to create a new contain class this name it does event this is a boilerplate code you can reuse for all your Android widgets I am copying this code part from this official Android developers publication on medium.com this class will be used as a wrapper for data that is exposed wire allow data that represents an event you don't have to remember this code you can just copy this class for all your Android projects now let's switch back to subscriber via model dot kt+ Here I am going to define a mutable live data for the status message private well status message equals mutable loaded we are going to use this variable for a string message so the type should be string but we are going to use newly created you in class as a prepper therefore type should be an event of a string you then I am going to create a getter for this loaded well message low data that should be same as the bull then get miss status message is immutable limited therefore they can edit its value we can assign different values bit but it is a private variable therefore they cannot access to it from the outside classes that is the correct code in practice we should do that for data security and for data stability then here we have created a public data our set classes can just observe the live data since we are not willing to modify this we don't need to define this as we develop data now let's go to insert function Here I am going to update the value of mutable live data with the success message status message value equals event we need to pass this tree message here let's say subscriber inserted successfully then let's go to update function subscribe the updated successfully then the delete function subscribe yet successfully finally clear old function we'll subscribers deleted successfully now let's open the mainactivity Here I am going to write codes to observe the tablet subscribe every model dot message lot of cell lifecycle owner is this observer it not yet content if not handled this avoids repetitions let let's write the dose message here you it's also coming to this das message now I am going to run there and see how this new changes work let's add a new subscriber you Kahless update this one you good about peace working as intended so this is how we display messages on the view without violating the hem EVM architecture now during this lesson you will loose return values of room for proper much accurate verifications let's go to subscriber Dao interface I am going to start with insert function a function annotated with insert annotation can return a long value which is the new row ID for the inserted item if the parameter is an array or a collection it should return an array up long values Oh Ali stop long values so let's get the newly inserted row ID to get the newly inserted row ID lifts at a long return type now switch to repository class we need to add a long return type to this corresponding insert function then at return here so this function will return the newly inserted row ID next is switch to view model class here in the insert function of the subscriber view model class we can get the return value as new row ID then for the verification you let and if there's using the Nero ID if any error happened probably return the row ID as minus 1 so if new row ID is cleared to the N minus 1 is you it all good let's add the new row ID to the message this is not necessary but for the learning purpose let's just end it now I am going to run that and see how this works you you can see we have received the neuro ID let's go back to now interface again we can have this update annotated function return an INT value indicating the number of rows updated in the database then I am changing the repository function accordingly you next change the view model update function you it's random and see how this works you good app is working as we intended now also for the delete functions we can have them return an int value indicating the number of rows removed from the database then let's modify repository delete functions accordingly you next switch to the view model let's say number of rows did it you I'm going to do the same for this clear old function you okay now let's stand up again and see these changes in action let's do this one functions are working as we intended now I am going to delete all subscribers good other piece working as we expected so there's how we can use return values from Rome database functions for verifications now it's very quickly at some validations for the text input fields here I have opened the subscriber view model class I am going to write user input validations inside this sale or update function first of all is spelled it for null values in our case both name and email values cannot be null if input name value is equals to null we can copy the message statement from below you let's say this in the subscribers name email input fields also can be not so else--if input email dot value easy customers you let's say please in the subscribers email next we will write the validation for the email address entered email and this should be in the great format let me show you how to do it that turns good email address good mature input email add value no tomatoes this statement will give true if the entered email address in the correct format but we want to send a message if it is in the incorrect format so let's at this then copy the message they say please in the correct email address okay after these validations we can also use it or save or update data so is let's cut and paste them inside you so this is our improved save update function with validations now it is good time to run that and see how these newly added validations work it's this for the empty name and then for the empty mate you then I'm entering an email address in in correct format you good our new user input validations are working as intended if you have studied our code well you would have recognized that there is an inefficiency in this display subscribers list function every time we create a new subscriber update a subscriber or delete a subscriber we create a new my recyclerview adapter object we should have written codes to create a 1 adapter object and update it for database changes let's do it now I am starting from the my recycler wave adapter class let's take this subscribers list definition from the constructor and keep it as a reference variable here assigning an area street now let's define a new function to set the list of subscribers to this you then let's write codes to clear the order list and assign the new updated list to it you all right now let's go back to main activity here we need to take this code part two in it recyclerview function since we need to refer to this adapter instance as define it as grass level variable and here let's construct the adapter we don't need this parameter now then in this display subscribe assist function I am going to write codes to a no exceed list function we just created passing the updated list of subscribers as an argument earlier we created a new adapter object for every new update but now we are just reusing the initially created and a project so we must still recyclerview that there is a new update this is how we do it and after dot notify data set changed now if we run this up we will see a piece working well as it worked before but if you carefully calculate the loading time and memory usage of the app you will observe that our new version of that piece much efficient than the previous so for this reason thank you so much for is me see you soon with the next season [Music]
Info
Channel: AppDevNotes
Views: 45,849
Rating: 4.9077492 out of 5
Keywords: Android, Kotlin, Room, Room Data Persistence, ViewModel, LiveData, DataBindng, Coroutines, RecyclerVIew, Jetpack, Android Architecture Components, CRUD App, Tutorial, Example, Project, MVVM, To Do App, CRUD
Id: v2yocpEcE_g
Channel Id: undefined
Length: 106min 0sec (6360 seconds)
Published: Tue Apr 07 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.