Top 10 Advanced Android Development Topics You Must Know | Android Studio Tutorials - All in One

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone welcome back to my channel in this video we will learn how to store and display data using share preference so from this video we will be starting our Android cotlin Advanced Series where we'll be going to cover topics like mvvm room database API retrofit and many more all of these topics are kind of tricky but don't worry we will learn each topic with the help of project now come to today's video where we will understand what is share preference also just a little note that in 2023 developers prefer data store rather than share preference which we will cover in Jetpack compos series now what is share preference let's understand with a simple example imagine you have a small notebook like a d di in your Android phone where you can jot down some notes that you want to remember later this notes could be things like your favorite color a game level you reached or whether you want the app to show music or not share preference in Android is like that little notebook it's a way for apps to store and remember small pieces of information that they can use later just like you open your diary to see what you wrote app can open share preference to see what settings or values you have saved it's handy because even if you close the app or turn off your phone the information you wrote down in share preference will still be there it's like your app's own private memory where it can store simple things you want it to remember even when you're not using the app got it now let's create it choose mty views activity then write the name as learn shared preference and click on finish let me give you a quick overview of what exactly we are going to create so it's a very simple notes project where the user will write a note in edit text and by clicking on save button it will store the note in share preference and then when the user will click on display note button it will display the exact note in the text view simple right you can further modify the project by maybe adding a recycler view to display multiple nodes it's all up to you here I'm just going to give you a basic idea of how share preference works so first let's do the prerequisite so go to colors.xml add the red color whose hex code is FF 3131 and then then go to themes. XML here mention all the three parameters color primary color primary variant and Android status by color and done next go to gradal build here I will write build features and then inside it write view binding as true now click on sync now and done then let me quickly add a background just to make the project look more presentable you can skip this drawable step if you want to and done now prerequisits are done so go to activity main.xml here I will create an edit text with a save button and below that a display note button with a text view where the note will be displayed and that's it let me quickly write the code and done you can pause the video and copy the layout code okay now see we have kept parent as relative layout then inside it to linear layout and then inside it an edit text whose ID is notes edit text and a button whose ID is save note button then outside the linear layout there is a button whose ID display node button and the text view for ID is not text View and that's it this is how it looks now go to main activity let me give you a quick overview what exactly we are going to do so we will initialize share preference with a name then inside the same node button we will store the data using share preference methods and then lastly inside the display node button we will retrieve the data and display it on text View and that's it so first let me quickly set a binding and then then declare share preference and done now I will initialize it as share preference is equal to get share preference this is very important meod to store name of the share preference and its mode so inside it I will write no data as a share preference name and then context mode as private this is a way to specify the excess mode for your share preference in this case you are using mode private which means only your app can access this share preference got it then we need to store data when the user will click on save note button right so for that I'll write minding dot save note button dot set on click listener and then inside it first we will take take the input from user through edit text so let me quickly write it and done so whatever the text user will write in notes edit text will be stored in the note variable then remember in SQL database we used to define access mode for database like writeable database or readable database likewise we need to specify here as well so I'll write well shared edit as share preference dot edit means the preference can be modified or edited now write dot put string so put string is a method to store share preference using a key so I'll write key as note this is the key you are giving to the piece of information you are storing that is note through edit text and this node is an actual content that you need to store then finalize everything by using apply method and then I'll throw a toast as not stored successfully [Music] lastly once the note is stored you can wipe off the edit text using clear method simple right now when the display node button will be clicked then it will retrieve the note and display it on text view so to do that first write Bing dot display node button dot set on click listener on it and then inside it I'll retrieve the data first so write will sto note is equal to shed preference dog string see to store the data we have used put string method and to retrieve the data we have used kit string method got it then inside it write the exact key that is note and then I'll keep the value as null which means it will act as a default value that will be written if there is no value associated with the key node and then the data will be stored in the stored note variable then lastly display the note so I'll write binding dot no text view dot text is equal to mention the stored note variable where the actual note is retrieved and stored and that's it we are done with the coding now let's run the app see this is how it looks I'll quickly write here some note and now I'll click on save note and see the to says as note stored successfully now I click on display note and look the note is displayed here perfect also let me quickly show you where exactly share preferences saved so go to device Explorer while the device is in running mode then go to data and then again data and then inside it find your Project's package name here it is click on it then go to share preference folder and here you will see a share preference name that is no data I click on it and see it's a XML file where the exact note is stored using map attribute and that's it you can follow us on Instagram or join us telegram group for more updates Link in the description box so yeah that is it for the video if you are new to this channel then please consider subscribing to my channel and I'll see you in the next video hey everyone welcome back to my channel in this video we will learn data binding and view binding one by one with their examples so first let's understand what is data binding data binding is a technique that allows you to establish a connection between UI components and the data see in very simple language it's like giving a variable to text view directly in the XML layout I repeat variable not ID so usually we assign variable to a particular UI component in activity right but in data binding we can directly assign it in XML layout got it this is how we enable data binding in gridder module build features and inside did data binding is equal to true now next is what is view binding see view binding is a feature that simplifies the process of interacting with UI components basically it replaces F view by ID method and also in F view by ID if you wrote incorrect ID or maybe not initialize it then it will obviously going to lead incorrect view type casting or null reference so to avoid such cases view binding was in introduced this is how we enable view binding in grd module build features and inside it view binding is equal to true now what is the difference between data binding and view binding so view binding is a subset of data binding like whatever functionalities view binding can perform that can be performed by data binding as well but whatever functionalities data binding perform view binding cannot in simple words data binding can be used as a substitute to view binding but view binding cannot be used as a substitute to data binding like data binding can replace find view by ID and it can also connect data in UI while view binding can replace find view by ID but it cannot connect data in UI got it we have previously used view findinding in most of the projects so I assume you are quite familiar with it and even if you're not then let's understand it better through examples this is an m project where I will Implement view binding as well as data binding one by one so first let's start with easy one that is view binding step number one is to enable view binding so go to build grader app and inside the Android brackets and below the cine options here write build features and then inside It Right View binding is equal to true and that's it now click on sync now and done then go to activity main.xml here we will create a simple linear layout with a text View and a button so let me quickly create it and then see parent layout as linear layout and inside it a text view whose ID is also a text View and then a button whose ID is also a button and that's it there is no functionality or any logic in it I'm just demonstrating you like this will be your UI components now go to main activity. GD first let me show you the traditional method that is by using find view by ID [Music] see this is where we declare the variable and then using find view by ID we initialize the UI components but with fine view by ID there are chances of wrong IDs or null reference so to avoid that let's go for view binding also you might be wondering what's wrong with this method it's easy then why the need of view binding because if the project is small with less UI components then it is fine to use find view by ID but imagine an xtml layout file with six button five image view 10 text view then in that case you can't keep writing fine view by ID for each one of them right hence that's where we will need viewp pointing got it so we have already enabled view binding in grel and now we need to write three lines of code just to declare and initialize it first write private l in it where view binding as activity main binding tell me in which activity we are currently in main activity right and in which XML layout we are trying to connect activity main.xml correct so it will be activity main binding consider if the layout name is activity login then it will be activity login binding and if the layout name is activity snup then it will be activity snup binding do you see a pattern so prefix is XML layout name that is activity made and suffix is binding always remember that the Declaration is dependent on layout file name not an activity got it let me show you if I reame main activity as maybe login activity so see still no error but now I'll rename XML layout as activity login and see there is an error now it will become here as activity login pining got it hence declaration is dependent on XML layout file name next we have already declared it now to initialize it write the variable as binding is equal to activity login binding dot inflate as layout inflator means to fetch the layout then we usually attach XML layout in set content view but now instead of it we will write binding do root means to attach the entire layouts basically you can access any UI components from it now all the setups are done and it's time to actually use it see I want to set a text on text view so to do that first we need to access it so for that I'll write binding that is a variable then dot so when you write binding dot it will instantly show you a list of UI components see we have text view then button then container everything at one place so out of it I'll choose text view then dot text and some random text on it and that's it now I want to set on click listener on button so first to access it I'll write binding Dot and out of this list I'll choose button UI component then dot set on click listener on it and that's it then inside it you can perform any actions did you see we don't need to declare or initialize the button we just wrote binding Dot and then we had a list of UI components in it cool right and that is what VI binding is all about also make sure to remove old activity UT otherwise it will throw error now let's try data binding I'll clear everything and back to empty project now whatever we performed in view binding same things can be performed in data binding as well but view binding is not capable to establish a connection between data and UI components and that's when we use data binding so first we need to enable it and go to gr module below cot options here write build features and then inside it write data binding is equal to true and that's it now click on sync now and done but if you'll notice here it throws a warning as you need to add a coding kept plug-in so to do that in the same grel module file you will find a plug-in set where add a new plugin as ID cotlin k a PT and then click on sync now and that's it so data minding is enabled and now let's set up first go to activity main.xml here we have previous XML layout where linear layout as a parent layout then inside it a text view whose ID is also a text View and below it a button whose ID is also a button and that's it now here comes a Twist as I said data binding connects UI components with data so text View and button is are UI components but where is data so just above the parent linear layout we will create a layout with all the necessary declaration so let me quickly write it and done see no linear layout no relative layout no constraint layout just a layout the closing layout will be at the end means it will cover all the UI components in it now inside the layout and above the linear layout we will add a data so I will write data and inside it I will write variable and then again in inside it I will write variable name as message and its data type as string and that's it once the data variable is created then we will assign it to the UI component directly in the XML layout itself and that's what the magic of data binding is so we will assign this message variable to text view how write text s at theate curly brackets and mention the variable name that is message simple right see ID is text View and variable is message both of them are different then come to main activity. KD here first we will declare it as private L it where binding as activity main binding I have already explained it in view binding then we will initialize it as binding is equal to data binding util dot set content View and here mention this and the XML layout not the root and that's it so data binding is declared and initialized and now we will see how are we supposed to use it okay so I'll write binding Dot and here you will see a list of UI components as well as variable name so I'll select message variable see if I would have go for text view ID then this is how the code would have look but as I chose variable itself that is assigned to text view I can skip text view ID as well as do text all I have to write is equal to as some string got my point also as I said data binding can do the job of view binding so in that case if I want to access button then I'll write here binding dot I'll choose button ID then dot set on click listener on it then inside it you can perform any operations and that's it I hope you have understood view binding as well as data binding so make sure you use either one of them in your next project I'll recommend to go for view binding okay so yeah that is it for the video if you are new to this channel then please consider subscribing to my channel and I'll see you in the next video hey everyone welcome back to my channel in this video we will learn one of the components of MV v m architecture that is view model so first let's understand what is mvvm so in very simple language mvvm architecture gives your project a proper organized structure with the help of its three components first is model then second is View and then third is view model got it I'm not going in detail about View and model because today our focus is only on view model so later in upcoming video I'll cover them but to understand view model model we need to know little bit about View and model to so let me give you a quick overview about them see in very simple language VI handles the user interface basically all the UI components design XML and all and model represents the data it could be local data such as room or SQL light or it could be remote data source such as retrofit API and all cut it and then comes the view model as you already know that view handles UI and model represents data but now the question is how will UI and data will communicate with each other and that's where view model comes into the picture so view model acts as a bridge between View and model it is responsible for preparing and managing between data and UI C model is responsible for only data and view is responsible only for UI but view model is resp responsible for the communication that takes place between them communication as in actions that needs to be performed like I'll give you an example consider a Notes app where notes database is sqlite or maybe room database as data that is basically a model and recycler view list view that displays the node as UI that is basically a view and then comes the view model which basically acts as a mediator between them to send and receive request request as in read the data write the data update the data or delete the data this processing can also be done using live data I'll cover this topic in the next video so stay tuned for that but for now let's understand view model in detail through a sample so open Android Studio choose empty views activity name the project as learn view model let me give you a quick overview what exactly we are going to create so we will be creating a counter app like when the user will click on the button then the count will increment by one it will go like 0 1 2 3 that way I know it's a very simple app but our Moto is to understand how can we use view model and other two components as well so let's create it first let's do the prerequisite so go to colors.xml add color is red with hex code AS FF 3131 and done next go to themes. XML add all the three items color primary color Prim variant and Android status bar color and done then go to build. gradal here we will add view binding so write build features then inside it write w binding is equal to true and then click on sync now and done now to use view model we will require view model dependency so let me copy paste it and done then again click on sync now and then you can find the dependency in the description box also let me quickly add background drawable just to make the app look more presentable you can skip this step okay close all the tabs now go to activity main.xml here I will create a text view that will display the count and a button that will increment the count simple right so let me quickly create it and done see this is how it looks we have a constraint layout as a parent layout then inside it a text view whose ID is text view counter and then below it there is a button whose ID is button increment and that's it this text View and button are UI components that is basically a view now view is done and then comes the view model we will create a separate class for view model Okay so so right click on it and create a new cotlin class file I'll write the name as my view model and done now listen to me carefully first we will extend the classes view model then next we will create instruction that needs to be performed on the data but where is data I mean model see as this is a very simple project so there is no such big database like SQL or room database here we have our data as private where counter is equal to zero this counter variable is a data or you can say model got it so we have view as well as model and now it's time to connect both of them via view model class as I previously said that view model send and receive receive the request such as create read update or delete data so here we will perform two requests first is to read the data and second is to update the data data is in counter value like read counter will fetch the count and display it and update counter will increment the count got it let's implement it first create a function for read so fun get initial counter it will return return the initial value of counter that is zero so as the return return value data type is integer so I'll write here as int and then inside it return counter that is zero itself simple right next as we want to update the count so I'll create an update counter function so I'll write fun get updated counter again it will return an integer so I'll write here as int and then inside it it will return return incremented counter now beginners might have confusion with Plus+ counter why is it not counter Plus+ see if it will be counter Plus+ then in that case initial value is zero and when you click on increment button then the next value is also zero and then again you click on it the next value will be one and so on but if it will be plus plus counter then in that case initial value is zero and when you click on increment button then next value will be one and then again you click on it then next value will be two and so on getting my point so in counter Plus+ it consider itself first and then increment the next value while in Plus+ counter it directly increment the next value got it now view model and view model everything is ready let's connect all of them in main activity first first let me quickly set up [Music] binding and then next we need to access my view model function so for that we need to call the my view model class so let me quickly declare it and done now I need to initialize my view model so I'll write view model provider see view model provider is a utility class provided by view model library that helps you to create and retrieve instant es of view model classes for us it's our my view model class so first I'll write this as owner this as in main activity itself then using get method I'll retrieve the my view model class then next we need to set initial value on our text view initial value is basically zero only but if you remember we have created a get initial counter function in my view model class right then my V model. getet initial counter function dot two string because as you remember function was written in integer so to display it on text view we need to convert it to string got it so initial value set as zero Now set on click listener on button increment and then inside it on the same text view counter it will display the updated counter value so I'll write my view model do get updated counter do two string and that's it now let's run the app see it's initially zero now I'll click on increment button and look the count goes like 1 2 3 and so on perfect but if you are new to this topics you will be wondering why there is a need to do all of these things like why can we declare counter zero here itself and increment it directly why to make such CS right let me clear your doubt see first thing that view model makes everything structured like model view view model everything is separated and organized if you would have created everything in same activity then that would have been more chaotic right and second the very important reason is that view model can handle system configuration changes very well system configuration as in screen rotations like I'll show you an example sample this is duplicate counter app project but without using view model everything is in same activity and now see it works exactly same but here comes the twist I'll increment the count and if I rotate the screen then look the count went back to zero again I'll increment it and then rotate the screen see again the count went back to zero it's like every time you rotate your phone the activity will start from the beginning that will be annoying right hence view model is used to overcome this issue this is our counter app project using view model here I'll increment it and then rotate it and see even after the screen rotation the counter value remains as it is now I'll increment it and again I'll rotate it and see again the value is as it is got my point and that's it so yeah that is it for the video if you're new to this channel then please consider subscribing to my channel and I'll see you in the next video hey everyone welcome back to my channel in this video we will learn about live data with view model I have already covered view model in my previous video so I'll highly recommend you to watch that video first before watching live data okay all right coming back to today's topic you remember these are the three components of mvvm right model view and view model model represents the data view is basically the UI and view model acts as a bridge between model and view basically it is responsible for managing UI related data and also for communication that takes place between View and model communication as in to send and receive request to perform a particular action action as in to maybe update the data or delete the data got it now Focus between View and view model this is where live data resides between View and view model but what is live data live data is part of Android architecture components and also it is a data holder class that is observable which means it can be used to hold and observe changes to the data in very simple language live data is like a special container that holds a piece of information and it can let other parts of your app know when that information changes let's understand it through an example imagine you are building a weather app that displays the current temperature for our city so instead of manually updating or refreshing the temperature display every few minutes or whenever it changes you can use live data it's like live data holds the temperature data and the UI observes it whenever the temperature data changes then the UI automatically displays the updated temperature Val value which makes your weather app more Dynamic and responsive without the need for manual updates got it now let's understand live data more through the project so open Android Studio choose empty views activity name the project as learn live data let me give you a quick overview what exactly we are going to create create so we will be creating a counter app where if the user clicks on the button then the count will be incremented by one like 0 1 2 three that way I know it's a very simple amp but again our focus is to understand how can we use live data in the project also it's the same app which we created before in view model but this time we will be creating it with the help of live data the use of live data ensures that any Observer of the counter live data will be notified automatically when count value changes this in turn triggers the UI update in the activity simple right now let's create it first let's do the prerequisite so go to colors.xml add the red color hex code AS FF 3131 and then next go to themes. XML add this three lines color Prime color primary variant and Android St Spar color and then now go to build. gridle app here add view winding and click on sync now and then then as we want to use live data as well as view model hence we will require both the dependency you can find them in the description box then click on sync now and done close all the tabs now go to activity main.xml here I'll create a text view that represents the count and a button that will increment the count so let me quickly create it and done see parent layout as constraint layout then inside it a text view whose ID is text view counter and then below it a a button whose ID is button increment and that's it this is how it looks now comes the important part as I previously said live data is present between View and view model so view is our activity main.xml and now let's create view model so right click on it create a new cotl class name it as my view model this is where the magic happens I already showed you how view model works first is to extend class as view model perfect so previously inside it we created counter variable and its function right but now here inside it I'll create live data first create a variable named as count live data then initialize it as mutable live data and keep the data type as int now what is mutable live data mutable live data is a subass of live data that allows you to modify the value it holds this means you can change the integer value stored in the count live data then we need to initialize the value so let me quickly write it first and then now see init block is used to initialize properties when an instance of the class is created like in our case init block is setting up the initial value as zero of the count live data property next we need to declare live data so let me quickly write it and then now see here I have declared a variable that is counter live data as live data data which holds the integer values only then get Block is used to retrieve the value of count live data and provide it as the value of counter live data lastly I'll create an increment counter function so let me quickly write it [Music] and done now see this increment counter function will be used when the increment button will be clicked basically it will increment the number by one it goes like count live data dot value will retrieve the current count at is display on the text View and then using question mark and colon that is Elvis operator it sets the default value as zero and then increment it by one simple right so quick overview when you access the counter live data property which we will do it in main activity then it Returns the value of count C data this allows UI components to observe and access the counter value as live data without the need to directly access live data great right now let's move to main activity this is where we will initialize the view model observe the live data and increment the counter so first let me quickly set up binding and done next we need to access my view model function so for that we need to call my view model class so let me quickly declare it and done now I need to initialize my view model so I'll write my view model as View view model provider see view model provider is a utility class provided by view model library that helps you to create and retrieve instances of view model classes for us it's a my view model class so first I'll write this as the owner this as a main activity itself then using get method I'll retrieve the myv model class this is how we initialize it next we need to observe the live data so I'll write my view model dot counter live data remember counter live data not count live data okay then dot observe as this then create account variable that will keep the account value and then inside it set the count on the text view counter using text method then add Observer here so here UI is observing counter light data and whenever the count change it will immediately update the text view counter see so simple right lastly set on click listener on button increment and then inside it write my view model and access the increment counter function which we created in my view model class and that's it we are done with the coding now let's run the app see it's initially zero now I'll click on increment button and look the count goes like 1 2 3 and so on perfect the app is very easy that's not even the concern my concern is that you guys have understood how live data work right to make it easy for you remember these four steps first is mutable live data second is init block then third is live data and then fourth is observing the live data simple right and that's it hey everyone welcome back to my channel in this video we will learn about mvvm architecture and its three components that is model view and view model out of these three components view model is a New Concept for you hence I have cre created a separate video on it in detail so make sure to watch that video first okay you can click on the I button to watch but now in today's video we will be covering model view and view model all three of them in the same video and in the same project okay so first let's understand what is mvvm mvvm is an Android architecture that basically organize your code into separate modules like data will be stored in different module UI will be stored in different module modules as in packages which ultimately makes development and reuse of both simpler and faster like in corporates usually multiple team member works on the same project right but imagine that project with no mvvm structure like data UI logic everything in the same package it will be so confusing for each member to understand that project right but now imagine the same project with MVM structure let me explain it through an example imagine the code behind zomato app it literally have thousand lines of code crazy right but more than that imagine maintaining that code but no that's not how professional app works they are built in such a way that they are well organized and structured so if they want to update any feature they will be able to quickly find it in the code because they know in which package which functionality resides all the small project might not necessarily require mvvm but it is highly recommend to use MVM or any other type of architecture when you create a professional app okay till now you are aware what is MVM and why is it required so now let's quickly understand its three component as well that is model view and view model so model represents the data view represents the UI and view model represents the communication that takes place between View and model simple right see whenever you create a project using mvvm make sure to create create three different packages inside it that is model package which will consist of all the data related activities then view package which will consist of all the UI related activities UI related activity does not only means XML file but also the activities which Define UI components in it like main activity and then view model package which will consist of all the UI related data activities got it so now let's understand it better through an example simple project open Android Studio choose Mt views activity name it as learn mvvm let me give you a quick overview of what exactly we are going to create so we will be creating a simple kids calculator app that just add two numbers I know it's a very simple app but again as I always say our focus is to understand how can we use m VM in the project now let's create it first I'll do the prerequisite so go to colors.xml add the red color with hex code AS FF 3131 and done next go to themes. XML add these three lines color primary color primary variant and Android status by color and done now go to build. grd app here add view binding click on sync now and then also as I'm using the latest Android Studio so I guess there is no need of adding view model dependency but if you face any error regarding dependency then simply add it in the credle module okay I'll mention the dependency in the description box then let me quickly add a background just to make the app look more presentable you can skip this step close all the tabs next let's quickly design activity main.xml here we will have four important components two edit text one button and lastly a text VI to display the result and that's it so let me quickly create it and done now see the designing code is quite a lot as you can see but as I previously said Focus only on four important components and their respective IDs let me show you first parent layout is a linear layout and then inside it this linear layout card view add text view is just to make app look more presentable and then inside it this is important edit text whose ID is edit text num one the next edit text whose ID is edit text num two and then a button whose ID is calculator button then just a result text View and then below it a text view whose ID is result text View and that's it I'll slowly scroll the code so you can pause the video and copy the code and then now comes the mvvm part this is where we will create different packages see inside com. example. learn mvvm this is our main package and inside it we will create three package that is model view and view model right so to create a package right click on it click on new package after this write model and press enter see we have a model package ready similarly we will create View and view model package too and done now as I previously said inside each package we will have the respective activities so first we will create model activity then view model activity and then lastly view activity that is main activity itself so let's do it step by step first we will create data that is basically our model so right click on model package and create a new codling data class name it as calculator data here we will have all the data variables like first number second number and the sum value as I previously said it's a very basic app so the data will be very low key only imagine maybe there is a nodes app then we might have room database or sqlite database but for now it just basic variable as a storage so I'll write first variable as num one data type as int then second variable as num two as int then third variable as sum that is also as int and that's it see to add two numbers first number will be stored in Num one then second number will be stored in Num two and then the result will be stored in some variable got it this is our variable will act as a storage to store the data and done now next thing is to create view model where I will give the instruction that needs to be performed on that calculator data so first right click on view model package create a new cotal in class as calculator view model this is where I will write the instruction instruction as in the logic to add two numbers so first I'll extend view model and then inside it we will create a function as calculate sum so write fun calculate sum and pass the parameters as num one as int and then num two also as int then as I said instruction needs to be performed on model that is basically a calculator data right so at the end of the logic it should return return calculator data hence I'll write here as calculator data and then inside it the logic what is the logic to add two numbers you guys already know that is to use add operator so it goes like some variable will store the num one plus num two result simple right and as I said lastly it will return the calculator data hence I'll create a calculator data object with num one num two and some as its properties which Returns the object and that's it all right model is ready view model is also ready and now it's time to attach them with view that is nothing but a main activity which consist of all the UI comp components like edit text textt View and button so first we will move main activity from Main package to view package and then now go to main activity here are three important things that needs to be done first is to initialize view model then add functionality on the button and then lastly display the result on the text view simple right before that first let me quickly set up binding and done now as we need to access add function from view model so for that we need to declare and initialize it so view model is declared and now let's initialize it I'll write calculator view model as view model provider see view model provider is a utility class provided by view model library that helps you to retrieve the instances of view model class for us it's a calculator V model class hence I'll write this as the owner this as in main activity itself then using get method I'll retrieve calculator view model class and done this is how we initialize it now why are we not declaring or initializing calculator data as well which is basically our model class because we we have already created its object in view model right so this is what mvvm is data and view directly does not communicate with each other they go via view model class okay then next set on click listener on calculate button and then inside it first I'll take the input from the user through edit text so let me quickly write it [Music] and then see num one variable will store the first number input that is given by user through edit T and similarly num two will store the second number input you already know text method and two string method but what is two internal let me explain two internal basically converts the string that is obtained in two string to an integer if the conversion succeeds then it will return the integer value otherwise it will return null simple right then this is the LV operator it checks the result of two internal if two internal returns null then it it default is set to zero got it lastly we need to display the result so first create a result variable that will store the sum value and how will we calculate the sum using calculate sum function that is present in calculator view model right so to access it I'll write here as calculator view model dot calculate sum and pass the arguments as num one and num two the calculated sum is stored inside the result variable and now using text method we will display it on the text view so I'll write here as binding dot result text view dot text as dollar sign to access the variable so I'll write here as result variable do sum where does this sum comes from to check that press control and click on it see this is where it comes from basically it is a string interpolation that substitutes the value of result. sum into the string means in a very simple language whatever the result sum data is that is displayed on the result text View and that's it we are done with the coding now let's run the app this is how it looks I'll write here as 20 and here is 30 and then click on calculator button and see 50 is displayed as result perfect app is very py that's not even the point my point is how we Implement mvvm so let me quickly give you an overview look we have three different packages model view and view model with their respective activities inside it in model activity we have data in view model activity we have model object as well as the addition logic then in view main activity we have connected a view model with its UI component and that's it this is what mvvm is all about at the end of this Advanced series I'll surely create a fully functional app using MVM okay so stay tuned for that and for now you can follow us on Instagram or join a telegram group for more updates Link in the description box hey everyone welcome back to my channel in this video we will learn about room database this is one of the most important topic in Android development also as this is Advanced Series so topics are kind of little tricky but don't worry I'll try my best to make it as simple as I can so as you already know there are variety of ways to store data right previously we have used Firebase realtime database then SQL light database right and now room database it's Advanced Clean and high efficient than other database all right let's understand room database but before proceeding with that first we need to do a little recap about sqli database because they are kind of related to each other hence let's first understand sqli database so this is all bookish definition so better focus on what I am telling you okay now see as you already know sqi database is a local storage present in your device that stores retrieve update and delete the data with the help of queries right we have previously created a Notes app using sqli database with CR functionality you can click on the eye button to watch but SQ database has some kind of drawbacks as well as a lot of boiler plate code hence to overcome that issues room library was introduced room database is a library that provides a an abstraction layer over sqlite database now what is abstraction layer basically abstraction layer is a way of hiding the working detail of a subsystem in our situation subsystem is SQL light in simple words as I said SQL light has a lot of boiler plate code right so room database basically hides it and provides only the necessary code we will see that differences in the next slide but before that let's understand more about room database it's a clean and efficient way to store retrieve update and delete the data and it does not necessarily require queries to perform actions also clean as in they are really structured like mvvm how mvvm separates model view and view model similarly room database does the Same by separating its component which we will see in the upcoming slide also it stores the data locally in the device itself got it then see as I previously said room is an abstract layer on the top of sqlite database which basically handles the task that were performed by the sqlite open Helper and also it brings a lot of customization that SQL light lack in itself in simple words you can say it's a better version of SQL light database but what makes it better than SQL light let's see the differences first in SQL light there is no compiled them verification of SQL queries but in room it validates each and every SQL query at the compile time second as your schema changes schema as in database structure okay so it says if your schema changes then in SQL we need to update it manually while in room it automatically updates it then third as I said previously room avoid boiler plate code by directly mapping the database object to Java object while SQL uses a lot of boiler plate code to do the same thing fourth as room is a new and advanced Library hence it works with live data mvvm RX Java and many more while SQL does not next remember in mm this is view this is view model then below it there is a repository that consist of model which is basically room database this is where room database resides got it in the end of this Advanced series I'll be creating a project using room and mvvm which will clear all your doubts okay so stay tuned for that then next comes the important part that is basically three components of room first is entity second is doww that is database access object third is database these three components are responsible for making the application clean and structured each one of them is very important so let's understand it one by one with the help of examples okay first is entity an entity is a class that represents a database table including its column data type and primary key in simple words there is an entity data class that will declare table name and all the columns present inside it let's see the sample code to understand it better this is an entity data class named as user entity also I thought of creating an entire room database project but it's quite huge hence I'll cover it in the end of the series but for now we have sample codes for each component to implement room database make sure to add room database depend tendency in the Gradle module now let's have a look at entity data class as I said entity declares table name as well as column name so this is how it looks this atate entity annotation each components has its own annotation like entity has atate entity Dow has atate Dow and database has atate database but what is annotation annotation is like a node that defines what actions are we supposed to perform like whenever we declared entity annotation that means this is where we are supposed to declare table name and column see this is the list of all the annotation present in room database you will find this on internet too now back to entity class so our table name is users and this is not a normal class it's a data class okay then inside it we have three column name with their data type first is ID whose data type is long and also it's a primary key you know the concept of primary key right like if we associate primary key with a column that means that column values will be unique so here all the ID needs to be different from each other likewise phone number and email column can also be a primary key right it is mandatory to decare one of the column value as primary key in room database okay next if we have a column name as name whose data type is string and then email that is also a string and that's it see it's so easy to write entity code right now let's understand dowo that is database access object a Dao is an interface that provide abstract method to interact with database basically it enables grud operation that needs to be performed on The Entity sounds complicated let's crack it first let's understand what is an interface so interface is a collection of constant and Abstract methods now what is abstract method abstract method us don't have body like they does not have any implementation details present in it let's have a look at sample code of Dow this is an interface whose class name is user da as I said each component has its own annotation so for Dow it is atate Dao which lets you create an interface with all the abstract methods present in it entity is a data class and DOW is an interface clear right now let's have a look at all the abstract methods as I said abstract method means the method without a body so as you can see we have crud annotation with suspend keyword but there is no body right but what is suspense keyword suspend keyword makes sure that whatever the function is that needs to be performed in the background threade for a synchronous database access means that function can be paused or resume without blocking the threade on which it's running all this function needs to be performed on the user entity which we created before that is nothing but the table and columns right see don't focus on each and every line of code because it's just a sample code hence I'm focusing only on the syntax code see as I previously said you don't need to write queries so see we have insert annotation then update annotation and then delete annotation with their respective function but R also provide us to write custom queries using query annotation like this query retrieves all the data from the users table and this one retries only the ID from the user tables got it so we have table in entity and instructions in Dow and now we need to connect both of them through database right hence let's understand the third component that is database it is an abstract class that serves as a main access point to the sqli database and also it connects user entity and user Dow let's have a look at sample code of database this is an abstract class called as user database abstract class is different and Abstract method is different okay so I already explained what is abstract method basically method without body an abstract class is similar like interface which contains mixed methods like methods with body as well as methods without body got it now here it has atate database annotation that declares user entity with its database version and then an abstract class named as app database that extends room database basically it serves as the main entry point for interacting with the database then inside it we have an abstract function that defines an abstract method that is user Dow with no body right this method is used to obtain an instance of the user Dow interface which provides method to interact with the database table associated with the user entity then it defines a companion object and uses create database method to initialize the database see I'm not going to explain it in detail because it's just a simple code to give you an idea about database component right but we will understand it in detail while creating the project okay and that's it I know there was a lot of information to observe but each and every point is very important and also while learning room database we came across so many new Concepts like like interface abstract class abstract method assment keyword annotations right here it is a quick little summary for you pause the video and read it carefully if you want you can take a screenshot of it okay hey everyone welcome back to my channel in this video we will learn about navigation component Library I'll be using navigation in one of my upcoming project hence I wanted to cover it and also it is one of the most important topic when you will deal with back compose it's super duper easy to understand but there are few terms that you need to remember in navigation component okay all right let's understand what is navigation First don't see the technical definition of it just simply answer the meaning of navigation word I'll say to shift from one place to another place basically you can say to navigate from one screen to another screen sounds simple right let's see the technical definition of it it says the navigation component is a library that can manage navigation flow that's what we saw in the above definition right basically it navigates from one screen to another screen and that is nothing but navigation flow got it then it can also manage transition animation look you know how PP works right they move from one slide to another slide and sometimes to make PP more creative we put transition between the slides right similarly to navigate from one screen to another screen in the app you can add a transition between them cool right then deep link deep link is a link that takes you directly to a specific screen within your app and lastly obviously while navigating from one screen to another screen you may have to pass some data that is also possible with the help of navigation so I guess you got an idea what exactly navigation does right so all of these things are managed using destination actions visual editor and components these are all all technical terms in simple language destination is the target screen on which we are supposed to land on then action is basically from which screen to which screen next visual editor is like you know how we have XML editor where we can drag and drop UI components similarly there is a visual editor which will help us to manage navigation flow and then we have three components navigation graph navigation host and navigation controller which we will cover in the upcoming slides Okay so I guess you're pretty much clear about it now if you're aware with Android beginner concept then you might be wondering same things like navigating from one screen to another screen or passing the data that can also be done by using intent then why is there a need of navigation well let me clear that first of all both of them are completely different from each other I'll give you three major points to differentiate first in intent we usually write the target activity class name right but in navigation we Define a part path and a destination that makes the code more organized then second the important point that is intent are usually used for navigating between activities while navigation is used for navigating between fragments if you remember navigation drawer or bottom navigation code there we used to have a blocker a code that represent replace fragment code which consist of fragment manager fragment transaction right but now in advanced and latest project we use navigation then thir point it says in intent we have to manually manage the back stack means what are we supposed to do when back button is pressed while in navigation it automatically handles it clear right moving on to the next slide as I said all this navigation flow is handled by these three components that is navigation craft navigation host and navigation controller let's understand it one by one first is nvra I'll tell like how we have separate menu directory in resource folder similarly we will have a separate directory for navigation which will consist of Nave graph nav graph is like a visual editor where we will have destination screens basically all the fragments present inside it this is where we assign parts and navigates from one screen to another screen but all of this is Possible only when we will have an host as an activity layout means activity XML layout that could be activity main.xml which will act as a name host under which all the fragments will be managed so Nave host is basically a container that we are supposed to add in the activity layout and that container is nothing but fragment container view itself you will understand it better when we will implementing sample project now we have na graph that is hosted by NA host and na host that is controlled by a third component that is n controller which is present in your main activity it programmatically control and na navigates programmatically and it through logic this is all theoretically but everything will be cleared once we will create the example project so let me give you a quick overview so there will be three fragments handled by one activity first fragment will be a welcome screen that has two buttons in it login and sign up button when you will click on login button then it will navigate you from welcome screen to login screen and when you click on sign up button then it will navigate you from welcome screen to signup screen and that's what navigation is I know it's very simple but very important as well there are more Concepts in it like transition deep linking passing the data which I'll cover in upcoming videos maybe in Jetpack compos series but for now let's understand how these three components will contribute see NV graph will consist of all the three fragments with their respective part then all these fragments will be handled by one activity in our project activity main.xml will act as a na host and Main activity will act as a na controller so let's create it open Android Studio choose mty views activity name it as Lear navigation and done let's do the prerequisite first go to colors.xml add red color with hex code AS FF 3131 and done then go to themes. XML add this three lines color primary color primary variant and Android status bar color and then then as it's a Lin screen we will require fancy edit text so let me quickly create it and done then just to make app look more presentable I'll add background drawables and done please skip this step then as it's a library so we need to add dependency so go to grad app here add a plugin then below it add both the dependency and also don't forget to add view binding as well and also as navigation is a New Concept so it requires compile SDK 34 or greater okay do not click on sync now yet then go to gradel build project here add the entire build script also build script should always be at top and plugin should be below it now you can click on sync now and done you can find all the dependency in the description box next as I said we will have one activity that is a default activity main activity and three fragments welcome fragment login fragment and signup fragment so let me quickly create them and done I'll quickly clear all the unnecessary codes from each fragment activity [Music] and done now close all the tabs then let's design all the fragments XML first go to fragment welcome here we will create two button so let me quickly create it and done see linear layout as parent layout then inside it a linear layout and then inside it two button first is to go to login button and second is to go to sment button and that's it next go to fragment signup here we will create two edit text and one button so let me quickly create it and done see two linear layout and inside it a edit text whose ID is sign up username then another edit text whose ID is sign up password and then a button whose ID is sign up button and that's it next go to fragment login here we will copy paste the signup code and done now change the ID as login username login password login button and also change the other required details and done so all the fragments are ready and now it's time for navigation component our first navigation component is nav graph so let's create it right click on resource folder create a new directory keep the resource type as navigation and done then inside it create a new navigation resource file name it as na graph and click okay this is our visual editor remember I said there will be a visual editor where we will add all the fragments with their respective path this is where it is but I also said that everything is handled by host so as you can see over here it says no host found hence first let's assign the host so go to activity main.xml here we assign host and in main activity we assign controller but how do we assign na host to activity main remember I said na host is a container in Pallet section we have something called as containers click on it then keep scrolling till you find n host fragment here it is also an easy way to find it simply search it first remove the default text view now drag and drop new host fragment in the middle of activity main perfect choose name graph which we created before and then constraint it from each side and that's it our host is ready how simple was that let's see how it looks in the code look na host fragment is nothing but fragment container view itself I'll rename the ideas na host fragment container View keep the name as it is and default na host as true also it automatically assigns our na graph and that's it now our na host is ready so let's quickly set up nacra as well also remember this first create na graph file then set up na host and then go back to na graph and set it up for I mean by that is you need na graph file to set up Nave host and na host to set up na graph getting it come back to Nave gra here we will create destination status fragment itself so click on plus sank first choose welcome fragment then next choose login fragment and then next choose signup fragment you can rearrange it as you want also as this is a launcher fragment so assign it as start destination once all the fragments or destinations are created then let's give them a path or actions so can you see a spot here start an arrow from welcome fragment to login fragment and see there is a path similarly we will create another part that will go from welcome fragment to Sno fragment and that's it see so easy right let's see the code this looks kind of complicated right hence design is preferable but still you should be aware with all these terms look the start is destion is welcome fragment okay and inside navigation we have our three fragments that is login fragment sign up fragment and welcome fragment also as you can see login and signup does not have action present in it while welcome fragment has two actions in it because both the path comes from welcome fragment hence it has two action present in it like first action is from welcome fragment to login fragment that is basically an ID and destination obviously as login fragment similarly second action is from welcome fragment to sagna fragment and destination is sagna fragment and that's it so our Nave graph is ready as well as Nave host is also ready and now it's time to set up Nave controller hence go to main activity here we will set up our na controller first declare it and then then create an override function called as on support navigate up here initialize nav controller as find NV controller and inside it mention the fragment container view which we created before in activity Main then return it as Nave controller dot navigate up or super do on support navigate up let me explain it see this line is responsible for determining whether the navigation action should be handled by the Nev controller or by the parent class if navigate up returns true then navigation FL will work as different find but in case it returns false means due to certain reason it fails to navigate from one screen to another screen then in that case it falls back to the default Behavior provided by the parent class got it now once all the three components is successfully set up you can use it in your fragment like I'll show you go to welcome fragment this is where we have two buttons right login and sign up button where each one will redirect to the respective fragment so to do that first we need to set a binding and done this is how we set up binding in fragment then we will write the code between The Binding code here first write binding dot go to login button do set on click listener then when the user will click on login button it will navigate to login screen correct so to do that first let me write the code and then I'll explain and done now see it refers to the view that was clicked in our case that is go to login view then find na controller is a function provided by navigation component it allows you to find the navigation controller associated with the current view or fragment our nav controller is present in main activity right so using fine NV controller it will navigate from one screen to another screen like from welcome fragment to login fragment click on it and see it leads us to na graph this is where the ID is similarly we will write the code for go to sign up button as well it is the view then find new controller and then navigate it from welcome fragment to signup fragment and that's it we are done with the coding now let's run the app see our first screen is welcome fragment then I'll click on login button and here it is login screen then I'll click on sign up button and here it is signup screen I know the project is very basic but all I wanted to show you is that how navigation component works okay hey everyone welcome back to my channel in this video we will learn about Co routines I know Co routines is a very New Concept for you but it is very easy we will understand the basics of Coe routines through an example letter okay first let's see what is co routines Co routines are a concurrency design pattern that allow for sequence IAL execution of task in a non-blocking manner in very simple language Co routines manages multitasking very well by dividing its processes into multiple threads now what is thread thread is like a pipeline where all the processes take place processes as in UI interaction image loading file downloading and all so this is our main thread here all the processes take place now imagine how tough it is to handle so many processes by a single threade the app will lag it will freeze even it can get crashed and that's not how professional app should work right here core routines was introduced to overcome the burden that was put on Main threat but how will it overcome by dividing the processes into multiple threade you can call it co- routine threade or background threade now as you can see we have two threade one is main threade that is handling UI interaction logical operations and arithmetic operations and then there is a background thread that is handling file downloading and image loading the process are divided into two threads which makes Co routin non-blocking because they allow for sequential execution of task without blocking the main thread that ultimately improves app performance and prevent lagging of freezing great right now in core routines there are few terms that you need to understand for which first we need to see how do we create cortin here it is to Implement Coe routines in the app you need to add this dependency then this is a general syntax Coe routine scope dispatcher do io. launch to understand code routines deeply we need to understand these two term scope and its type and dis meure and its type so first let's understand what is scope scope basically determines the lifetime and behavior of Coe routines by executing asynchronous code now what is asynchronous asynchronous in Coe routines means that the task can be executed at the same time without blocking the main thread got it so we have two types of scope first is global scope and second is co routine scope you can use any scope based on your requirement first let's see what is global scope Global scope is not tied to a specific Coe routine it allows task to be executed concurrently means at the same time without being limited by the life cycle of individual Co routines while Co routine scope is is tied to activity life cycle or fragment life cycle means consider coroutines is running and suddenly the app is destroyed means remove from the recent app list then in that case core routines will also be destroyed because obviously it was dependent on life cycle but if you have used Global scope then core routines won't be destroyed because obviously it was non dependent on life site easy right then let's see what is dispatchers very simple definition dispatcher defines which which thread to use for executing the code like main thread or background thread that we need to Define okay there are three types of dispatcher let's see each one of them first is dispatcher default second is dispatcher IO and third is dispatcher main basically which dispatcher are we supposed to use for which process like for CPU based operations such as Computing or sorting algorithm then we are supposed to use dispatcher default then for Io based operations such as Network request or file operations we are supposed to use dispatcher IO that is our background thread then for all the UI related operations like set on click listener or button or set tags we are supposed to use dispatcher main that is our main thread itself got it wait come back to the previous slide look here main thread is handling all the UI related and mathematical operations and background thread is handling all the io related operations like file downloading and image downloading right see default thre is main thread only which is pretty good at handling UI related operations such as set on click listener and all but if you tell main thre to handle file downloading as well then it will be like I can do it tell dispatcher iio or background threade to handle it now let's understand it better with a simple code routine example project okay open Android Studio here is an example project that I created to show you the difference between a app without Co routine and a app with Co routines first let me give you a quick overview this is where we have added the view binding then come to activity main.xml here we have created two processes in the same screen first is counter process which we have to manually update the count by clicking on the start counting button and then second process is where a file downloading will be done of course there is no actual file getting downloaded it's just a demo okay so to create this UI first I have used constraint layout as a parent layout then text view representing process one then another text view which represents the count whose ID is Count number then a button whose ID is Count button then another text view for process two and then a button whose ID is download button got it now come to main activity I have not used score routines yet see we have implemented binding then kept initial counter value as zero then first button is Count button button the logic says when you will click on the count button the count number that is the text view will be incremented by one every time then we have another button which is download button as I said it's not going to download an actual file but it's just a representation of how a file is downloaded like I have used a for Loop whose variable is I that starts from one and goes up to like La then inside it there is a lock tag this loog tag will be visible in lock cat so it goes like we have used tag as a representation for log then inside it a message that says downloading I that will be the number going from one to L in which threade like threade do current threade name represents the threade name in which all this process is happening either it will be main threade or in background threade it will just display the current thread name that's it simple right now remember what I said while explaining it default small thread is main thread that handles all the UI related operations such as set on click listener it will handle it wisely but that is a file downloading process as well that too has to be handled by the main thread but do you think it will be able to handle it let's find out by running the app now see I'll open lock cat so you can see the fake downloading process this is old process so I'll quickly clear it I'll use Tag as a reference then I'll click on start downloading button see how fast it is getting downloaded on the main threade but in the middle of the process I'll start another process as well that is start counting and look it is lagging it is freezing and finally got crashed it was tough for main three to handle two different process at the same time in the same trade hence we will use code routines let's modify the code so go to build. gradel here in dependency add the following Coe routine dependency you can find it in the description box then click on sync now and done we want modify activity main code so directly come to main activity here set on click listener is handled by main thread fair enough but we don't want file downloading to be handled by main thread instead who should handle it of course code routine or background threade so how do we create code routines first is to decide which scope remember Global scope or Co routine scope I'm fine using Co routine scope even if it is dependent on the life cycle so I'll write here as Cod routin scope then I have to decide which dispatcher are we supposed to use as I'm performing file downloading process which obviously means I need to use dispatcher IO so I'll quickly write here and then finally launch will execute the below code so I'll cut paste it and done now this process will run in Main threade and this process will run in the backround threade easy right let's run it look I'll click on start downloading and see here it says the download is running on the background thread simultaneously I'll click on start counting Button as well which is running on the main thread look no lagging no freezing and no crash as both the processes are in different thread hence it is working perfectly fine great right so that's it this was all the basics of Co routines later in future I'll cover Co routines advanced concepts as well okay hey everyone welcome back to my channel in this this video we will learn about retrofit it might sound like a tough topic but trust me it is very simple I'll be releasing this video in Hindi as well on Android knowledge 2.0 channel so make sure to subscribe my second Channel as well Link in the description box now let's understand what is retrofit this is all bookish definition let me tell you what exactly retrofit is retrofit is a library which is used for making Network request and handling API Communication in applications basically it communicates between webs server and application web server as it API now what is API API stands for application programming interface it provides a set of rules and protocols that allow different applications to communicate with each other enabling developer to access and utilize functionality from external services within their own applications in very simple language consider I'm creating an app like Ola where I need map functionality so either I have two options to create my own map API or simply use Google Maps API in my application Google Maps API is an external service provided by Google which we can use in our application API can be free or paid we have several API like news API weather API chat APD API Spotify API and many more they all works in real time means all the information provided by API are live like consider I'm creating a News application where I'll use news API so because of that I'll get all the latest news in my app getting my point now there is something called as rest API let's understand it so rest stands for representational State transfer it's a part of API that basically has a set of HTTP based protocols and principles that defines how system can communicate over the Internet they use HTTP methods or annotations like get post put delete and many more out of which we will mostly use get post and query method get method is used to retrieve the data post method is is used to send data to the server query method is used when we have to specify a particular parameter we will use all of this when we will create project okay I know Theory might sound very boring to you but these are few important terms that you need to know before creating an example project next is Json Json stands for JavaScript object notation it is basically a format in which the data is preserved data is in maybe all the latest news or weather updates got it but code cannot understand Json format hence we are supposed to convert it or in technical language we say pass the data serialize or deserialize it there are many ways to convert Json format to data out of which we will be using Json Library I repeat Json not Json we will add Json dependency in Android Studio that will help us to convert it got it that converted data will be at forj class that is plain old Java object or simply you can say a data class now let's have a look at API as I'm creating an example project only H I'll be using a fake API we will use real API as well in the end of this series but for now this is a popular website Json placeholder do typing code.com that students and developer use to learn API let's go to this website first here it is this is not API this is a website that is providing us an API then where is API these are all the epis that website is providing US Post comments Al to do let's have a look at them now out of all of them I'll be going for album's API album as and song albums let's have a detail look at it here are two things you need to know first is the URL and second is Json syntax this is our URL till here it's a base URL and this one is a endpoint that is basically our API itself see Json placeholder is our main or base URL that provide us an API and this albums is our endpoint that is an API itself got it this is important because in code we have to mention base URL and endpoint to access the service also we can further customize URL as well by categorizing it more but for now just remember this pattern then this is what Jason for formats look alike I know it looks confusing but you will be able to understand it once you are aware with the Json syntax so let's have a look at it also you'll be wondering what is this language so it's let it it won't bother us okay so now see this is what the syntax looks like we have two square brackets in the start and in the end those square brackets is array okay and inside array we currently have two objects in it objects is determined by the curly braces so this is is one object and this is another object both of them are separated using a comma then in each object we have a key and a value separated by a colon both of them are in double quotes this is key and this is value for example this is an array inside it two objects and then inside each object we have key and values this ID is a key and one is an INT value then this name is a key and Android is a string value then in second object ID is the key and two is an INT value and name is a key and knowledge is a string value got it there can be multiple key and values in an object and multiple objects in an array got it now let's have a look at Json format see this square bracket is an array that starts here and ends here in between they have multiple object to be precise they have 100 objects separated by comma and in in each object we have keys and values so in first object we have key as user ID and value as one then another key as ID and value as one then another key as title and value as some string next we have another object with same case but different values and so on so basically we are going to send a request through retrofit to this API or server and as a response it will send us this Json response which will convert it in data using Json library and display it on the text view simple right let's quickly have a look at all the steps so first we will add dependency then permissions then we will create a data class an interface and retrofit instance then from all the above steps we have sent the request and now we will receive it and display it in the text view now let's go to Android studio and create it choose empty views activity name it as Lear retrofit and finish first as I said we will add dependency so go to grle module these are the three dependency I'll mention them in the description box this is for retrofit this is for Json library for conversion and this one is for live data we will use live data to receive the request I have already explained live data in detail in one of my previous video you can click on the eye button to watch then add view binding as well also I do face error with comine SDK so I'll change it to 34 and now click on sync now and done then next next as all of this process is happening on internet so obviously we will require internet and network permissions so go to Android manifest first I'll add Internet permission then next I'll add Access Network State permission and then next I'll add Access Wi-Fi State permission and that's it now we need to create a datab class so right click on it new class name it as album item and choose data class here we are supposed to add keys with their data type that were present in objects and Json I'll keep it side by side see keys are user id id and title right so I'll write here as well ID as in then user ID as end and then title as string simple then I'll add a serialized name to each one of them now what is serialized name the serialized name is an annotation in Json which is used to map a Json key to a data field during serialization or deserialization basically it allows you to specify a custom name for the key if it differs from the data field name to ensure a proper conversion between Json and data safe play then we have keys values we will receive it from server but if you'll have a look at it you will see all these objects are in an array so we are supposed to create that array too right so come back to Android studio right click on it create a new codl class name it as albums as I said we have to create an array list and inside it the object so I'll extend it as array list and inside it our data class that that is album item itself right and that's it now our next step is to create an interface so right click on it create a new class name it as album service and choose interface here we are supposed to define endpoint using https method that is get method so I'll write here as get annotation and inside it write the end point remember I told you about the base URL and endpoint this is our endpoint so I'll write here as slash albums basically get matter retrieves the data right so to retrieve it I'll create a get albums function and as we are retrieving it we will use response class it's a part of retrofit and inside it album class it retrieves a list of albums simple right now next step is to set up retrofit instance it is very easy it's all mostly syntax only so right click on it create a new class name it as retrofit instance here we are supposed to define the base URL and initiate retrofit so to do that first I'll create a companion object companion object consists of Singleton object basically like a static keywords then inside it create a variable named as main URL and insert here the base URL that is the website that is providing the API I'll copy paste it and add then below it we will create a get retrofit instant function that will return a retrofit so first let me quickly write it and done see it will return retrofit with its base URL as the URL we have mentioned above and then Json converter that will con the Json into data and finally build it once everything is set up we will receive the request through live data and displayed in the text view so first we need to give a text view an ID and go to activity M here add IDs title text view because we will receive entire data but we will display only the title for now I'll remove it and done then go to main activity here as I said we will receive the request through live data so let's create it first let's set a binding and done the next we need to initialize the service so let me quickly write it first and done this line creates an instance of an interface that is album service using retrofit basically it enables you to make HTTP request to the SL albums that is our end point defined in the interface then next with the help of live data we will take the response so let me quickly write it [Music] and done now see this code defines a live data that is response live data that emits the response from the retrofit service. getet albums emits as send the response it is typically used for observing and handling the responses then next we need to observe that data so first let me quickly write it and then see this code observes the response live data and upon receiving a response it trads through the list of albums in the response body and store it in the album list variable then if the album list is not null means it is present then use while loop to iterate through each album and store it in album item variable and then for each album it extracts the title and store it in album tit title variable and then finally append it to the title text view append as in to add we usually use append instead of text in web services okay and that's it our code is ready let's run the app perfect all the album title are displayed on the screen see compare it side by side I know it looks messy but it's an example project just to make you understand how retrofit Works further in upcoming videos we will create a professional app using retrofit but for now just remember the steps to implement retrofit okay hey everyone welcome back to my channel in this video we will learn about dependency injection using tagger H the topic is kind of tricky but don't worry I'll try to make it as simple as I can also dependency injection is a very vast topic so one video is not enough for it hence in this video I'll only cover the basics of it later in some other video we will will go in detail about it okay now let's understand what exactly dependency injection is so consider a code where we have multiple classes dependent on one class which makes the entire code tightly coupled tightly coupled means classes are dependent on each other and ultimately it becomes very difficult to manage and test hence to overcome this issue dependency injection was introduced as the definition says that allows the separation of object creation from their usage by making code more modular and testable means it makes the entire project Loosely coupled and removes the dependency from the code also as the last line says by providing required dependency to classes from external sources rather than having to create their own here external sources means using dagger next this is a general diagram where we have class A and Class B here Class A depends on Class B which makes the class B as dependent of Class A okay as I previously said there will be multiple classes depending on one class here for the general example I have only one class depending on another class but there could be multiple classes like Class B Class C Class D depending on Class A got it now next in dependency injection we have two types manual dependency injection di means dependency injection okay and automatic di let's have a detailed look at them so in manual di we create the object manually without using any external resource although it is not recommend to use manual di because we have a better and advanced option available that is automatic di which we will see in upcoming slides but first let's see what are the types of manual di but first let's see what are the types of manual di we have two types in it Constructor injection and field injection injection so in Constructor injection we pass the dependency of a class to its Constructor simple then in failed injection dependency are instantiated after the class is created we will cover both of them practically as well so wait for it but for now let's have a look at automatic di so in automatic dependency injection we have two types dagger and Hil basically in automatic we don't have to create each object for every class instead dagger or Hilt will make it for us and that's what automatic means right hence it is highly recommend to use now let's have a look at each one of them in detail so first what exactly is dagger I kept the definition very simple to understand so it says manual dependency injection can be problematic depending on the size of your project obviously see me having three to five classes depending on one class that is fine to handle right but there will be project where we will have 100 of classes depending on one class now that is difficult to handle right and that's when dagger comes into the picture so basically dagger generates the same code what we would have manually written But Here Comes The Twist that it internally creates a graph of objects that it can refer to provide an instance of a class basically it generates a factory type class that I'll show you when we will create the example project okay now all of this is done using annotations let's have a look at them mod is used on a class that construct object and provide dependencies provides is used on a method in the module class that will return the object inject is used on field Constructor or method to indicate the dependency are requested component is used on a component interface which act as a bridge between module and inject single T is used to indicate only a single instance of dependency object is created and that's it then next is Hilt again it makes a manual dependency injection easy to use by reducing boiler plate code basically Hil provides container for every class and manages their life cycle automatically so we usually use dagger and Hilt together but for now not to make the project very complicated I'll be using dagger only but later in upcoming video we will cover Hilt as well now let's have a look at our example project so this is what a project representation looks like we have one class C and two classes that is Class A and Class B so Class C depends on Class A and Class B which makes them dependent of Class C basically every time we want to access Class A and Class B we need to create an instance of Class A and B in class C that makes it tightly coupled right hence we will be using dger to remove the dependency I have divided the project in four case in first first case we will write the code without any use of dependency injection then in second case we will write the code using manual field injection then in the third case we will write the code using manual Constructor injection and then in the fourth case we will write the code using dagger got it let's go to Android studio and create it so first let me quickly create the three classes that is Class A Class B and Class C and done now in class A it's an example project so I'll be simply printing a line in locket nothing complicated right so here first I'll create a function named as start Class A and inside it log as tag and message as Class A started and that's it similarly I'll do it in class B as well function start Class B and inside it log as tag and messages Class B started and that's it as I previously said Class A and Class B are dependent of Class C so go to class C and this is where we will create an instance of both of them first case without using dependence injection so inside Class C I'll call Class A and Class B and done then we will create a function as start Class C and inside it I'll create an instance of Class A do start class method and Class B dot start class Class B method then write a log for Class C started and that's it see Class A is independent Class B is independent but Class C depends on Class A and B right then lastly call Class C in main so go to main activity I will here call Class C then create an instance of it as Class C dot start Class C and that's it this is what the code looks like without dependency injection I know you will be wondering it looks so easy nothing complicated but think as a professional developer then you will realize this is all tightly coupled which makes your code very difficult to manage and test probably not in this case because there is only three classes but imagine a project with 100 or even thousands of classes that's where all these Advanced topics are used I'll show you the output see in loat we have tag as Class A started Class B started and Class C started that is very basic I'm not going to show output in every case because it literally is same what important is our code because that is different in every case case now let's move to our second case using manual field injection Class A and Class B will be as it is only class C and Main will change so let me quickly comment all the previous code and done now see here as the field injection says dependency are instantiated after the class is created hence instead of making instances private here I'll be using lat in it so let me quickly write it and then lat in it modifier declares a property without initializing them immediately and we will initialize them but not here in main okay and that's what field is right then where means the value can change letter and then similarly from the previous code we will write start Class C function as it is and done then go to main activity here I'll call class instance and then as we have used Lattin it in class A and class B so we need to initialize them over here hence I'll write here as Class C dot Class A is equal to class a object similarly for class B as well and then once it is initialized then start Class C method and done this is what manual field injection look looks like it is not tightly coupled but still there is a lot of code to write hence it is not recommended to use next let's have a look at third case that is manual Constructor injection I'll come on the previous code and done now in Constructor we usually have parameters assigned so Class C is a Constructor and inside it I'll write private well Class A as Class A and then private well Class B as Class B both of them are a Constructor parameters then we will write start Class C function as it is and done now come to main activity here I'll call both the classes instance Class A and Class B then I'll call Class C instance as well but as Class C is a Constructor so obviously it will require its param as well so I'll mention here as Class A and Class B as its parameter then simply call start Class C method on Class C instance and that's it this is what our manual Constructor injection looks like easy right but there is something more easy than that which is dagger so now let's move to our fourth case that is using dagger this is very important so Focus as we are using dagger so obviously we will require dependency so go to graded module here add both the dependency I'll mention them in the description box also as we are using kpt so we will require kept plugin as well so inside plugins mention the Kap plugin then next I'll change compile SDK to 34 and that's it now click on sync now and then go to class A here we will add inject annotation with a Constructor remember I said inject can be used with field Constructor and Method so that's why we'll be using your Constructor so wherever we mention inject annotation it requests for its dependency like I have mentioned inject for class A so it will provide us with class a dependency likewise we will do it for class B as well here I'll add inject annotation with a Constructor and done then go to class C here also I'll mention inject annotation with a Constructor as it's a class where all the other classes are dependent so we do have parameters inside it then write start Class C function as it is and that's it now listen to me carefully to use tagger we need to create a module object and a component interface that we will access in main so first let's create module object right click on it new class name it as class AB module and choose object I'll mention module anot ation here let's have a look at its definition so module annotation is used on class that construct object and provide dependencies in our case it is Class A and class P right then inside it we will create two functions that will return the object and to do that we need to mention provide annotation right let's have a look at its definition it says provides is used on a method in the module class that will return return the object and that's what we are implementing right so I'll mention provides annotation and then create a function called as provide Class A by calling Class A that will return return Class A and that's it similarly I'll do it for class B as well and done our module object class is ready next we need to create component interface we create component interface for the class on which every other class is dependent on so in our case it is Class C right right click on it create a new class name it as Class C component and choose interface here we will mention component annotation let's have a look at its definition it says component annotation is used on a component interface which act as a bridge between module and inject we have already used inject in every class and also we have already created a module object for those injected class right so let's mention it here modules as class AB module and then next inside the interface create a function as get Class C instance that will call the class C and that's it now our component interface is also ready then go to main activity rebuild the project and done remember in start I mentioned about some Factory type clant which dagger uses I'll show you that see here a new directory is created called as Java generated in this directory we have all the factory type of classes basically Factory classes are used to create instance of objects all of them are generated by dagger let's have a look at them you're not supposed to modify or edit it [Music] okay now here write dagger see the component interface will create it own dagger component the dagger prefix followed by a component interface name is a common convention for dagger generated components then dot create method and then dot get Class C instance which will obtain the instance of Class C and then dot start Class C method which will start its functionality which in our case including starting class A and Class B as well and that's it our codee is ready now let's run the app the output will be same only see Class A B C started that's not even the concern Our concern is writing code using dagger I know dagger may seem complex at first but its Advantage become more apparent as your project grows and evolves the benefits of improved code organization maintainability and testability often outweigh the initial setup like you'll be wondering why is there a need of module object then component interface and all it's all extra Goode no they are not they are all your initial setup so that letter your code becomes easy to test and manage it's like working hard in your 20s to leave a stable life in your 30s also I'll be releasing this video in Hindi as well on my second channel so please do subscribe it and for more updates you can follow us on Instagram or join a telegram group Link in the description box so yeah that that is it for the video if you're new to this channel then please consider subscribing to my channel and I'll see you in the next [Music] video
Info
Channel: Android Knowledge
Views: 3,545
Rating: undefined out of 5
Keywords: shared preferences, data binding, view binding, viewmodel, livedata, mvvm, room, navigation component, coroutines, retrofit, dependency injection, dagger, hilt, learn android, advanced topics in android, android tutorials, learn advanced android tutorials, kotlin, java, advance series, android knowledge, android studio, learn kotlin android, database, projects in android, full tutorial, compilation video, learn android studio, learn kotlin projects, create an app, create android app, ui
Id: a_sIiLT-e3Y
Channel Id: undefined
Length: 148min 0sec (8880 seconds)
Published: Mon Nov 06 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.