News App in Android Studio using Kotlin | Android Knowledge

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone welcome back to my channel we will be starting with a new series where I will create a new zap I said series because the project is quite big so it will take around six videos to complete it okay also we will be covering five major Advanced topics such as mvvm retrofit navigation compan component core routines and room database in one single project so I will highly recommend to do a revision of each topic before starting with the project Link in the description box all right let's have a look at the demo this is how it looks I have kept the project very minimal and functional we have a bottom navigation with three categories headlines favorites and search as you can see in headlines all the latest news are shown here all all of them are freshed from news API in real time you can even click on it and see it opens up the article in a web view great right you can scroll through it and also you can save it in your favorite section by clicking on this Floating Action button look it's saved here in favorites not just that but you can also remove it from favorites by swiping it and also you can undo it as well cool right then go to search section here you can literally research anything it will come up with the result see there it is all of this might look very easy to you and it is indeed very easy it just yet we have to write a lot of code for it now let's go into the technical side of it to display all this articles we are using news API which I'll show you later so with the help of that it fetches the realtime data or news and displayed on the recycler view then with the help of web view we can open the article in the app itself without going to any browser then by clicking on add to favorite that particular article gets saved in room database so what you see here this is all saved in room database and SL whenever you will open the app again they will be still here lastly search uses API only and other topics like mbvm will help us to make the project organized and segregate in model view and view model not just that but also navigation component will help us to navigate from one screen to another screen effortlessly so I guess that was a lot of overview now let's dive into the project as this is the first video so we will just cover the prerequisites and XML design later in upcoming video we will implement the logic also I'll be providing you with all the layout design code so that you don't have to waste your time in designing part but don't directly jump onto the code first see how I do it step by step and accordingly you can do it too okay now open Android Studio choose Mt views activity name the activity as the news app and click on finish first let's start with colors so go to colors.xml here I'll add two colors one is purple who's code is 593 c8f second is yellow where a hex code is FFC 00 0 and that's it next go to themes. XML here I'll uncomment this line and write the color as purple then duplicate this line and write item name as color primary varant then next write the item name as Android status bar color and that's it now as we are using bottom navigation so there is a concept called as active indicator which means on whichever fragment we are on the icon will be highlighted with an indicator like this way but by default it's white color and I want it to be yellow hence here I need to create a custom theme for active indicator got it so let me write the code first and then see we have given a name as app do custom. indicator and parent as active indicator obviously then I have set the color as yellow and that's it our theme is ready next our bottom menu needs three icons right so let's add them in the drawable folder first is language which will act as an headlines icon second is favorites and third is search and done next as we will be creating a search bar so for that we will require a border around it so let's create it create a new drawable resource file name it a search border as it's a border so we will create a stroke of Color Purple and with two DP then corners of 14 DP and that's it next as we will be using multiple Concepts like retrofit mvvm room database and many more so obviously we will require their dependencies right let's include them in a grle first go to grle Project I have mentioned all the plugins and dependency in the source code so you can copy paste it from there here class path this is for navigation component then a plugin as Dave tools KSP KSP stands for quot symbol processing it's a better and alternative way of K plugin because it's two times faster than KD when it comes to analyzing the codlin code have a look over here even the official documentation recommends to migr from KD to kscp you can go through it later do not click on sync now okay then go to build gradel module here add KSP plug-in and navigation component plugin then compile SDS 34 then add view binding as well then last lastly add all the dependency and done see this is for view model this is for room database then this is for code routines then for retrofit then navigation component and then lastly for Glide Glide is used for image processing and we have images that needs to be fetched from API so we will require Glide okay okay also if you notice here we have used KSP here and also here both of them are used with compiler because it analyzes and compiles the cotan code and that's it now you can click on sync now and done if you face any shoe over here it's probably because of gred version is different or qul version is different so make sure you have exact values chose all the tabs now let's create bottom menu first create a menu directory and inside it create a menu resource file and bottom navigation menu and then now as our bottom menu has three fragments remember headlines favorites and search and we will create three items so first item is headlines fragment as ID then title as headlines and icon as headlines similarly I will create for favorites item as well and then for search item as well and that's it our bottom navigation menu is ready next we will create all the packages and fragments I'm not going to create all the classes only fragments and packages got it first package is adapters this is where we will have a recycle view adapter class next package is API this is where all the retrofit related classes will be the next package is DB database this is where all the room database related classes will be the next package is models this is where all the data related classes will be the next package is Repository this is all a part of the database related class then we have next package as util this is where the resources will be stored then last package is UI this is where main activity view models and fragments will be next to make the project more readable I'll rename the main activity to news activity always remember to rename using refactor use shift plus F6 for shortcut or through right click menu it's like if you rename a variable directly then only at that particular place the variable name will be changed and everywhere in the code it will remain the same that's a very incorrect approach so instead go for refactor so if you rename a variable it will be changed all over in the project got it also don't forget to change layout name as well and move news activity in UI package inside UI only we will create a separate package for fragments like this way and now inside it we will have four fragments article fragment favorite fragment search fragment and headlines fragment so let me quickly create it and then see we have four fragments with their XML layouts as well I'll quickly remove all the unnecessary code from from all the fragments and done close all the tabs then next to fet or display all the latest news we will require internet so obviously we have to take permissions for it right so go to Android Manu first here ask for Access Network State permission and internet permission and done then next let's design all the XML layouts first let's start with fragment article I'll copy paste the code and then I'll explain you the elements present in it okay and then now see in fragment article we have used web view web view allows you to display the content of website in your app itself so the entire article will be seamlessly displayed using web View and then in that article itself we will have a floating action button so when the user will click on it it will add that particular article into the favorites list got it also please keep in mind with all the idas so that you don't get confused while writing in the code now let's design the favorites fragment as well here copy paste the code and done see there is a text view as favorite title also you are supposed to add popins font otherwise it will show you error how do we add it listen to me click on the text View and we have attributes they search for font family then scroll for more fonts and then there search for popins regular and done then below it a recycler view so whatever we save in our favorites list it will be displayed in the form of recycler View and that's it now as we are using internet display the new so there are chances of internet connectivity issues or maybe no internet right so to handle that we will create an item layout for all the internet errors like you can click on the button to refresh it hence I'll create a new layout resource file named as item error and copy P the code and done now see here is a text view which says no internet and a button that says pretry we will handle them logically in the code next go to fragments headline I'll copy paste the code and done now see here we have a text view as headlines title then below it a recycl view or all all the Articles will be display then if the user has internet problems and recycl view is not able to display news article then in that case we will include our item error layout which we created before I hope you're aware with the fact that we can include other layouts using include tag then lastly we have a progress bar as we will be using pag ination which basically loads or display the data or articles one set at a time so there will be a seconds of gap before displaying another set of Articles hence to fill that Gap we will be using progr bar as loading bar and that's it next go to fragment search. XML I'll copy paste it and done now here we have a text view as search title then below it an edit text that will act as a search bar and also we have given a background as search border which we created at the start and then below it a recycled view that will display all the search resultant then here also we will include arror layout in case user runs out of internet and then a program SP to fill that Gap during pagination and that's it next as we have created recycler view so obviously we will require an item layout for it so create a new layout resource file name it as item news and I'll copy paste the code and done now see here we have an image view that will display the article image then we have a text view which will display the source of news basically like the newspaper or the news channel then another text view as article title the next text view represents article description that will display only two lines in the recycler view item the next the next text Will represents article date and time when it was published and that's it see this item layout is for Recycler view not for the article article will be display on web view the way it will be display on the website we are not providing them with any layout we are just providing them web view got it I know some people will have confusion about it so hence it was necessary to clear it now moving on to the last XML layout activity news this is where fragment container and bottom menu will be attached so let me copy paste the code and done see we have a frame layout and inside it we have a fragment container view that represents the Nave host fragment as I said we will be using navigation component from navigating from one screen to another screen and we will require n first fragment this shows errors because we have not yet created n graph we will create it later then outside the frame layout we have bottom navigation view where I have attached bottom menu and also if you can notice here I have attached custom active indicator style as well which we created in themes right it is not shown here but it will be visible at the run time and yeah that's it now let's create na graph so create a navigation directory then inside it create a new sve graph and done now look here carefully we have a na host present here then here add all the destination or [Music] fragments and then so we have headlines favorite searge and article now the navigation flow goes like this way that each one of them means headline search and favorite it will eventually open article fragment like all of them have a recycler View and all of them have articles in it and all of them will open that articles right so flow will go from headlines to article same way flow will go from favorite to article then same way the flow will go from search to article and that's it easy right I'll quickly rename it and also make sure start destination is headlines fragment now with the help of argument tag we can attach the data to that particular fragment which we will do it later in the upcoming video this is all prerequisite so you must be confused like what is this what are we doing but don't worry you will understand it once we will start writing the code all right now only last thing that is left is API key where do we get this API key from so every API has its own key which is private you're not supposed to share it with anyone and with the help of that key you can access the data as we want news data so there are varieties of news API available on internet out of which we will be using news API I'll mention the link in the description box this is how the website looks like it's free easy to integrate and widely used just to show you we also have another famous news API called as G news if you want you can use it too but as a beginner follow me so best part about news API is that it provides with a lot of customization like country language Publishers or the timings you will know when we will Implement retrofit now let's focus on API key as a new user click on get API key fill in all the details like name email and password and select I an individual and submit it then at the end it will provide us with an API key so make sure to keep it safe and saved and also you will get the API key on your email too and that's it all our prerequisites are done now in the upcoming videos we can write the code without any interference and that's where the real logic begins so stay tuned for that okay also for more updates you can follow us on Instagram or join the telegram group Link in the description box 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 continue with a news app Series in previous video we have covered prerequisits and XML design so if you have not yet watched it I'll highly recommend you to watch that first and then hop onto this video now in this video we will cover mostly retrofit part like connecting API with our app and converting Json data and all okay but before starting with that let me give you a quick recap of our previous video so in our previous video we have added all the dependences and plugins in grer then we have designed all the XML layouts bottom navigation menu and nacra then we have added permissions in manifest and also icons in the drawable folder then colors themes and segregating all the packages and then last but not the least we also downloaded our API key from the news API website and that's it you can find all the prerequisite source code in the description box all right now let's begin with the logic path so first open the news API website make sure that you are already logged in then go to documentation now see we have two options either to display all types of news or to display only the top level news I want to display only top headlines which are popular H go to top headlines here see it says this endpoint provides live top and breaking headlines for a country or category now listen to me carefully this is very easy okay see we send requests to AP via URL and in response it send us the result simple this is a request and this is our result and also this is a Json data let's quickly do a revision of Json synx this is what it looks like we have square brackets that is array and inside it curly braces that is our objects each object has key and a value separated by colon and then then each object is separated by a comma easy right now in this response you can see there are objects in it like status article source author title description and all so let's have a look at each response object definition so first one is status it checks if the request is successful or not okay means all good and if any error occurs then it will show a code like maybe 404 which denotes web page not found then we have total results which means the number of results available for the request then we have articles which means the news itself then inside articles array we have other objects such as Source author title and all out of which source has two values in it ID and name of the source source means from which newspaper that news came from got it then we have author title description Ur URL to image published add content all of these terms you already know but there are few terms you need to know like description is like a summarized news and content is the entire news then publish at is the date and time of the article when it was published and URL to image is basically the image converted in a URL format and that's it now we need Json data right but this Json data can be read by compiler so we need to convert it to data class so what we will do is open Android Studio go to files then settings and then plugins here install a plugin known as Json to cotl class this plugin will make our work 10 times easier I'll tell you how so traditionally we used to create response data class on our own that is too much of work but now all we need to do is to go to news API website here copy this URL of top headlines make sure to exclude get and then paste it this is what the actual Json data is I know it's not formatted but that's okay because our plugin will do everything for us so all you have to do is press control+ A and control+ C to copy the entire Json data and now come to Android Studio here right click then new and then cotlin class from Json click on it here pays the entire Json data which we copied before see it's not formatted so click on this format button and look everything is formatted so now this plug-in will take this response and automatically going to generate three classes for us why three because see here first class will be for this three objects article status and total results then second class will be for objects that is present in articles and then third class will be for the objects that is present in Source got it now all of this is response only so I'll name it as news response and then I'll click on generate and see we have our three classes ready also all three of them will come under models package because obviously that is a data right not database I said data and data is nothing but modeling itself this is news response data class in which we have articles status and total results here make sure to change the list to mutable list mutable means flexible or the values that can be changeing letter then click on article so you will be redirected to our second class that is article data class in which we have other attributes like author content description and many more then Source also has values in it so click on it and you will be redirected to our third class that is Source data class in which we have ID and name and that's it see the Json data code which we copy pasted in plug-in that only retrieves the object from the entire Json data not the data itself like I know as a beginner you might have confusion that we are retrieving the entire data but no we are not instead the data is live and real time that is directly provided from the requested URL which we'll be going to use got it next as article is a data class so we need to attach it with its respective fragment in navigation graph so go to news NV graph here in artical fragment we will create an argument tag and inside it name as article and argument type as article data class copy the reference path and paste it and that's it also you will face error in name but that's not your fault instead it's just a bug in Android studio giraff version so don't worry it won't affect your code next we need to create few constant values that will never we going to change so for that create a class under U name it as constants now inside it we will create companion object companion object is basically a part of the class so whatever we write in it that can be accessed anywhere in the class it's a good practice because there will be few terms that we need to keep using so we can't write it every time instead just mention it over here and letter you can access it anywhere in the code for example API key we will require API key for the URL right hence we will create a constant value of it as API key and copy paste the API key as it is then next is the base URL base URL means the website URL of API not the API URL okay so in our case it is news API and simply copy paste the news API URL here and done then third is search news time delay as 500 long which means in a search operation that will be a delay of 500 milliseconds between consecutive search request then next is query page size as is 20 which means the number of articles that will be fashed on a single page and that's it these are the four constants that we will access whenever required okay next is very important news API so inside API package create an interface name it as news API and done so we have already created our response and now it's time to create our request that is our URL so in API we need to F two kind of data first is the top headlines that will be displaying headlines fragment and second is everything means common news for search purpose okay now to fetch something we will use get annotation and inside it from where to fetch basically the end point of the URL so in our case the end point is is V2 /tp headlines so copy paste it then we will create a suspend function named as get headlines and inside it we need to customize our URL like from which country we need the news from or maybe from which particular Source we need the news from got it see these are all the customization or in technical language request parameters you can do with the URL look over here here is the pce URL this is the end point and then from here after question mark the customization starts so we have different request parameters such as apik which is mandatory then we have country customization these are all the country codes available like if I want the news only from India then I'll use ion and if I want the news only from USA then I'll use us code got it there is a list of country code available on on the internet so you can find it accordingly then we have categories such as business entertainment health and all like I have a look at this one we have top headlines from the country de that is code for Germany and category as business and then API key all this customization are separated using and operator then next we have sources means from which particular newspaper you want news from but you can't make country or category with Source while customizing the URL got it then Q is for the keywords like for example if I write in my URL as Q is equal to stocks then all the news related to stocks will be displayed and this cue will be required when we'll create a function for search the next is Page size which is the number of results per page that we have already set to 20 as default then page is used to go through different pages from the results only if the page size is greater than its results now using all of these parameters we will create a customized URL of Our Own in which we will have an API key obviously then we will have country as us and then page very simple URL how will we create it see as we are customizing the URL so we will we use Query annotation here so I'll write query as country then create a parameter as country code and keep the default value as us next I'll create a query for page and then create a parameter as page number and keep the default value as one which means by default page number one will be called got it then next I'll create another query as API key and then create an API key parameter and here mention the default API key value which we created as a constant and that's it lastly after taking the request it will return as a response that is a news response this response class is used to handle HTTP responses similarly we'll create a customized URL for search as well but in this case the fing of data should not be limited to top headlines instead it should be everything okay then create suspend function for search and inside it query SQ that represents the keyword and then search query as a parameter next query is Page whose parameter will be page number as one and then obviously an API key that is our constant value of API key and that's it again in in return it will give us a response as news response and our news API is also ready now last but not the least is to set up retrofit this is easy because it's all syntax only so under API only create a new class as retrofit instance and then inside it a companion object means whatever we write inside it it will remain static or fixed values in our case it is used to create a Singleton instance of retrofit now what is Singleton Singleton is a class that is limited to instantiation to a single instance only means in simple words it can be only instantiated once then let me write the code first and then I'll explain you [Music] and then now see what is by lazyy by lazyy create a lazily initialized retrofit instance means that the instance will only be created when it's first exist and then subsequent exess will reuse the existing instance got it then inside it a HTTP logging Interceptor is configured to log HTTP request and response detains then an okay HTTP client is created with this this Interceptor then finally a retrofit Builder is used to configure the base URL then Json Factory conversion then set the okay HTTP client and lastly build the retrofit instance next I have created another lazy property named as API which creates an implementation of the news API interface using retrofit instance and that's it our retrofit part is also done now in next video we will cover database part so stay tuned for that okay so yeah that is it for the video If you 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 continue with our news app in the previous video we have set up retrofit so if you have not yet watched it I'll highly recommend you to watch that first and then watch this video now in this video we will cover mostly room database part like creating database and writing queries okay but you will be wondering why is there a need of room database because we'll be saving our favorite news article in the favorite tab which means we'll be storing the favorite news articles in the database so that when we open the app for the next time then all the favorite articles should still be present in the favorite tab got it now let's begin it first go to article if you remember this was a Json data that was converted into article data class right basically this is a article only like a template so when we save an article in favorite then all the parameters present inside it like author content description and all are also save as stable columns but very stable that we will create now but before that Let me refresh your memory room database consist of three components and entity Dow that is database access object and database so entity defines data structure Dow provide method for data access and database serves as a main access point got it we will create classes for all three of them so first let's start with entity entity represents a database table including its columns data types and primary key now we already have an article data class in which all columns with its data type is present so all we need is to create an entity that is database table and a primary key so let's create it first above article data class mention entity annotation and inside it table name as articles and done then we need to add primary key for that we will require a unique column that will be a ID so first I'll create an ID as int question mark is equal to null which means ID can hold an integer value or a null value now I'll set primary key on it and make sure to keep Auto generate as true which means that the database will handle generating unique values for it and that's it our entity class is ready now let's move to our second component that is Dow see Dow is an interface that provides abstract methods enabling crud operations like create read update or delete so let's create it first right click on DB package and create a new interface class name it as article Dow and done so here we will Implement all the database queries such as insert query select query and delete query these are the three database operation that we need to perform on the favorite article like adding to favorite means insert query then to display all the favorite articles means select query then to delete a particular article means delete query easy right now let's implement it here I will write da annotation that will Mark the interface as a data access object and then further let me write the code first and then I'll explain you okay and done now see insert annotation is used for inserting data into the database simple right then what is this on conflict so on conflict strategy. replace means if there is a conflict like if same time key already exist in the table then the old data will be replaced with the new data it's basically a safe way of writing code so that we don't face any error in future then we have created a suspend function named as upsert that inserts or updates an article in the database the suspend keyword indicate that this function should be called from a CO routine then lastly it returns long which typically represents the primary key of the article next is to display all the favorite article so for that I have used query annotation with a query as select star from articles articles is the table name then I have created a function as get all articles and written type as live data containing a list of all articles in the database simple right the next is delete annotation it is used for deleting data from the database then again we have created a suspend function as delete article which will delete an article from the database and suspend will make sure that the database operations are performed on a background threade and that's it our Dow interface is also ready next again go to article here as you can see int data type is supported by database fine string data type is also supported by database that is also fine but Source data type is not supported by database because Source itself is a object so what we need to do is to convert it to a data type that is supported by the database and that is nothing but type converters type converters is used to convert complex data types which are not supported by database into a format that is supported by the database got it hence to do that first we need to serialize the entire data class now what is serialization serialization is the process of converting an object into format that can be easily stored or transmitted so I will write here as serializable then we need to create a type converter class so right click on DB package and create a new class name it as converters here we need to create two functions from source and to source so first let me write the code and then I'll explain you and done now see to tell compiler it's a converter class we need to mention type converter annotation here then I have created a function as from source which will convert Source object into string now if you'll see here in Source class there is two values in it ID and name out of which we don't really require ID but we do required name so come back to converter class here we will convert only source name name this function will be used when storing a source object in the database then next function is two Source here we will convert name String into Source object which will create a new source object using the provided name and as we are not using Source ID hence I have mentioned Source name twice basically this function will be used when retrieving a source object from the database and that's it now let's move to room database third component that is database database serves as the main access point and also it defines the database version and entities so let's create it right click on DB package and create a new class name it as article database and then here we need to create and set up the database so to tell the compiler it's a database class here we need to mention database with annotation and inside it entities as article class and version as one then it is very necessary to mention converter class in the database hence I will write here as type converters annotation with its converters class and done now listen to me carefully we will make this class as abstract class because we will be creating an abstract function in it later then as this is the main access point of the database so article database will extend room database now inside it I'll create an abstract function as get article Dow which declares artical Dow interface abstract function basically has no body in it then we will create a companion object so whatever present inside companion object is static and can be accessed anywhere in the code using its name then inside it it's mostly syntax only so let me write the code first and then I'll explain you [Music] and done now see volatile annotation ensures that changes made by one threade are immediately visible to other threads an instance variable holds the Singleton in instance of the article database or null then this is a lock object which is used to synchronize the database creation process basically this block ensures that only one threade can execute the code inside the block at a time got it then this is a custom invoke operator for the companion object basically it allows you to create an instance of article database by calling article database context in workk function follows the a single turn pattern ensuring that only one instance is created then this line checks if the instance is already initialized if not then it enters a synchronized block using lock object to ensure that only one threade can create the database instance at a time then inside the block again it checks if the instance is still null and then creates the database using the create database function I know you will be wondering why is there a need of invoke operator function in all because inoke operator is used for Simplicity when creating an instance and also double check locking pattern is Implement to ensure threat safety during database creation process lastly I have created a function as create database it is responsible for creating the article database instance using database Builder method then it also specifies the database class database name that is article db. DB then finally build it and that's it our room database part is also done now in next video we will set up our adapter so stay tuned for that 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 continue with our news app in previous video we have set up room database so if you have not yet watched it I'll highly recommend you to watch that first and then watch this video now in this video we will cover adapter and repository part okay so let's create it open Android studio right click on repository package and create a new class name it as news repository and done now what's a general meaning of repository it means a place or a container where something is deposited or stored right same we will be going to do in this news repository with the help of article database and retrofit instance which we created before okay so I'll write here as well DB and declare article database class then inside it I'm going to create five functions get headlines function search news function upsert function get favorite news function and delete article function we have already created these five functions but this time we will call all of them as methods in their respective function so first we need to call get headlines method that is present in news API with its parameters as country code and page number so let's create it and now see suspend make sure that all this operation is running on background trade then we have a function as get headlines with its parameters as country code whose data type is string and page number whose data type is int and then inside it I have called the get headlines method which is present in API and that API is present in retrofit instance see if I click on it it leads me to news API interface and this news API inter interace is called in retrofit instance over here hence the chain goes like this way and then all you have to do is pass the arguments basically this function uses retrofit to fetch headlines based on country code and page number arguments got it then next we need to call search news method that is again present in news API with its parameters as search query and page number so let me write the code first and done now see here we have parameters as search query and page number then I have called the search for news method from news API through retrofit instance and pass the arguments basically this function uses retrofit to search for news based on search query and page number arguments the next method that we need to call is upsert function present in article Dow with its parameters as article so let me write the code first and done now see I have created an upsert function with its parameters as article and then call the upsert method that is present in article Dow and that article Dow is present in TB that is basically an article database and then we have passed the arguments as article okay see we are not creating any logic here we are just calling those methods which we created before got it then next we will call get all Artic function which does not have any parameters inside it so first let me write the code and then now see I have created a get favorite news function with no parameters which is equals to here I have called the get all article methods that is present in article Dow through article database simple right then next we will call delete article function that is present in article now with article parameter so let let me write the code first enter now see here I have created a suspend function as delete article with article as a parameter which is equal equals to here I have called delete article method from article Dow through article database and pass the arguments as article and that's it our news repository is ready you can press control and click on this method and do backtracking to know where it comes from okay next we need to create an adapter class for a recycler view which we have used in all three fragments so to do that right click on adapter package and create a new class name it as news adapter and done here we need to create view holder then adapter functions and then on item click listener so let's create it first we need to extend it as recycl view do adapter and inside it news adapter dot article view holder then we will create this article view holder class here as inner class article view holder and Constructor parameter as item view that is view itself now what is inner class inner class means they have access to the members of the outer class okay okay then it extends recycler view Dot View holder and pass the argument as item view see the primary purpose of view holder is to hold references to views within an item layout to you know avoid repeatedly calling fine view by ID got it then here declare all the UI components that we have used in item news layout see here such as article image article source and many more so I'll write here as lead init where article image as image view then same way I'll declare other components as well and then see we have article image article source article title article description and article date and time okay next implement the three members and done so we have on create view holder get item count and onbind view holder let's start with on create view holder let me write the code first and done see here at the end it will return article view holder obviously which means it will return item news layout only that I have initialized here as layout inflator inflat as item news layout got it then next is get item count but before proceeding with that we need to set up a diff util and Ayn list differ now what are these complex words it's very easy basically both of them are used together to efficiently update the contents of a recycler view without refreshing the entire data set at first it may look very difficult but it's very easy to understand so let me write the code first and then I'll explain you and done now see this is an differ call back implementing diff utin do item callback interface this interface is used by diff util to determine the difference between two list this method are items the same is called to check whether two item represents the same object in the article data class here it checks if the URL property of the old and new item is same basically this is used to determine if an item has been moved in the list or not similarly this method R contains the same is called to check whether the contents of two items are same in the article data class here it checks if the entire objects are same basically this is used to determine if an item's content has been changed then this line creates an a syn list differ instance using differ call back which we created right basically a syn list differ determine differences between two list on a background threade which helps in smooth UI update and that's it if you find it very complex it's okay give it some time and also try researching it on your own okay now let's move to get item count here it will return the size of list and that list is a part of differ only so I'll write here as written defer do current list do size and done next let's write the code for onbind view holder but before that we need to declare a variable named on item click listener this variable is a nullable function type that takes an article as a parameter and returns unit unit means a function that does not return anything basically this is used to set up a call back for item click events which we will implement it okay then come inside the onbind view holder here we will initialize all the UI components which we declared before so first let me write the code and done now see it retrieves the article object at the current position from the list managed by the async list differ basically this is the data that we want to bind to the Views then we have initialized all the UI components with the help of holder let me delete extra so we have article image source title description and article date time associated with its UI components then I have binded the data with view like this are all the view and this are all the data okay then we have used Glide library to load an article from the URL to image into the article image view then I have set the source name on the article source View and similarly for title description and published ad means all the data set on their respective UI components got it next I have set on click listener on the entire item View using item click listener which I created before so if any of the item above is clicked then it opens up the article lastly we require this item click listener for all the other fragment recycler view right so for that I'll create a function as set on item click list now that takes a parameter as listener and then further it takes an article as its parameter and return return unit means return nothing then inside it same on item click listener method which we created before will be assigned to our listener parameter basically this function allows external classes to set their own click handling Logic for items in the adapter got it and that's it our news adapter class is also ready now next we need to set up a resource class which is basically a prerequisite for view model so let's create it right click on your deals package and create a new sealed class name it as resource and now what is sealed class sealed class often restricts the hierarchy and in our case it represents the different states that can occur when fetching the data from a remote Source got it different states as in success state or error state which we will be using in fragments and we model later okay so let me write the code first [Music] and then now see we have declared a sale class as resource with a generic type parameter as T then this property holds the data of type T and is nullable basically it represents the result data of the operation that could be success or error then next we have message variable that is used to store an eror message in case of error then inside it we have three classes success error and loading all of them with its parameter as t so first class is Success class which is a subass of resource representing the success State basically it has a Constructor that takes the data that is the result data and passes it to the Super class that is resource then second class is error class which is also a subass of resource representing the error State basically it has a Constructor that takes an error message and result data and pass them to the super class that is resource then third class is loading class which is again a subass of resource representing the loading State basically it does not have any property all it does is to indicate the super class that data is still being feted and that's it I know few Concepts were very new to you so it might look very difficult and that's completely okay but once the project is ready then you will realize why resource class was required why diffu was used and everything so don't worry about it okay now next we video is very important video where we will set up our view model class so stay tuned for that okay so yeah that is it for the video if you're 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 continue with a news app in previous video we have setup adapter and repository so if you have not yet watched it I'll highly recommend you to watch that first and then watch this video now this video is one of the most important video because we will be covering view model and view model Factory part and also this is our second last video of the news app series okay so now let's create it open Android studio now view model is a part of mvvm that is model view and view model so out of which we have already created model then we are about to create view model and then view we will be creating in next video got it I have already explained mvvm in detail in one of my previous video which you can watch by clicking on the I button but still let me quickly refresh your memory see view manages all the UI related activities such as design part or handling UI components in fragments or in activity then model manages all the data related activities such as to set up database maybe from local data source such as room database or remote data source such as retrofit and then view model manages all the UI related data activities basically it act as a mediator between View and model for communication not just add but it also manages all the logical part and that's it now come back to Android Studio here in UI package only we will create a view model class if you want you can create a new package for it okay so right click on UI package and create a new class name it as news view model and then here we have to create literally 10 functions I know it's quite a lot but this is where the real logic begins don't worry it's super duper easy to understand if you know little bit about view model okay so now let's create it step by step first step is to declare all the required variables I'll write variable as headlines whose data type is mutable live data that holds the resource class which we created before and use response for displaying headlines then I'll create another variable as headlines page to track the current page number for the headline page ination and then another variable as headlines response to store the last received response for headlines next I'll write search news variable as mutable live data again same resource of type news response for displaying search results then search news page variable to track the current page number for search result pagination then search news response variable to store the last received response for search results then new search query variable to store the new search query and then old search query variable to store the previous search query and that's it next we will add parameters AS application and news Repository and extend it as Android view model now we will create our first function as handle headline response so let me write the code first and see first it checks if the net Network request was successful if successful then increment the headlines page if headlines response is null then assign it the value of result response otherwise merge the new articles with the existing articles in headlines response then return a resource success containing the updated headline response but if the network request was not successful then return a resource error with the error message from the response next we will create another function as handle search news response in a similar manner so let me write the code and now see again it checks if the network request was successful if successful then check if search news response is null or if the search query has changed if true then reset the page count to one then update the search query and assign the result to search news response else increment the page count and merge the new articles with the existing one in search news response then return a resource success containing the updated search news response and lastly if the network request was not successful then return a resource error with error message from the response simple next we will create another function as add to favorite so let me write it and done this function takes an article as a parameter representing the article to be added to favorites then view model scope. launch is a CO routine Builder used within a view model to launch a core routines that is automatically cancelled when the view model is cleared or destroyed basically it helps to manage the co routine life cycle then lastly I have call a function upset on news repository that will update or insert an article next I have created another function as get favorite news there is no parameter in it all we have to do is to call get favorite news method from news repository and that's it then I'll create another function as delete article very similar to add favorite function but here we will call delete article method from news Repository and done next I'll create another function as Internet connection that will check if our device has active internet or not so let me write the code and done now see connectivity Services retrieves the system service for Connect it and cast it to a connectivity manager then get network capability gets the network capabilities of the currently active Network then I have wrote question mark dot that is save call operator and run extension function to execute the specific block only if the expression on the left is non null and if get network capabilities is null then the entire expression evaluates to false so when expression checks the network capabilities and returns through if any of the specified transport types such as Wi-Fi cellular or ethernet is available but if none of the specified transport types are available then it returns false and that's it next we will create another function as headlines internet which will check internet connection specifically for headline speech so let me write the code and then now see we have a suspend function headlines internet that Fates headlines based on country code then resource loading poster loading state to the headlines live data indicating that a network request is in progress and then it checks if there is an internet connection using the internet connection function which we created before if there is an internet connection then response will store the headlines fetched from the repository and post the result to headline SL data after processing the response but if there is no internet connection then post and addor state to the headline SL data then catch keyword catches any exception that might occur during the network request and when expression handles a specific type of exception like IO exception indicating unable to connect or for any other type of exception it post an error indicating no signal next we will create another function as search news internet that will handle internet connection specifically for search news so let me write the code and done now see search news internet function is similar to headlines internet function so this line updates a new search query variable with the provided search query then resource loading post a loading state to the search news live data indicating that a network request for search news is in progress then it checks if there is an internet connection using internet connection so if there is an internet connection then it fetches search news from the repository based on search query and post the result to the search news live data after processing the response but if there is no internet connection then it post an error state to search news live data as no internet connection then catch block is same as previous function and next function is get headlines host parameter is country code then launch the view model scope and inside it call the headlines internet method which we created before and pass the argument as country code same way create another function as search news most parameter is search query and inside it call search news internet and pass the argument as search query and done then last thing is to call get headlines method which we created just now inside in it block and pass the argument as us as the country code and that's it our view modern class is ready next is to create view model provider Factory so right click on UI package and create a new class as news view model provider Factory and so here I'll pass the parameters AS application and use repository then extend it as view model provider do Factory now what is view model provider Factory basically view model Factory is a class that instantiate and return view model simple and then inside it let me write the code first and done so this function is required to create an instance of the view model class basically it overrides the create method from The View model provider Factory interface then inside it it returns a new instance of the news view model by passing the application and use depository instances to its Constructor this ASD is used to ensure that the written instant matches with the generic type D which we called before and that's it our news view model provider Factory is also ready next go to news activity here we will set up view model provider Factory as well as Nave controller so first let me declare news view model and done then let me quickly set a binding and done now first is to set a view model so let me write the code and then now see we are creating an instance of news repository by providing it with an article database instance means news repository class requires an article database as a dependency then we are creating another instance of custom news view model provider Factory by passing the application and previously created news repository then lastly we are using the view model provider to create an instance of news view model then this parameter indicates a news activity itself and then view model provider Factory is used to create the instance and that's where we specify the class of view model we want that is our news view model and that's it basically this setup ensures that news view model is created with the appropriate dependency such as news repository and the article database and also the use of view model provider Factory allows you to provide the custom Logic for creating a view model instances which can be beneficial at the time of testing now next is to set up nav controller on our bottom navigation view which we created before so let me write the code [Music] and then now see we are finding the new host fragment using its ID news nav host fragment from the support fragment manager and as na host fragment cast is used to obtain a reference to the Nave host fragment instead then we are retrieving the na controller associated with the Nave host fragment basically the na controller is responsible for handling navigation within the fragment and then lastly we are setting up the NV controller using setup with NV controller on bottom navigation so basically it will be aware of all the navigation action defined in a na graph it's like when you select an item in the bottom navigation then it triggers the corresponding navigation action in our app and that's it our news activity is also ready now in next video we will set up our fragments so stay tuned for that 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 and welcome back to my channel in this video we will continue with our news app in previous video we have set up view model so if you have not yet watched it I'll highly recommend you to watch that first and then watch this video now in this video we will be covering fragments and also this is our last video of the news app series okay so now let's create it open Android Studio we have already created all the fragments that is article fragment headline fragment favorite fragment and search fragment so first let me quickly remove all the unnecessary Cod from all the fragments like this way and done I'll do the same thing for other three fragments as well and done now let's start with article fragment first I'll mention the XML layout file here then inside it we need to implement three things declare variable override on view created function and set up Floating Action button got it but listen to me as as this is an article fragment so here an entire article will be displayed in a web view hence we will write the code for web view which will be present in on view created function so first let's declare all the variables okay so all your responses API everything is connected in view model only so it's a must to declare news view model then if you remember in part three I guess we have created an argument tag in news Nave graph inside article fragment that we need to access here as well arguments then article fragment Arc this is an automatically generated class by safe arguments plugin basically it will help to pass arguments between fragments in a safe way then by NA ARS means n AR navigation AR is an extensive function provided by navigation component and it is used to retrieve the argument passed to a fragment so whenever we will use ARS in the code it means that we are accessing the arguments passed to the fragment got it then next we will create an override function as on view created where we will initialize our view so for that we will use finding so let me quickly set it up and done this is how we declare and initialize binding in fragments got it now inside on view created we will set up web view so to do that first we need to initialize news view model and done then I'll initialize article variable as ARS do article this article is the name given to the argument then call the web view through binding and use apply function then inside the apply blog here we will set the web view client for the web view so web view client is responsible for handling various events in the web view such as as when a new URL is about to be loaded then article. URL with a safe call operator and the let function basically the let function is used here to execute a block of code on the non null that is article URL safely then inside the Le function load URL and argument as it me article fragment itself and then now below it I'll set on click on Fab which will add the article to favorites in technical language it will insert the favorite article in the database got it so first access FB through binding then set on click listener on it and then inside it we need to call add to favorite method which we created in view model so for that I'll write news view model dot add to favorite method and pass the argument as article simple then to inform the user that article has been added to the favorite we will create a snack bar if you want you can simply create a toast as well not a problem and that's it our article fragment is ready now next we need to create headlines fragment there is a lot of code to write here basically here we will set our recycler view with all the Articles fetched from API not just that but we also need to handle pagination as well as progress bar and error message so first let's declare all the variables and then see we have news view Model news adapter then we have retrive button and error text both of this UI component is a part of item error layout and that item error layout is exist in fragment headlines as item headlines error so in case of any internet error this UI components will be used got it then I will overwrite on view created function and inside it let me quickly set a binding and then then inside on view created function we need to initialize as well as to fetch data from API through live data but to do that we will require few functions so outside on view created function we will create other required functions and then later we will call all those function inside on view created got it before creating those function we will require few Boolean variables such as is error as false is loading as again false then it last page also has false and then is scrolling also as FAL and then we will use all these variables in functions so let's create our first function as hide progress bar there will be a situation where we will require to hide the progress bar once the loading is done so for that call pagination progress bar do visibility as invisible then is loading as false and then next we will create another function as show progress bar where we'll display the progress bar this will be the situation where a data is getting fetched and in that situation we will require a loading or a progress bar hence here I'll keep is loading as true the next function is hide error message this will be required when internet is working perfectly fine and hence we will keep the error messages invisible the next function is show error message this will be required in case of any error where error message will be displayed on the screen got it next we need to set up pation I have already explained what is pagination but still it helps you load and display small chunks of data at a time so to create it write well scroll listener as object and extend it as recycler view dot onscroll listener now inside it there will be two methods onscroll and onscroll state changed onscroll method will be called after the scroll is compl completed and on scroll State change method will be called when the scroll State changes so first let me write the code for onscroll method and done now see we have an error over here because query page size should be integer hence it should be not in double quotes So remove it also same goes for this one too and now see error is gone then this block retrieves the linear layout manager from the recycler View and gathers information about first visible item the count of visible item and the total item count then it defin several conditions like is no error and is not loading and not last page that must be satisfied for pag inition to occur then based on these conditions it determines whether pagination should happen if should paginate is true then it triggers the get headlines method of the news view model and updates the state by setting is scroll to false and done then let me quickly write on scroll State change method as well and then now see the new state parameter represents the new scroll State then scroll State touch scroll indicates that the user is currently dragging the screen causing recycler view to scroll then if the condition is true then it set the it's scrolling to true and done next we will set up headlines recycler view we have already created an adapter for it so all we have to do is to attach it with the layout first let me write the codee and done now see again an error but it's a silly mistake of brackets so rearrange it this way then first we have created an instance of news adapter that will bind the data to the recycler view then this is the idea of recycler view present in headlines fragment that is recycler headlines and then apply on it inside the apply block we have set the linear layout manager as layout manager for the recycler view this means that the items in the recycler view will be arranged in a vertical scrolling list then I have added the scroll listener to the recycler view for page inition and done now come inside the on view created here we need to initialize few things so first is item headlines error that is present in headlines fragment only then next we need to initialize retry button and error text that is present in item error XML right so to exess that we need to inflate the respective layout here so let me write the code and done see this is how we inflate another layout in fragment so this is an item error layout now once we have the layout then we can easily initialize retry Button as well as error text and done next we will attach the news view model to an activity like this way okay and don't forget to call setup headlines recycle below it and done then next we'll set on item click listener means what will happen when the user will click on recycler view atem it will lead the user to article web view right so let me write the code and done now see we have set on item click listener on new adapter then inside it a bundle is created when item is clicked and then inside it serializable with the key article is added to the bundle and it is the item clicked got it then outside the apply block there is a n controller which will navigate the user from headlines fragment to article fragment with bundle containing the serialized article and then next we need to create few conditions like if the response is Success then what are we supposed to do or if the response is error then what are we supposed to do or if the response is in loading State then what we are supposed to do that we have to mention in The Observer first thing what will it observe headlines right so news view model. headlines do observe with its parameter as view life cycle owner comma Observer and variable as resp response that inside it when response is success or error or loading these are the three condition so let me write the code for it and then first if the response is Success then obviously hide the progress bar and also hide the error message then safe call Operator to check if the response data is not null and if it is not null then let function is invoked and that non-null value will be a news response variable then this line updates the data in the news adapter by submitting the list of articles from the news response to the adapter got it then this line calculates the total number of pages based on the total number of results and the page size also I have added plus two to provide some buffer then this line checks if the current page that is headlines page is the last page by comparing it with the calculated total pages and if it is the last page then adjust the padding of the recycler View and then next let me write the code and done now if the response is error then hide the progress bar then again same way check if response message is not null and if it is not null then let function is invoked and that nonnull value will be a message variable then inside it I'll write a toast as sorry error and whatever the message is then below it I'll call show error message method and pass the argument as message next if the response is loading then simply show a progress bar then come outside the observe here me set on click list on retry button so let me write the code first and done see it's like if there is no internet then this retry button would be shown right so if the user will click on retrive button once the internet is available then it will display all the headlines using get headlines method from news view model with country code as us and that's it our headlines fragment is also ready next let's go to favorite fragment here are four important things first is to display all the favorite articles that is saved in the database second is to make sure that if the user clicks on an item then it should navigate to that particular article only third the article should be deleted if the user swipe left on it and fourth user can undo its delete action got it so let's implement it step by step first is to declare all the necessary variables such as news view model and news adapter then overwrite on view created function and inside it let me quickly set up fragment binding and done next to display all the favorite articles most of the code will be similar to the previous code from headlines fragment so whichever one will be same we will simply copy paste it so first let's start with favorite recycler view setup come outside the on view created and here create a new function as set of favorite recycler and inside it copy the code from here and paste it here now here we don't require scroll list now so remove this line and also here it will be recycler favorite not recycler headlines right and done then inside on view created copy the code from here and paste it here now see obviously instead of set headlines recycler it will be favorite recycler and then set on item click listener will be as it is except that it will navigate from favorite fragment to article fragment then we don't require item add layout so remove all this line and done then next we need to set up swipe left feature so Focus first we will create a class item touch helper call back and extend it as item touch helper dot simple call back then inside it I'll pass two parameters up and down will allow vertical movement and left and right will allow horizontal movement got it then inside it we will have two override functions on Mo which will return true and on swiped so let me write the code first and done now see on Mo function is in moved when an item is dragged from the recycler View and return true means moving item is allowed but we don't require it then on Swipe function is invoked when item is swiped either to left or right then it takes a position of the swiped item in the adapter then retrieves the associated article from the current list in the adapter later it removes the article from the favorite database and then displays a snack bar as removed from favorite with an action as undo so in case of undo it will add that particular article back to favorites then show will display it and then at the end we will create an instance of item touch helper with the item touch helper call back and apply on it then inside the apply block I'll attach the item touch helper to the recycler View and then lastly we will create a get favorite news method from the news view model user using live data that represents a list of favorite news articles then set up an observer on the object with its two parameters as view life cycle owner which is used as life cycle owner only then Observer will be triggered when the manuver the data heal by the live data changes and finally inside the call back the new list of favorite articles is submitted to the news adapter and that's it our favorite fragment is also ready now it's time for our last fragment that is search fragment there is a lot of code here as well but it's very similar to headlines fragment so we'll do a little bit of copy pasting okay now let's create it first we will declare all the necessary variables let's start with view model then adapter then declare all the error UI components retry button error text and item search addor then over override on view created and inside it let me quickly set a binding and done next outside on view created we will create same functions which we created in headlines fragment like height progress bar or show error message and all so copy all the four functions with its variable and paste it here and done make sure to change the variable name then again we want pagination on search as well so we will use the same code as we used in headlines for pagination so let me copy paste it and done I have already explained the cod in headline fragment here we have two methods in it ons scroll and onc scroll State change everything will be same only except the input see here headlines was retrieving get headlines from the news view model and here it will be retrieving search news keyword from the edit text through news view model then next we need to set up search recycler view again it will be same except the IDS so let me copy paste it and done make sure to change ID as recycler search and this as search fragment and done make sure to add missing brackets now come inside on view created here again we will copy paste and then make sure to change the idas then this as setup search recycler and this as search fragment to article fragment and then then next we need to set up code routines so let me write the code first and then this job is a co- routine job that can be used to manage the LIF cycle of a Coe routine then this sets up the text change listener on the search edit view basically it listens for the changes in the text of the edit text then if there is an existing Co routine job it cancels it basically to prevent from multiple overlapping Coe routines then it launches a new Co routine within the main Co routine scope then inside it there is a delay of search news time delay milliseconds before executing the code inside the code routine it will suspend the code routin for the specified time period Then editable is a save call combined with let function it checks if the editable is not null and then executes a code inside the lead block later it checks if the text is editable is not empty if it is not empty then it call search news to perform search operation based on the keyword entered in the edit text then next we need to observe search news through view model so let me quickly copy paste it and then then remember we have a situation where if response is Success then this action will be performed and if response is error then this actions will be performed and if response is loading then this actions will be performed got it then obviously change it to search news then this one as search news page also change this IDs recycler search make sure to import Observer and done last thing is to set on click listener on retry button this one is different so let me quickly write the code [Music] and done now see if the internet is not available then it will show a retry button so if the user will click on it following actions will be performed if search edit text is not empty means keyword is present then search news from the news view model else simply hide the error message and that's it our search fragment is also ready and now it's time for moment of truth let's run the app app I'll highly recommend you to run the app on device not on emulator here it is but it's not displaying any news so let me check what's the issue and then I will let you know I am back very silly mistake we have not mentioned the XML layouts in the fragments like this way we will do it for other fragments as well and done now see we have latest news displaying on the screen then if I click on any of the article it will open in web view see you can literally read entire article here also if I click on this favorite button it will add the article into favorite fragment see here it is now we can also remove it by swiping left and see the article is removed from favorite and also added back using undo not just that but we can also search any keyword in search fragment and see here it is all the results with the same keyword and that's it also there will be few articles which will throw error or crash because they might be null so take care of that otherwise it will work perfectly fine and with that said our news app series is completed now for your convenience I'll be releasing source code of the news app series soon so if you're facing any error then you can simply compare your code with the source code okay also for more updates you can follow us on Instagram or join our telegram group Link in the description box 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 [Music] video
Info
Channel: Android Knowledge
Views: 5,311
Rating: undefined out of 5
Keywords: android studio, android tuto, android studio tutorial 2023, news app, news api integrate, android, how to make news app, how to create news app, how to integrate news api, beginners, mvvm, room, navigation component, coroutines, retrofit, dependency injection, dagger, hilt, learn android, android tutorials, kotlin, android knowledge, learn kotlin android, database, projects in android, full tutorial, learn android studio, learn kotlin projects, create an app, create android app, app
Id: UvaVJ0EseP0
Channel Id: undefined
Length: 144min 45sec (8685 seconds)
Published: Thu Dec 07 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.