NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

- Fragments - Jetpack Navigation
- MVVM
- DataBinding
- Lifecycle aware components
- Room

Android Jetpack: Navigation
Navigation is a common problem that every Android app has to solve. There are many challenges around it that become more noticeable as the app grows in complexity: From Fragment transactions, deep linking to different parts of the app, passing arguments in a safe and secure way, handling up/back navigation (especially with deep links), dealing with the back stack and finally to testing the navigation within the app. JetPack’s navigation component was built with the purpose of bringing solutions to these issues.

Navigation - Some useful definitions
● Navigation graph: An XML resource that contains all navigation-related information in one centralized location. This includes all of the individual content areas within your app, called destinations, as well as the possible paths that a user can take through your app.
● NavHost: Context or container that has all the information it needs to handle any navigation-related actions on its own.
● NavController: Component used to perform navigation between destinations.
● NavigationUI: Component that connects the navigation with some material design components (such as the BottomNavigationView and the DrawerLayout)

Navigation component benefits
● Handling fragment transactions.
● Handling Up and Back actions correctly by default.
● Providing standardized resources for animations and transitions.
● Implementing and handling deep linking.
● Including Navigation UI patterns, such as navigation drawers and bottom navigation, with minimal additional work.
● Safe Args - a Gradle plugin that provides type safety when navigating and passing data between destinations.
● ViewModel support - you can scope a ViewModel to a navigation graph to share UI-related data between the graph's destinations.

Fragment transactions
With the navigation component, there’s no longer a need to manually handle fragment transactions, it takes care of it internally. So in order to go from FragmentA to FragmentB, you’ll just need to call the corresponding navigation action at runtime. It will look like this.

Single Activity & Multiple Fragments Model
With the navigation component and the single activity model, an Activity’s role becomes more of an entry point to the app that delegates the handling of its content rather than being its owner. A NavHost, it is hooked up to a navigation graph which represents the single source of truth, where all the destinations, actions, arguments and deep links are defined.
When using fragments as destinations, you can use the NavHostFragment class as a NavHost.

Passing data in a safe way
Passing data between Fragments can get tedious and is error-prone, besides, things can go wrong or at least get confusing, while refactoring the codebase for example. Ideally, we’d like to pass and receive arguments in an easy manner without having to worry about their keys, and read them in a safe way.
The navigation component brings a solution to this using the Gradle plugin androidx.navigation.safeargs. It basically generates some boilerplate code to make your life easier.

Deep links
Deep linking inside an application gets complicated as the app gets more complex. Issues such as how to structure these deep links, how to pass the required information and how to build the right back stack arise. In the navigation component, deep linking is a first class citizen, and both its types are supported:
● Explicit (when you specify where you want to navigate to in your app)
● Implicit (when other apps trigger your app to launch).

Explicit deep links
Explicit deep links, which is for things such as notifications, app widgets, actions and slices. They are usually pending intent based. An example of building a notification that deep links to a fragment that has the id destinationFragment in the navigation graph main_navigation_graph.

Implicit deep links
Implicit deep links, which concern handling web urls and custom scheme URIs. In the example below, the destination fragment is accessible via the web url www.example.com/path/subpath prefixed by both http and https schemes, and the custom scheme URI android-app://path/subpath/{data}, where data will be available in the destination fragment’s arguments bundle with the key data.

Global actions
You can use a global action to create a common action that multiple destinations can use. For example, you might want buttons in different destinations to navigate to the same main app screen.

Navigation and the back stack
Android maintains a back stack that contains the destinations you've visited. The first destination of your app is placed on the stack when the user opens the app. Each call to the navigate() method puts another destination on top of the stack. Tapping Up or Back calls the NavController.navigateUp() and NavController.popBackStack() methods, respectively, to remove (or pop) the top destination off of the stack.

popUpTo and popUpToInclusive
When navigating using an action, you can optionally pop additional destinations off of the back stack. For example, if your app has an initial login flow, once a user has logged in, you should pop all of the login-related destinations off of the back stack so that the Back button doesn't take users back into the login flow.
To pop destinations when navigating from one destination to another, add an app:popUpTo attribute to the associated <action> element. app:popUpTo tells the Navigation library to pop some destinations off of the back stack as part of the call to navigate(). The attribute value is the ID of the most recent destination that should remain on the stack.
You can also include app:popUpToInclusive="true" to indicate that the destination specified in app:popUpTo should also be removed from the back stack.

Model–View–ViewModel (MVVM)
MVVM is an architectural design pattern that works well for mobile apps.
MVVM decouples the View from the ViewModel by using something called a Binder. The ViewModel doesn’t know about the View or Views subscribed for changes. The Binder delivers the changes from the ViewModel to the View. This allows developing and testing the View in isolation without breaking the ViewModel.

MVVM Components
MVVM has three main components:
● Model
● View
● ViewModel

Defining the Role of the View
In MVVM, the View is very lightweight because it has almost no logic in it. The View is everything UI related. In Android, this is usually an Activity or a Fragment. Its role is to display whatever it receives from the ViewModel and forward input to it. It’s as simple as that!

