SlideShare a Scribd company logo
Android Jetpack
Hassan Abid - Google Developer Expert Android
Presented at Google IO Extended Singapore 2018
Android Jetpack - Google IO Extended Singapore 2018
Google I/O Talks
● Android Jetpack: what's new in Android Support Library
● Android Jetpack: what's new in Architecture Components
● Modern Android development: Android Jetpack, Kotlin, and more
● Android Jetpack: how to smartly use Fragments in your UI
● Android Jetpack: manage UI navigation with Navigation Controller
● Android Jetpack: manage infinite lists with RecyclerView and Paging
● Android Jetpack: easy background processing with WorkManager
● Android Slices: build interactive results for Google Search
● Android Jetpack: sweetening Kotlin development with Android KTX
● Protips: a fresh look at advanced topics for Android experts
AndroidX
AndroidX: "Android Extension Libraries"
android.support.v4.view.ViewCompat
→ androidx.core.view.ViewCompat
android.support.v7.app.AppCompatActivity
→ androidx.appcompat.app.AppCompatActivity
android.arch.persistence.room.RoomDatabase
→ androidx.room.RoomDatabase
AndroidX
● Strict Semantic versioning rule
○ Reset to 1.0.0
Refactor to AndroidX
Migration from 28.0.0-alpha1
Recommended Architecture
Architecture Components
● LifeCycle (1.1.1 Stable)
● Databinding (Stable)
● ViewModel (Stable)
● LiveData (Stable)
● Room (1.1.1 Stable)
● Paging (1.0.1 Stable)
● WorkManager (Alpha Release)
● Navigation (Alpha Release)
https://developer.android.com/jetpack/docs/release-notes
Adding Components to your project
allprojects {
repositories {
jcenter()
google()
}
}
Example : LifeCycle
dependencies {
def lifecycle_version = "1.1.1"
// ViewModel and LiveData
implementation "android.arch.lifecycle:extensions:$lifecycle_version"
// alternatively - just ViewModel. use -ktx for Kotlin
implementation "android.arch.lifecycle:viewmodel:$lifecycle_version"
}
Example : LifeCycle (Android X)
dependencies {
def lifecycle_version = "2.0.0-alpha1"
// ViewModel and LiveData
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
// alternatively - just ViewModel use -ktx for Kotlin
implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version" }
LifeCycle
LifeCycle
LifeCycle Benefits
● Avoid Lifecycle related UI state loss: View Model
● Observability for your UI: LiveData
● Avoid Lifecycle related memory leak
● LiveData transformations
● UI-Database observations : LiveData /Room
● XML-ViewModel observations: DataBinding
● Query and Observe UI Lifecycle State
Fragment View Lifecycle
viewModel.plantAndGardenPlantings.observe(viewLifecycleOwner, Observer { result ->
if (result != null && result.isNotEmpty())
adapter.submitList(result)
})
Databinding
Databinding
A support library that allows you to bind UI components in your
layouts to data sources in your app using a declarative format rather
than programmatically.
TextView textView = findViewById(R.id.sample_text);
textView.setText(viewModel.getUserName());
<TextView
android:text="@{viewmodel.userName}" />
Databinding LiveData
class PlantDetailViewModel() : ViewModel() {
val plant: LiveData<Plant> = ...
}
<data>
<variable
name="viewModel"
type="viewmodels.PlantAndGardenPlantingsViewModel"/>
</data>
<ImageView
android:layout_width="match_parent"
android:layout_height="100dp"
android:scaleType="centerCrop"
app:imageFromUrl="@{viewModel.imageUrl}"
/>
Databinding : One More thing
android {
dataBinding {
enabled = true
}
}
val binding = DataBindingUtil.inflate<FragmentPlantDetailBinding>(
inflater, R.layout.fragment_plant_detail, container,
false).apply {
viewModel = plantDetailViewModel
setLifecycleOwner(this@PlantDetailFragment)
}
ViewModel
ViewModel
● Provide data for UI Components
● Survive Configuration changes
ViewModel
Hold UI Data
Repository
API for loading and saving
data
Activity
Drawing UI
User Interactions
Presenter
Process Data for UI
ViewModel
class PlantDetailViewModel() : ViewModel() {
val plant: LiveData<Plant>
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val plantDetailViewModel = ViewModelProviders.of(this, factory)
.get(PlantDetailViewModel::class.java)
}
Don’t store activity context in
ViewModel
LiveData
LiveData
LiveData is an observable data holder. It is lifecycle aware
public class ProductViewModel extends AndroidViewModel {
private final LiveData<ProductEntity> mObservableProduct;
// ....
public LiveData<ProductEntity> getObservableProduct() {
return mObservableProduct;
}
}
// Observe product data and
model.getObservableProduct().observe(this, new Observer<ProductEntity>() {
@Override
public void onChanged(@Nullable ProductEntity productEntity) {
// update UI
}
});
ViewModel + LiveData +
DataBinding = Reactive UI
Room
Room
● Object Mapping for SQLite Database
● Raw Queries are supported
● Support for RxJava
● Work with java.util.Optional
Room - Entity
@Entity(tableName = "plants")
data class Plant(
@PrimaryKey @ColumnInfo(name = "id") val plantId: String,
val name: String,
val description: String,
val growZoneNumber: Int,
val wateringInterval: Int = 7,
val imageUrl: String = ""
)
Room - Dao
@Dao
interface PlantDao {
@Query("SELECT * FROM plants ORDER BY name")
fun getPlants(): LiveData<List<Plant>>
@Query("SELECT * FROM plants WHERE growZoneNumber = :growZoneNumber ORDER BY
name")
fun getPlantsWithGrowZoneNumber(growZoneNumber: Int): LiveData<List<Plant>>
@Query("SELECT * FROM plants WHERE id = :plantId")
fun getPlant(plantId: String): LiveData<Plant>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertAll(plants: List<Plant>)
}
Observable queries
Room - RoomDatabase
@Database(entities = [GardenPlanting::class, Plant::class], version = 1,
exportSchema = false)
@TypeConverters(Converters::class)
abstract class AppDatabase : RoomDatabase() {
abstract fun gardenPlantingDao(): GardenPlantingDao
abstract fun plantDao(): PlantDao
...
}
Modern Android App
Architecture
Android Jetpack - Google IO Extended Singapore 2018
Paging Library
Paging
● Fetch from database, Network, or both into RecycleView
● Extension of observable List Pattern (e.g LiveData<List>)
● Configurable Load Size, prefetch, placeholders
● Integrates with Room, LiveData, RX
● Stable release
Paging - core components 1/2
● PagedList
○ Load data in pages
○ Async data loading
● DataSource and DataSource.Factory
○ Base class for loading snapshots of data into PagedList
○ Backed by Network or Database
Paging - core components 2/2
● LivePagedListBuilder
○ Build a LiveData<PagedList> based on DataSource.Factory and a
PagedList.config
● BoundaryCallBack
○ Signals when PagedList has reached end of available data
● PagedListAdapter
○ A RecyclerView.Adapter that presents data from PagedLists
Paging - simplified
UI
PageListAdapter
PagedList
--------------
--------------
--------------
Data Layer
DataSource.Factory
BoundyCallBack
Data Source
OnItemAtEndLoaded()
Save data
Get Data
ViewModel
LiveData<PagedList>
Repository
LivePagedListBuilder
LiveData<PagedList>
create()
Build
--------------
Load
more
DataSource
● PageKeyedDataSource
● ItemKeyedDataSource
● PositionalDataSource
BoundaryCallBack
class ConcertBoundaryCallback(
private val query: String,
private val service: MyService,
private val cache: MyLocalCache
) : PagedList.BoundaryCallback<Concert>() {
override fun onZeroItemsLoaded() {
requestAndSaveData(query)
}
override fun onItemAtEndLoaded(itemAtEnd: Concert) {
requestAndSaveData(query)
}
}
Navigation
Navigation - Challenges
● Passing Arguments
● Deep Links
● Fragment Transactions
● Testing
Navigation - Only available in Android Studio
3.2
Navigation
<navigation xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
app:startDestination="@+id/garden_fragment">
<fragment
android:id="@+id/plant_list_fragment"
android:name="com.google.samples.apps.sunflower.PlantListFragment">
<argument
.../>
<action
android:id="@+id/action_plant_list_fragment_to_plant_detail_fragment"
app:destination="@id/plant_detail_fragment"
app:enterAnim="@anim/slide_in_right"
app:exitAnim="@anim/slide_out_left"
app:popEnterAnim="@anim/slide_in_left"
app:popExitAnim="@anim/slide_out_right" />
</fragment>
....
</navigation>
Navigation - Add Navgraph
<fragment
android:id="@+id/garden_nav_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_garden"/>
Navigation - NavigationController
val navController = Navigation.findNavController(this,
R.id.garden_nav_fragment)
// Set up ActionBar
setSupportActionBar(binding.toolbar)
NavigationUI.setupActionBarWithNavController(this,
navController, drawerLayout)
// Set up navigation menu
binding.navigationView.setupWithNavController(navController)
Navigation - NavigationOnClickListener
private fun createOnClickListener(plantId: String): View.OnClickListener {
val bundle = bundleOf(PlantDetailFragment.ARG_ITEM_ID to plantId)
return Navigation.createNavigateOnClickListener(
R.id.action_plant_list_fragment_to_plant_detail_fragment, bundle)
}
<action
android:id="@+id/action_plant_list_fragment_to_plant_detail_fragment"
app:destination="@id/plant_detail_fragment"/>
Samples and Code Lab
Android SunFlower https://github.com/googlesamples/android-sunflower
Universal Music Player
https://github.com/googlesamples/android-UniversalMusicPlayer/blob/master/app/build.gradle
Architecture Components https://github.com/googlesamples/android-architecture-components
Code Labs https://codelabs.developers.google.com/?cat=Android
Guide to Architecture Components https://developer.android.com/jetpack/docs/guide
Conclusion
● Finally Android platform got an Architecture
● Highly Recommended for New Apps
● Try out samples and codelabs
Thank You!
Twitter : @hassanabidpk
Github : hassanabidpk

More Related Content

PDF
Android Jetpack
PPTX
Android Jetpack - What's new
PPTX
Kotlin in industry
PPTX
The Best Way to Become an Android Developer Expert with Android Jetpack
PDF
ID Android TechTalk Series #6 : Google Service and Gradle - Anton Nurdin Tuha...
PDF
Google+ API (2012)
PPT
IntroToAndroid
PPTX
Reason to choose Angular JS for your Web Application
Android Jetpack
Android Jetpack - What's new
Kotlin in industry
The Best Way to Become an Android Developer Expert with Android Jetpack
ID Android TechTalk Series #6 : Google Service and Gradle - Anton Nurdin Tuha...
Google+ API (2012)
IntroToAndroid
Reason to choose Angular JS for your Web Application

What's hot (20)

PPTX
What's new in android jakarta gdg (2015-08-26)
PDF
Google cloud endpoints
PDF
Google Cloud Enpoints
PPTX
Android Studio簡介
PDF
Firebase analytics event_201607
PDF
Micro Frontends
PDF
Entwicklung mit Android Studio und Gradle
PDF
Intro to Flutter
PDF
Introducing the (new) Google Docs API (2019)
PDF
Get Hip with JHipster - Colorado Springs Open Source User Group 2021
PDF
#MBLTdev: Разработка backend для мобильного приложения с использованием Googl...
PPTX
Gradle and Android Studio : Best of Friends
PDF
Node in Production at Aviary
PDF
Mobile backends with Google Cloud Platform (MBLTDev'14)
PDF
Intro to Gradle + How to get up to speed
PPSX
Build Cutting edge Mobile Apps using QML and JavaScript for MeeGo N9: Linux F...
PDF
Present and Future of GWT from a developer perspective
DOCX
ProjectsSummary
PDF
Get Hip with JHipster - GIDS 2019
PDF
Microservices for the Masses with Spring Boot, JHipster and OAuth - GIDS 2019
What's new in android jakarta gdg (2015-08-26)
Google cloud endpoints
Google Cloud Enpoints
Android Studio簡介
Firebase analytics event_201607
Micro Frontends
Entwicklung mit Android Studio und Gradle
Intro to Flutter
Introducing the (new) Google Docs API (2019)
Get Hip with JHipster - Colorado Springs Open Source User Group 2021
#MBLTdev: Разработка backend для мобильного приложения с использованием Googl...
Gradle and Android Studio : Best of Friends
Node in Production at Aviary
Mobile backends with Google Cloud Platform (MBLTDev'14)
Intro to Gradle + How to get up to speed
Build Cutting edge Mobile Apps using QML and JavaScript for MeeGo N9: Linux F...
Present and Future of GWT from a developer perspective
ProjectsSummary
Get Hip with JHipster - GIDS 2019
Microservices for the Masses with Spring Boot, JHipster and OAuth - GIDS 2019
Ad

Similar to Android Jetpack - Google IO Extended Singapore 2018 (20)

PDF
Building Modern Apps using Android Architecture Components
PPTX
How Android Architecture Components can Help You Improve Your App’s Design?
PDF
Android Architecture Components with Kotlin
PDF
Android Architecture Components
PPTX
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
PPTX
Paging Like A Pro
PPTX
Android Architecture - Khoa Tran
PDF
Arquitetando seu app Android com Jetpack
PPTX
Architecture components, Константин Марс, TeamLead, Senior Developer, DataArt
PDF
Android Architecture Components
PPTX
Android architectural components
PPTX
Android Architecture Components
PDF
Arquitetando seu aplicativo Android com Jetpack
PDF
Architecture Components
PDF
Cleaning your architecture with android architecture components
PDF
Architecture Components
PDF
Architecture components - IT Talk
PDF
Android Jetpack + Coroutines: To infinity and beyond
PDF
Gabor Varadi - Reactive State Management with Jetpack Components
PPTX
Model viewviewmodel2
Building Modern Apps using Android Architecture Components
How Android Architecture Components can Help You Improve Your App’s Design?
Android Architecture Components with Kotlin
Android Architecture Components
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
Paging Like A Pro
Android Architecture - Khoa Tran
Arquitetando seu app Android com Jetpack
Architecture components, Константин Марс, TeamLead, Senior Developer, DataArt
Android Architecture Components
Android architectural components
Android Architecture Components
Arquitetando seu aplicativo Android com Jetpack
Architecture Components
Cleaning your architecture with android architecture components
Architecture Components
Architecture components - IT Talk
Android Jetpack + Coroutines: To infinity and beyond
Gabor Varadi - Reactive State Management with Jetpack Components
Model viewviewmodel2
Ad

More from Hassan Abid (17)

PDF
[IO Extended KL] On-Device AI: Is It Time to Go All-In, or Do We Still Need t...
PDF
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
PDF
DevFest SG 2024 - What’s new in On-device Generative AI
PDF
What’s new in Android: Embracing era of Generative AI
PDF
Improving app performance with Kotlin Coroutines
PDF
Android 101 - Kotlin ( Future of Android Development)
PDF
Exploring CameraX from JetPack
PDF
What’s new in Android JetPack
PDF
Kotlin for Android Developers
PDF
Recap of Android Dev Summit 2018
PDF
What's new in Android Pie
PDF
Django for mobile applications
PDF
VR Video Apps on Daydream
PDF
Best Practices in Media Playback
PDF
ExoPlayer for Application developers
PPTX
Android n preview
PDF
Introduction to Pakistan
[IO Extended KL] On-Device AI: Is It Time to Go All-In, or Do We Still Need t...
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
DevFest SG 2024 - What’s new in On-device Generative AI
What’s new in Android: Embracing era of Generative AI
Improving app performance with Kotlin Coroutines
Android 101 - Kotlin ( Future of Android Development)
Exploring CameraX from JetPack
What’s new in Android JetPack
Kotlin for Android Developers
Recap of Android Dev Summit 2018
What's new in Android Pie
Django for mobile applications
VR Video Apps on Daydream
Best Practices in Media Playback
ExoPlayer for Application developers
Android n preview
Introduction to Pakistan

Recently uploaded (20)

PDF
CCleaner Pro 6.38.11537 Crack Final Latest Version 2025
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PPTX
assetexplorer- product-overview - presentation
PPTX
AMADEUS TRAVEL AGENT SOFTWARE | AMADEUS TICKETING SYSTEM
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PPTX
Oracle Fusion HCM Cloud Demo for Beginners
PDF
Cost to Outsource Software Development in 2025
PPTX
Weekly report ppt - harsh dattuprasad patel.pptx
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PPTX
Computer Software and OS of computer science of grade 11.pptx
PDF
Digital Systems & Binary Numbers (comprehensive )
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
Autodesk AutoCAD Crack Free Download 2025
PPTX
Monitoring Stack: Grafana, Loki & Promtail
PDF
Designing Intelligence for the Shop Floor.pdf
PDF
AI-Powered Threat Modeling: The Future of Cybersecurity by Arun Kumar Elengov...
PPTX
Patient Appointment Booking in Odoo with online payment
CCleaner Pro 6.38.11537 Crack Final Latest Version 2025
wealthsignaloriginal-com-DS-text-... (1).pdf
Design an Analysis of Algorithms II-SECS-1021-03
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
assetexplorer- product-overview - presentation
AMADEUS TRAVEL AGENT SOFTWARE | AMADEUS TICKETING SYSTEM
Operating system designcfffgfgggggggvggggggggg
Odoo Companies in India – Driving Business Transformation.pdf
Oracle Fusion HCM Cloud Demo for Beginners
Cost to Outsource Software Development in 2025
Weekly report ppt - harsh dattuprasad patel.pptx
Design an Analysis of Algorithms I-SECS-1021-03
Computer Software and OS of computer science of grade 11.pptx
Digital Systems & Binary Numbers (comprehensive )
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Autodesk AutoCAD Crack Free Download 2025
Monitoring Stack: Grafana, Loki & Promtail
Designing Intelligence for the Shop Floor.pdf
AI-Powered Threat Modeling: The Future of Cybersecurity by Arun Kumar Elengov...
Patient Appointment Booking in Odoo with online payment

Android Jetpack - Google IO Extended Singapore 2018

  • 1. Android Jetpack Hassan Abid - Google Developer Expert Android Presented at Google IO Extended Singapore 2018
  • 3. Google I/O Talks ● Android Jetpack: what's new in Android Support Library ● Android Jetpack: what's new in Architecture Components ● Modern Android development: Android Jetpack, Kotlin, and more ● Android Jetpack: how to smartly use Fragments in your UI ● Android Jetpack: manage UI navigation with Navigation Controller ● Android Jetpack: manage infinite lists with RecyclerView and Paging ● Android Jetpack: easy background processing with WorkManager ● Android Slices: build interactive results for Google Search ● Android Jetpack: sweetening Kotlin development with Android KTX ● Protips: a fresh look at advanced topics for Android experts
  • 4. AndroidX AndroidX: "Android Extension Libraries" android.support.v4.view.ViewCompat → androidx.core.view.ViewCompat android.support.v7.app.AppCompatActivity → androidx.appcompat.app.AppCompatActivity android.arch.persistence.room.RoomDatabase → androidx.room.RoomDatabase
  • 5. AndroidX ● Strict Semantic versioning rule ○ Reset to 1.0.0
  • 6. Refactor to AndroidX Migration from 28.0.0-alpha1
  • 8. Architecture Components ● LifeCycle (1.1.1 Stable) ● Databinding (Stable) ● ViewModel (Stable) ● LiveData (Stable) ● Room (1.1.1 Stable) ● Paging (1.0.1 Stable) ● WorkManager (Alpha Release) ● Navigation (Alpha Release) https://developer.android.com/jetpack/docs/release-notes
  • 9. Adding Components to your project allprojects { repositories { jcenter() google() } }
  • 10. Example : LifeCycle dependencies { def lifecycle_version = "1.1.1" // ViewModel and LiveData implementation "android.arch.lifecycle:extensions:$lifecycle_version" // alternatively - just ViewModel. use -ktx for Kotlin implementation "android.arch.lifecycle:viewmodel:$lifecycle_version" }
  • 11. Example : LifeCycle (Android X) dependencies { def lifecycle_version = "2.0.0-alpha1" // ViewModel and LiveData implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version" // alternatively - just ViewModel use -ktx for Kotlin implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version" }
  • 14. LifeCycle Benefits ● Avoid Lifecycle related UI state loss: View Model ● Observability for your UI: LiveData ● Avoid Lifecycle related memory leak ● LiveData transformations ● UI-Database observations : LiveData /Room ● XML-ViewModel observations: DataBinding ● Query and Observe UI Lifecycle State
  • 15. Fragment View Lifecycle viewModel.plantAndGardenPlantings.observe(viewLifecycleOwner, Observer { result -> if (result != null && result.isNotEmpty()) adapter.submitList(result) })
  • 17. Databinding A support library that allows you to bind UI components in your layouts to data sources in your app using a declarative format rather than programmatically. TextView textView = findViewById(R.id.sample_text); textView.setText(viewModel.getUserName()); <TextView android:text="@{viewmodel.userName}" />
  • 18. Databinding LiveData class PlantDetailViewModel() : ViewModel() { val plant: LiveData<Plant> = ... } <data> <variable name="viewModel" type="viewmodels.PlantAndGardenPlantingsViewModel"/> </data> <ImageView android:layout_width="match_parent" android:layout_height="100dp" android:scaleType="centerCrop" app:imageFromUrl="@{viewModel.imageUrl}" />
  • 19. Databinding : One More thing android { dataBinding { enabled = true } } val binding = DataBindingUtil.inflate<FragmentPlantDetailBinding>( inflater, R.layout.fragment_plant_detail, container, false).apply { viewModel = plantDetailViewModel setLifecycleOwner(this@PlantDetailFragment) }
  • 21. ViewModel ● Provide data for UI Components ● Survive Configuration changes ViewModel Hold UI Data Repository API for loading and saving data Activity Drawing UI User Interactions Presenter Process Data for UI
  • 22. ViewModel class PlantDetailViewModel() : ViewModel() { val plant: LiveData<Plant> } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val plantDetailViewModel = ViewModelProviders.of(this, factory) .get(PlantDetailViewModel::class.java) } Don’t store activity context in ViewModel
  • 24. LiveData LiveData is an observable data holder. It is lifecycle aware public class ProductViewModel extends AndroidViewModel { private final LiveData<ProductEntity> mObservableProduct; // .... public LiveData<ProductEntity> getObservableProduct() { return mObservableProduct; } } // Observe product data and model.getObservableProduct().observe(this, new Observer<ProductEntity>() { @Override public void onChanged(@Nullable ProductEntity productEntity) { // update UI } });
  • 25. ViewModel + LiveData + DataBinding = Reactive UI
  • 26. Room
  • 27. Room ● Object Mapping for SQLite Database ● Raw Queries are supported ● Support for RxJava ● Work with java.util.Optional
  • 28. Room - Entity @Entity(tableName = "plants") data class Plant( @PrimaryKey @ColumnInfo(name = "id") val plantId: String, val name: String, val description: String, val growZoneNumber: Int, val wateringInterval: Int = 7, val imageUrl: String = "" )
  • 29. Room - Dao @Dao interface PlantDao { @Query("SELECT * FROM plants ORDER BY name") fun getPlants(): LiveData<List<Plant>> @Query("SELECT * FROM plants WHERE growZoneNumber = :growZoneNumber ORDER BY name") fun getPlantsWithGrowZoneNumber(growZoneNumber: Int): LiveData<List<Plant>> @Query("SELECT * FROM plants WHERE id = :plantId") fun getPlant(plantId: String): LiveData<Plant> @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertAll(plants: List<Plant>) } Observable queries
  • 30. Room - RoomDatabase @Database(entities = [GardenPlanting::class, Plant::class], version = 1, exportSchema = false) @TypeConverters(Converters::class) abstract class AppDatabase : RoomDatabase() { abstract fun gardenPlantingDao(): GardenPlantingDao abstract fun plantDao(): PlantDao ... }
  • 34. Paging ● Fetch from database, Network, or both into RecycleView ● Extension of observable List Pattern (e.g LiveData<List>) ● Configurable Load Size, prefetch, placeholders ● Integrates with Room, LiveData, RX ● Stable release
  • 35. Paging - core components 1/2 ● PagedList ○ Load data in pages ○ Async data loading ● DataSource and DataSource.Factory ○ Base class for loading snapshots of data into PagedList ○ Backed by Network or Database
  • 36. Paging - core components 2/2 ● LivePagedListBuilder ○ Build a LiveData<PagedList> based on DataSource.Factory and a PagedList.config ● BoundaryCallBack ○ Signals when PagedList has reached end of available data ● PagedListAdapter ○ A RecyclerView.Adapter that presents data from PagedLists
  • 37. Paging - simplified UI PageListAdapter PagedList -------------- -------------- -------------- Data Layer DataSource.Factory BoundyCallBack Data Source OnItemAtEndLoaded() Save data Get Data ViewModel LiveData<PagedList> Repository LivePagedListBuilder LiveData<PagedList> create() Build -------------- Load more
  • 39. BoundaryCallBack class ConcertBoundaryCallback( private val query: String, private val service: MyService, private val cache: MyLocalCache ) : PagedList.BoundaryCallback<Concert>() { override fun onZeroItemsLoaded() { requestAndSaveData(query) } override fun onItemAtEndLoaded(itemAtEnd: Concert) { requestAndSaveData(query) } }
  • 41. Navigation - Challenges ● Passing Arguments ● Deep Links ● Fragment Transactions ● Testing
  • 42. Navigation - Only available in Android Studio 3.2
  • 44. Navigation - Add Navgraph <fragment android:id="@+id/garden_nav_fragment" android:name="androidx.navigation.fragment.NavHostFragment" android:layout_width="match_parent" android:layout_height="match_parent" app:defaultNavHost="true" app:navGraph="@navigation/nav_garden"/>
  • 45. Navigation - NavigationController val navController = Navigation.findNavController(this, R.id.garden_nav_fragment) // Set up ActionBar setSupportActionBar(binding.toolbar) NavigationUI.setupActionBarWithNavController(this, navController, drawerLayout) // Set up navigation menu binding.navigationView.setupWithNavController(navController)
  • 46. Navigation - NavigationOnClickListener private fun createOnClickListener(plantId: String): View.OnClickListener { val bundle = bundleOf(PlantDetailFragment.ARG_ITEM_ID to plantId) return Navigation.createNavigateOnClickListener( R.id.action_plant_list_fragment_to_plant_detail_fragment, bundle) } <action android:id="@+id/action_plant_list_fragment_to_plant_detail_fragment" app:destination="@id/plant_detail_fragment"/>
  • 47. Samples and Code Lab Android SunFlower https://github.com/googlesamples/android-sunflower Universal Music Player https://github.com/googlesamples/android-UniversalMusicPlayer/blob/master/app/build.gradle Architecture Components https://github.com/googlesamples/android-architecture-components Code Labs https://codelabs.developers.google.com/?cat=Android Guide to Architecture Components https://developer.android.com/jetpack/docs/guide
  • 48. Conclusion ● Finally Android platform got an Architecture ● Highly Recommended for New Apps ● Try out samples and codelabs
  • 49. Thank You! Twitter : @hassanabidpk Github : hassanabidpk