Defining the Model
The Model is a lightweight component that doesn’t know about any other component. Its role is to store the state of the system and let the ViewModel query it.
The Model is often created using a Repository pattern. Data Access Objects (DAO) that provide Create-Read-Update-Delete (CRUD) operations can help the repository fulfill requests. For Android, the Google team released the Room Persistence library within Jetpack for this purpose.

Defining the ViewModel
The ViewModel is the centerpiece of MVVM. It has all the business logic and some of the display logic in it.
The ViewModel needs to adapt the information in the Model for the Views to display. The ViewModel also transforms input events into data for the Model to store.

Internal and Factory class Implementation
Make the implementation class internal. Then, provide a public Factory that always returns a reference to the Interface type. This way, the implementation never leaves the module.
With these modifications, the implementation of BasicLocationProvider is well-protected from users of the class.
Most Dependency Injection frameworks have an easier way of doing this. For example, in Dagger, you can expose the @Module, but keep the implementation classes internal.

Using DataBinding
Data binding is a technique that connects data sources with consumers and keeps them in sync. Android’s Data Binding Library lets the developer keep the UI in the layout XML files and generates code from them. The library also does the heavy lifting of synchronizing the View with data that comes from the ViewModel.
To add data binding to your project, you need to add the following to your app’s build.gradle file:

What is a life cycle aware component?
A life cycle aware component is a component which is aware of the life cycle of other components like activity or fragment and performs some action in response to change in life cycle status of this component.

Why have life cycle aware components?
An Activity or Fragment may include callbacks such as network calls or heavy computational calls that may take a noticeable amount of time and are thus performed on a different thread to avoid blocking the main thread and freezing the user’s screen.
During this period, the activity may transition into a state where it can no longer accept UI changes. It may have called onStop where it is no longer on the foreground, or onDestroy where it no longer exists. Doing so could result in a memory leak or even crash your application.
One such solution to this problem is to manually dispose of callbacks and observers in these lifecycle methods of the Activity or Fragment. The problem with this approach is that it results in much boilerplate and could get disorganised very quickly, especially if you have lots of callbacks to dispose.

Cases require Lifecycle-based Management
● Switching between fine-grained location updates when the app is in the foreground, and course-grained location updates when the app is in the background
● Starting video buffering as soon as possible but deferring playback to when the activity/app is fully started
● Starting and stopping live-network update streams (such as when listening to a real-time database)
● Pausing and resuming animated drawables based on whether the activity is in the foreground

Lifecycle-Aware Components
The two main components to use are LifecycleObserver and LifecycleOwner.
If an Activity/Fragment implements LifecycleOwner, it can utilise components that implement LifecycleObserver to handle all the lifecycle-based logic internally within those components instead of in the Activity/Fragment. This is possible because classes that implement LifecycleOwner must implement a single method: getLifecycle().
Based on the Lifecycle value returned by this method, a LifecycleObserver can avoid invoking certain callbacks if the owner is not in a state to do so.
A very popular Android component that makes use of Lifecycle-Aware components is LiveData. The observe(lifecycleOwner, observer) method takes in a LifecycleOwner as a parameter and makes use of a LifecycleObserver within its code.

Implementing your own LifecycleOwner
Beyond Activities and Fragments, it’s possible to make any class a LifecycleOwner.
LifecycleRegistry is a class that extends Lifecycle which allows you to determine how it transitions through lifecycle states. You can use this to return the lifecycle state you want your class to be in and return it with getLifecycle().

How do Lifecycle states move in Activities?
● Before any lifecycle methods occur, the activity’s state is simply INITIALIZED. After which, the state is moved naturally in its lifecycle methods. The state is CREATED upon onCreate(), and RESUMED upon onResume(), you know the drill.
● There is no PAUSED or STOPPED state (there is DESTROYED though), however, these “wind down” lifecycle methods simply reduce the state. E.g. onPause() moves the state from RESUMED to STARTED.
● There is however, a special case for the ON_STOP lifecycle event. This is triggered in the activity’s onStop(), yes, but it is also triggered onSaveInstanceState(). This is to prevent any inconsistencies in the navigation state of your app, as there is a gap between when onSavedInstanceState() and onStop() are called.

Room Database
The database named as Room is also a Jetpack component. Using Room in your Android app is straightforward. There are three types of classes that you need to write:
● Entities
● Data access objects
● Databases

Entities
Entities are POJOs (Plain-Old-Java-Objects) with annotations for column names and a primary key:

Data Access Objects
Usually, each entity has its own data access object (DAO). The DAO implements the CRUD operations, as well as other helpful methods.

Database
The database interface needs to know what entities it will have. This lets Room generate the appropriate classes and methods.
Room also handles the versioning of your database. That’s what the second parameter version is for. It will help you run migrations when you upgrade the database.
Initialize the database when the app starts:

     
 
what is notes.io
 

Notes is a web-based application for online taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000+ notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 14 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.