SlideShare a Scribd company logo
Android Architecture
Components
LifeCycle , LiveData , Room and ViewModel
Agenda
● What is Architecture ?
● Common Problems
● Why to use Android Architecture Components ?
● LifeCycle
● ViewModel
● LiveData
● Room
What is Architecture ?
Software application architecture is the process of defining a structured solution that
meets all of the technical and operational requirements, while optimizing common
quality attributes such as performance, security, and manageability. It involves a
series of decisions based on a wide range of factors, and each of these decisions can
have considerable impact on the quality, performance, maintainability, and overall
success of the application
What is Architecture ?
What is Architecture ?
Separation of Concerns
Common Developer Problems
● Multiple Entry Point
● Constantly Switching Flow and Tasks
● Screen Rotation
Architecture Patterns
● MVC (Model-View-Controller)
● MVP (Model-View-Presenter)
● MVVM (Model-View-ViewModel)
● VP (View-Presenter)
Our Expectations
Reality
Why Architecture Components ?
Persist Data
Manage
LifeCycle Modular
Defense Against
Common Errors
Less
Boilerplate
Simple App
App UI/UX ROOM
Modifies,requests
or generates data
for database
Response
Back
LIVE DATA
Components
4. Room
1. LifeCycle
2. LiveData
3. ViewModel
Dependencies
//Room
compile 'android.arch.persistence.room:runtime:1.0.0'
annotationProcessor 'android.arch.persistence.room:compiler:1.0.0'
//LifeCycle and ViewModel
compile 'android.arch.lifecycle:runtime:1.0.0'
compile 'android.arch.lifecycle:extensions:1.0.0'
annotationProcessor 'android.arch.lifecycle:compiler:1.0.0'
LifeCycle : Problems
2. Untimely UI updates
1. Activity/Fragment LifeCycle
4. Screen Rotation
3. Broadcast Receivers
LifeCycle
LifeCycle Owner :
LifeCycle Owner are the objects with lifecycle
,like Activities and Fragments
LifeCycle Owners:
( Activities/Fragments )
LifeCycle Observer :
LifeCycle Observer observe LifeCycleOwners ,
and are notifies of lifecycle changes
LifeCycle Observer
(Ex: LiveData)
LifeCycle
@Override
public void onCreate(...) {
myLocationListener = new MyLocationListener(this, location -> {
// update UI
});
}
@Override
public void onStart() {
super.onStart();
myLocationListener.start();
}
@Override
public void onStop() {
super.onStop();
myLocationListener.stop();
}
LifeCycle
@Override
public void onCreate(...) {
myLocationListener = new MyLocationListener(this, location -> {
// update UI
});
}
@Override
public void onStop() {
super.onStop();
myLocationListener.stop();
}
@Override
public void onStart() {
super.onStart();
Util.checkUserStatus(result -> {
// what if this callback is invoked AFTER activity is stopped?
if (result) {
myLocationListener.start();
}
});
}
MyLocationListener
public class MyLocationListner implements LifecycleObserver {
}
//Add this our MainActivity
getLifecycle().addObserver(new MyLocationListner());
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void connectListener() {
...
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void disconnectListener() {
...
}
MyLocationListener
class MyLocationListener implements LifecycleObserver {
}
private boolean enabled = false;
public MyLocationListener(Context context, Lifecycle lifecycle, Callback callback) {
...
}
public void enable() {
enabled = true;
if (lifecycle.getCurrentState().isAtLeast(STARTED)) {
// connect if not connected
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
void stop() {
// disconnect if connected
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
void start() {
if (enabled) {
// connect
}
}
MainActivity
class MainActivity extends AppCompatActivity {
private MyLocationListener myLocationListener;
public void onCreate(...) {
}
}
myLocationListener =
new MyLocationListener(this,getLifecycle(),location -> {
// update UI
});
Util.checkUserStatus(result -> {
if (result) {
myLocationListener.enable();
}
});
LifeCycle : Use Cases
2. Stopping and starting video buffering
1. Location updates
3. Pausing and resuming animatable drawables
ViewModel
The ViewModel class is designed store and manage UI-related
data so that data survives the configuration changes such as
screen rotations
ViewModel:
public class MyViewModel extends ViewModel{
}
AndroidViewModel with context:
public class MyViewModel extends AndroidViewModel {
public MyViewModel(@NonNull Application application) {
super(application);
}
}
ViewModel LifeCycle
Create ViewModel
public class MyViewModel extends ViewModel {
private int mRotationCount;
public int getRotationCount() {
mRotationCount = mRotationCount + 1;
return mRotationCount;
}
}
Implement ViewModel
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//Get view model instance
MyViewModel myViewModel = ViewModelProviders.of(this).get(MyViewModel.class);
//set the increment value
mRotationCountTextView.setText("" + myViewModel.getRotationCount());
Context ViewModel
public class MyViewModel extends AndroidViewModel {
private NotificationManager mNotificationManager;
}
public MyViewModel(@NonNull Application application) {
super(application);
mNotificationManager = (NotificationManager) application.
getSystemService(Context.NOTIFICATION_SERVICE);
}
ViewModel : Use Cases
2. Shared between fragments
1. Retain State
3. Replacing loaders
LiveData
1. LiveData is observable data holder.
2. It notifies the observers when data changes so that
you can update the UI.
3. It is also Life Cycle Aware
LiveData : Pros
1. UI Matches your data state
2. No Memory leak
3. No more manual lifecycle handling
Create LiveData Object
public class NameViewModel extends ViewModel {
// Rest of the ViewModel...
}
// Create a LiveData with a String
private MutableLiveData<String> mCurrentName;
public MutableLiveData<String> getCurrentName() {
if (mCurrentName == null) {
mCurrentName = new MutableLiveData<String>();
}
return mCurrentName;
}
Observe LiveData Objects
private NameViewModel mModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
// Get the ViewModel.
mModel = ViewModelProviders.of(this).get(NameViewModel.class);
// Create the observer which updates the UI.
final Observer<String> nameObserver = new Observer<String>() {
@Override
public void onChanged(@Nullable final String newName) {
// Update the UI, in this case, a TextView.
mNameTextView.setText(newName);
}
};
// Observe the LiveData, passing in this activity as the
// LifecycleOwner and the observer.
mModel.getCurrentName().observe(this, nameObserver);
Update LiveData Objects
mButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String anotherName = "John Doe";
mModel.getCurrentName().setValue(anotherName);
}
});
Database ??
Room
Room is a robust SQL Object Mapping Library
Plain Old Java Object (POJO)
Old POJO Room POJO
public class User {
private int uid;
private String firstName;
private String lastName;
private int age;
private Date dateOfJoining;
}
public class User {
private int uid;
private String firstName;
private String lastName;
private int age;
private Date dateOfJoining;
}
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "first_name")
@Entity
@ColumnInfo(name = "last_name")
UserDao.java
public interface UserDao {
}
@Insert
void insertAll(List<User> users);
@Delete
void delete(User user);
@Update
void updateUser(User user);
@Query("SELECT * FROM user")
List<User> getAll();
@Dao
@Query("SELECT * FROM user WHERE uid = :userID")
User findUserById(int userID);
UserDao.java
public interface UserDao {
}
@Insert
void insertAll(List<User> users);
@Delete
void delete(User user);
@Update
void updateUser(User user);
@Query("SELECT * FROM user")
LiveData<List<User>> getAll();
@Dao
@Query("SELECT * FROM user WHERE uid = :userID")
User findUserById(int userID);
Setup Room Database
public abstract class AppDatabase extends RoomDatabase {
}
public abstract UserDao userDao();
@Database(entities = {User.class}, version = 1)
@TypeConverters({Converters.class})
Build Room Database
public class AppController extends Application {
private static AppController appController;
private AppDatabase appDatabase;
@Override
public void onCreate() {
super.onCreate();
appController = this;
}
public static AppDatabase getAppDatabase() {
return appController.appDatabase;
}
}
//Initialize the room database with database name
appDatabase = Room.databaseBuilder(this, AppDatabase.class, "user-database")
.fallbackToDestructiveMigration()
.build();
Display data
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<User> userList = AppController
.getAppDatabase()
.userDao()
.getAll();
//Update List in adapter
}
}
UserModel
public class UserModel extends ViewModel {
private final UserDao userDao;
public UserModel() {
userDao = AppController
.getAppDatabase()
.userDao();
}
public LiveData<List<User>> getAllUser()
{
return userDao.getAll();
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
private UserModel userModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Setup your UI
}
}
userModel = ViewModelProviders.of(this).get(UserModel.class);
userModel.getAllUser().observe(this, new Observer<List<User>>() {
@Override
public void onChanged(@Nullable List<User> userList) {
// updateUI
}
});
Thank you
burhanrashid52
Burhanuddin Rashid
Resources :
● Android Architecture Components : http://bit.ly/2hGRxoc
● Exploring Architecture Components : http://bit.ly/2j1Pvvv
Multidots Inc.
https://www.multidots.com/

More Related Content

What's hot

Hibernate complete Training
Hibernate complete TrainingHibernate complete Training
Hibernate complete Training
sourabh aggarwal
 
Apache Struts 2 Advance
Apache Struts 2 AdvanceApache Struts 2 Advance
Apache Struts 2 Advance
Emprovise
 
JSUG - Google Guice by Jan Zarnikov
JSUG - Google Guice by Jan ZarnikovJSUG - Google Guice by Jan Zarnikov
JSUG - Google Guice by Jan Zarnikov
Christoph Pickl
 
Introduction to JPA Framework
Introduction to JPA FrameworkIntroduction to JPA Framework
Introduction to JPA Framework
Collaboration Technologies
 
JPA 2.1 performance tuning tips
JPA 2.1 performance tuning tipsJPA 2.1 performance tuning tips
JPA 2.1 performance tuning tips
osa_ora
 
Five android architecture
Five android architectureFive android architecture
Five android architecture
Tomislav Homan
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
Guo Albert
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentation
John Slick
 
Android Components
Android ComponentsAndroid Components
Android Components
Aatul Palandurkar
 
Android DevConference - Android Clean Architecture
Android DevConference - Android Clean ArchitectureAndroid DevConference - Android Clean Architecture
Android DevConference - Android Clean Architecture
iMasters
 
Android application model
Android application modelAndroid application model
Android application model
magicshui
 
JPA For Beginner's
JPA For Beginner'sJPA For Beginner's
JPA For Beginner's
NarayanaMurthy Ganashree
 
Advance Java Practical file
Advance Java Practical fileAdvance Java Practical file
Advance Java Practical file
varun arora
 
Android Database Tutorial
Android Database TutorialAndroid Database Tutorial
Android Database Tutorial
Perfect APK
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
Alexey Buzdin
 
Тарас Олексин - Sculpt! Your! Tests!
Тарас Олексин  - Sculpt! Your! Tests!Тарас Олексин  - Sculpt! Your! Tests!
Тарас Олексин - Sculpt! Your! Tests!
DataArt
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
Collaboration Technologies
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate Tutorial
Syed Shahul
 
Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4
soelinn
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2
Haroon Idrees
 

What's hot (20)

Hibernate complete Training
Hibernate complete TrainingHibernate complete Training
Hibernate complete Training
 
Apache Struts 2 Advance
Apache Struts 2 AdvanceApache Struts 2 Advance
Apache Struts 2 Advance
 
JSUG - Google Guice by Jan Zarnikov
JSUG - Google Guice by Jan ZarnikovJSUG - Google Guice by Jan Zarnikov
JSUG - Google Guice by Jan Zarnikov
 
Introduction to JPA Framework
Introduction to JPA FrameworkIntroduction to JPA Framework
Introduction to JPA Framework
 
JPA 2.1 performance tuning tips
JPA 2.1 performance tuning tipsJPA 2.1 performance tuning tips
JPA 2.1 performance tuning tips
 
Five android architecture
Five android architectureFive android architecture
Five android architecture
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentation
 
Android Components
Android ComponentsAndroid Components
Android Components
 
Android DevConference - Android Clean Architecture
Android DevConference - Android Clean ArchitectureAndroid DevConference - Android Clean Architecture
Android DevConference - Android Clean Architecture
 
Android application model
Android application modelAndroid application model
Android application model
 
JPA For Beginner's
JPA For Beginner'sJPA For Beginner's
JPA For Beginner's
 
Advance Java Practical file
Advance Java Practical fileAdvance Java Practical file
Advance Java Practical file
 
Android Database Tutorial
Android Database TutorialAndroid Database Tutorial
Android Database Tutorial
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Тарас Олексин - Sculpt! Your! Tests!
Тарас Олексин  - Sculpt! Your! Tests!Тарас Олексин  - Sculpt! Your! Tests!
Тарас Олексин - Sculpt! Your! Tests!
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate Tutorial
 
Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2
 

Similar to Android Architecture Components

Architecture components - IT Talk
Architecture components - IT TalkArchitecture components - IT Talk
Architecture components - IT Talk
Constantine Mars
 
Android architecture component - FbCircleDev Yogyakarta Indonesia
Android architecture component - FbCircleDev Yogyakarta IndonesiaAndroid architecture component - FbCircleDev Yogyakarta Indonesia
Android architecture component - FbCircleDev Yogyakarta Indonesia
Pratama Nur Wijaya
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
javatwo2011
 
Android architecture components - how they fit in good old architectural patt...
Android architecture components - how they fit in good old architectural patt...Android architecture components - how they fit in good old architectural patt...
Android architecture components - how they fit in good old architectural patt...
DroidConTLV
 
Alexey Buzdin "Maslow's Pyramid of Android Testing"
Alexey Buzdin "Maslow's Pyramid of Android Testing"Alexey Buzdin "Maslow's Pyramid of Android Testing"
Alexey Buzdin "Maslow's Pyramid of Android Testing"
IT Event
 
Presentation Android Architecture Components
Presentation Android Architecture ComponentsPresentation Android Architecture Components
Presentation Android Architecture Components
Attract Group
 
The Next Step in AS3 Framework Evolution
The Next Step in AS3 Framework EvolutionThe Next Step in AS3 Framework Evolution
The Next Step in AS3 Framework Evolution
FITC
 
Quick Intro to Android Development
Quick Intro to Android DevelopmentQuick Intro to Android Development
Quick Intro to Android Development
Jussi Pohjolainen
 
Architecture Components
Architecture ComponentsArchitecture Components
Architecture Components
Sang Eel Kim
 
Building Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture ComponentsBuilding Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture Components
Hassan Abid
 
What's Coming in Spring 3.0
What's Coming in Spring 3.0What's Coming in Spring 3.0
What's Coming in Spring 3.0
Matt Raible
 
Android Architecture Components
Android Architecture ComponentsAndroid Architecture Components
Android Architecture Components
Darshan Parikh
 
Working effectively with ViewModels and TDD - UA Mobile 2019
Working effectively with ViewModels and TDD - UA Mobile 2019Working effectively with ViewModels and TDD - UA Mobile 2019
Working effectively with ViewModels and TDD - UA Mobile 2019
UA Mobile
 
Gwt.create
Gwt.createGwt.create
JSAnkara Swift v React Native
JSAnkara Swift v React NativeJSAnkara Swift v React Native
JSAnkara Swift v React Native
Muhammed Demirci
 
Codemotion appengine
Codemotion appengineCodemotion appengine
Codemotion appengine
Ignacio Coloma
 
Storage Plug-ins
Storage Plug-ins Storage Plug-ins
Storage Plug-ins
buildacloud
 
Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2
Matt Raible
 
Struts 2 + Spring
Struts 2 + SpringStruts 2 + Spring
Struts 2 + Spring
Bryan Hsueh
 
OpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheConOpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheCon
os890
 

Similar to Android Architecture Components (20)

Architecture components - IT Talk
Architecture components - IT TalkArchitecture components - IT Talk
Architecture components - IT Talk
 
Android architecture component - FbCircleDev Yogyakarta Indonesia
Android architecture component - FbCircleDev Yogyakarta IndonesiaAndroid architecture component - FbCircleDev Yogyakarta Indonesia
Android architecture component - FbCircleDev Yogyakarta Indonesia
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Android architecture components - how they fit in good old architectural patt...
Android architecture components - how they fit in good old architectural patt...Android architecture components - how they fit in good old architectural patt...
Android architecture components - how they fit in good old architectural patt...
 
Alexey Buzdin "Maslow's Pyramid of Android Testing"
Alexey Buzdin "Maslow's Pyramid of Android Testing"Alexey Buzdin "Maslow's Pyramid of Android Testing"
Alexey Buzdin "Maslow's Pyramid of Android Testing"
 
Presentation Android Architecture Components
Presentation Android Architecture ComponentsPresentation Android Architecture Components
Presentation Android Architecture Components
 
The Next Step in AS3 Framework Evolution
The Next Step in AS3 Framework EvolutionThe Next Step in AS3 Framework Evolution
The Next Step in AS3 Framework Evolution
 
Quick Intro to Android Development
Quick Intro to Android DevelopmentQuick Intro to Android Development
Quick Intro to Android Development
 
Architecture Components
Architecture ComponentsArchitecture Components
Architecture Components
 
Building Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture ComponentsBuilding Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture Components
 
What's Coming in Spring 3.0
What's Coming in Spring 3.0What's Coming in Spring 3.0
What's Coming in Spring 3.0
 
Android Architecture Components
Android Architecture ComponentsAndroid Architecture Components
Android Architecture Components
 
Working effectively with ViewModels and TDD - UA Mobile 2019
Working effectively with ViewModels and TDD - UA Mobile 2019Working effectively with ViewModels and TDD - UA Mobile 2019
Working effectively with ViewModels and TDD - UA Mobile 2019
 
Gwt.create
Gwt.createGwt.create
Gwt.create
 
JSAnkara Swift v React Native
JSAnkara Swift v React NativeJSAnkara Swift v React Native
JSAnkara Swift v React Native
 
Codemotion appengine
Codemotion appengineCodemotion appengine
Codemotion appengine
 
Storage Plug-ins
Storage Plug-ins Storage Plug-ins
Storage Plug-ins
 
Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2
 
Struts 2 + Spring
Struts 2 + SpringStruts 2 + Spring
Struts 2 + Spring
 
OpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheConOpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheCon
 

Recently uploaded

Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Speck&Tech
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 

Recently uploaded (20)

Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 

Android Architecture Components

  • 1. Android Architecture Components LifeCycle , LiveData , Room and ViewModel
  • 2. Agenda ● What is Architecture ? ● Common Problems ● Why to use Android Architecture Components ? ● LifeCycle ● ViewModel ● LiveData ● Room
  • 3. What is Architecture ? Software application architecture is the process of defining a structured solution that meets all of the technical and operational requirements, while optimizing common quality attributes such as performance, security, and manageability. It involves a series of decisions based on a wide range of factors, and each of these decisions can have considerable impact on the quality, performance, maintainability, and overall success of the application
  • 5. What is Architecture ? Separation of Concerns
  • 6. Common Developer Problems ● Multiple Entry Point ● Constantly Switching Flow and Tasks ● Screen Rotation
  • 7. Architecture Patterns ● MVC (Model-View-Controller) ● MVP (Model-View-Presenter) ● MVVM (Model-View-ViewModel) ● VP (View-Presenter)
  • 10. Why Architecture Components ? Persist Data Manage LifeCycle Modular Defense Against Common Errors Less Boilerplate
  • 11. Simple App App UI/UX ROOM Modifies,requests or generates data for database Response Back LIVE DATA
  • 12. Components 4. Room 1. LifeCycle 2. LiveData 3. ViewModel
  • 13. Dependencies //Room compile 'android.arch.persistence.room:runtime:1.0.0' annotationProcessor 'android.arch.persistence.room:compiler:1.0.0' //LifeCycle and ViewModel compile 'android.arch.lifecycle:runtime:1.0.0' compile 'android.arch.lifecycle:extensions:1.0.0' annotationProcessor 'android.arch.lifecycle:compiler:1.0.0'
  • 14. LifeCycle : Problems 2. Untimely UI updates 1. Activity/Fragment LifeCycle 4. Screen Rotation 3. Broadcast Receivers
  • 15. LifeCycle LifeCycle Owner : LifeCycle Owner are the objects with lifecycle ,like Activities and Fragments LifeCycle Owners: ( Activities/Fragments ) LifeCycle Observer : LifeCycle Observer observe LifeCycleOwners , and are notifies of lifecycle changes LifeCycle Observer (Ex: LiveData)
  • 16. LifeCycle @Override public void onCreate(...) { myLocationListener = new MyLocationListener(this, location -> { // update UI }); } @Override public void onStart() { super.onStart(); myLocationListener.start(); } @Override public void onStop() { super.onStop(); myLocationListener.stop(); }
  • 17. LifeCycle @Override public void onCreate(...) { myLocationListener = new MyLocationListener(this, location -> { // update UI }); } @Override public void onStop() { super.onStop(); myLocationListener.stop(); } @Override public void onStart() { super.onStart(); Util.checkUserStatus(result -> { // what if this callback is invoked AFTER activity is stopped? if (result) { myLocationListener.start(); } }); }
  • 18. MyLocationListener public class MyLocationListner implements LifecycleObserver { } //Add this our MainActivity getLifecycle().addObserver(new MyLocationListner()); @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) public void connectListener() { ... } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) public void disconnectListener() { ... }
  • 19. MyLocationListener class MyLocationListener implements LifecycleObserver { } private boolean enabled = false; public MyLocationListener(Context context, Lifecycle lifecycle, Callback callback) { ... } public void enable() { enabled = true; if (lifecycle.getCurrentState().isAtLeast(STARTED)) { // connect if not connected } } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) void stop() { // disconnect if connected } @OnLifecycleEvent(Lifecycle.Event.ON_START) void start() { if (enabled) { // connect } }
  • 20. MainActivity class MainActivity extends AppCompatActivity { private MyLocationListener myLocationListener; public void onCreate(...) { } } myLocationListener = new MyLocationListener(this,getLifecycle(),location -> { // update UI }); Util.checkUserStatus(result -> { if (result) { myLocationListener.enable(); } });
  • 21. LifeCycle : Use Cases 2. Stopping and starting video buffering 1. Location updates 3. Pausing and resuming animatable drawables
  • 22. ViewModel The ViewModel class is designed store and manage UI-related data so that data survives the configuration changes such as screen rotations ViewModel: public class MyViewModel extends ViewModel{ } AndroidViewModel with context: public class MyViewModel extends AndroidViewModel { public MyViewModel(@NonNull Application application) { super(application); } }
  • 24. Create ViewModel public class MyViewModel extends ViewModel { private int mRotationCount; public int getRotationCount() { mRotationCount = mRotationCount + 1; return mRotationCount; } }
  • 25. Implement ViewModel @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } //Get view model instance MyViewModel myViewModel = ViewModelProviders.of(this).get(MyViewModel.class); //set the increment value mRotationCountTextView.setText("" + myViewModel.getRotationCount());
  • 26. Context ViewModel public class MyViewModel extends AndroidViewModel { private NotificationManager mNotificationManager; } public MyViewModel(@NonNull Application application) { super(application); mNotificationManager = (NotificationManager) application. getSystemService(Context.NOTIFICATION_SERVICE); }
  • 27. ViewModel : Use Cases 2. Shared between fragments 1. Retain State 3. Replacing loaders
  • 28. LiveData 1. LiveData is observable data holder. 2. It notifies the observers when data changes so that you can update the UI. 3. It is also Life Cycle Aware
  • 29. LiveData : Pros 1. UI Matches your data state 2. No Memory leak 3. No more manual lifecycle handling
  • 30. Create LiveData Object public class NameViewModel extends ViewModel { // Rest of the ViewModel... } // Create a LiveData with a String private MutableLiveData<String> mCurrentName; public MutableLiveData<String> getCurrentName() { if (mCurrentName == null) { mCurrentName = new MutableLiveData<String>(); } return mCurrentName; }
  • 31. Observe LiveData Objects private NameViewModel mModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } // Get the ViewModel. mModel = ViewModelProviders.of(this).get(NameViewModel.class); // Create the observer which updates the UI. final Observer<String> nameObserver = new Observer<String>() { @Override public void onChanged(@Nullable final String newName) { // Update the UI, in this case, a TextView. mNameTextView.setText(newName); } }; // Observe the LiveData, passing in this activity as the // LifecycleOwner and the observer. mModel.getCurrentName().observe(this, nameObserver);
  • 32. Update LiveData Objects mButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String anotherName = "John Doe"; mModel.getCurrentName().setValue(anotherName); } });
  • 34. Room Room is a robust SQL Object Mapping Library
  • 35. Plain Old Java Object (POJO) Old POJO Room POJO public class User { private int uid; private String firstName; private String lastName; private int age; private Date dateOfJoining; } public class User { private int uid; private String firstName; private String lastName; private int age; private Date dateOfJoining; } @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "first_name") @Entity @ColumnInfo(name = "last_name")
  • 36. UserDao.java public interface UserDao { } @Insert void insertAll(List<User> users); @Delete void delete(User user); @Update void updateUser(User user); @Query("SELECT * FROM user") List<User> getAll(); @Dao @Query("SELECT * FROM user WHERE uid = :userID") User findUserById(int userID);
  • 37. UserDao.java public interface UserDao { } @Insert void insertAll(List<User> users); @Delete void delete(User user); @Update void updateUser(User user); @Query("SELECT * FROM user") LiveData<List<User>> getAll(); @Dao @Query("SELECT * FROM user WHERE uid = :userID") User findUserById(int userID);
  • 38. Setup Room Database public abstract class AppDatabase extends RoomDatabase { } public abstract UserDao userDao(); @Database(entities = {User.class}, version = 1) @TypeConverters({Converters.class})
  • 39. Build Room Database public class AppController extends Application { private static AppController appController; private AppDatabase appDatabase; @Override public void onCreate() { super.onCreate(); appController = this; } public static AppDatabase getAppDatabase() { return appController.appDatabase; } } //Initialize the room database with database name appDatabase = Room.databaseBuilder(this, AppDatabase.class, "user-database") .fallbackToDestructiveMigration() .build();
  • 40. Display data public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); List<User> userList = AppController .getAppDatabase() .userDao() .getAll(); //Update List in adapter } }
  • 41. UserModel public class UserModel extends ViewModel { private final UserDao userDao; public UserModel() { userDao = AppController .getAppDatabase() .userDao(); } public LiveData<List<User>> getAllUser() { return userDao.getAll(); } }
  • 42. MainActivity public class MainActivity extends AppCompatActivity { private UserModel userModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Setup your UI } } userModel = ViewModelProviders.of(this).get(UserModel.class); userModel.getAllUser().observe(this, new Observer<List<User>>() { @Override public void onChanged(@Nullable List<User> userList) { // updateUI } });
  • 43. Thank you burhanrashid52 Burhanuddin Rashid Resources : ● Android Architecture Components : http://bit.ly/2hGRxoc ● Exploring Architecture Components : http://bit.ly/2j1Pvvv Multidots Inc. https://www.multidots.com/

Editor's Notes

  1. -Greeting -What is architecture ?
  2. -Home Kitche Example
  3. -Which one to follow MVP,MVVP ? -Google Guidelines Architecture -No Force
  4. -Home Kitche Example
  5. -Home Kitche Example
  6. -Which one to follow MVP,MVVP ? -Google Guidelines Architecture -No Force
  7. -Which one to follow MVP,MVVP ? -Google Guidelines Architecture -No Force
  8. -What is our expectations ? -Client Requirements -Desgin
  9. Reality after uncertain changes in requirements and design changes
  10. 1.Better Data Persistent than SQL 2.Less boiler plate (SQLite documentation and creating a lot of constant) 3.Life Cycle Register unregister onStart and OnStop (Untimely UI updates) 4. Common errors (SQL queries compile time errors) 5. Modular and Structures,testable and maintainable
  11. -In this simple demo app -Add,Delete and Update users -LiveData changes reflect to UI -LiveData life cycle aware
  12. Four Major components -Room (wrapper on SQL Life) -ViewModel (Save data on screen rotation) -LifeCycle (Life cycle awareness) -LiveData (live changes update using lifecycle owner and observer) -Add Dependencies
  13. -Following dependencies to add
  14. 1.Handling events on onCreate,onResume,onPause,onStop,onDestroy 2.Receiving updates while screen is rotated on the devices is onPause or onDestroy 3.Register unregister onResume onPause adding and removing listener 4.On rotation data lost (Solution : sava bundle instance (not easy) )
  15. 1.LifeCycleOwner represents must be implemented to ana activity/fra 2.LifeCycleObserver is a class which extends LiveData<T> class 3.LifeCycleObserver requires a LifeCyleOwner Activity/Fragments to updates live data and be lifecycle aware
  16. 1.Handling events on onCreate,onResume,onPause,onStop,onDestroy 2.Receiving updates while screen is rotated on the devices is onPause or onDestroy 3.Register unregister onResume onPause adding and removing listener 4.On rotation data lost (Solution : sava bundle instance (not easy) )
  17. 1.Better Data Persistent than SQL 2.Less boiler plate (SQLite documentation and creating a lot of constant) 3.Life Cycle Register unregister onStart and OnStop (Untimely UI updates) 4. Common errors (SQL queries compile time errors) 5. Modular and Structures,testable and maintainable
  18. 1.Better Data Persistent than SQL 2.Less boiler plate (SQLite documentation and creating a lot of constant) 3.Life Cycle Register unregister onStart and OnStop (Untimely UI updates) 4. Common errors (SQL queries compile time errors) 5. Modular and Structures,testable and maintainable
  19. 1.Handling events on onCreate,onResume,onPause,onStop,onDestroy 2.Receiving updates while screen is rotated on the devices is onPause or onDestroy 3.Register unregister onResume onPause adding and removing listener 4.On rotation data lost (Solution : sava bundle instance (not easy) )
  20. -How many types of database used ? -Similar to GreenDao and realm
  21. Basic Three components of Room to build database 1.Entity (Define Table Schema) 2.DAO (data access object define all queries for specific tables) 3.Room Database (Singleton database builder with all abstract DAO classes)
  22. Entity -Convert response into POJO -Entity notation to make it dao -Annotation used -Primary key auto generate -Custom table name -Many more annotations
  23. (2) Dao -Insert list on single item -insert replace annotation -update -delete -raw query -parameter and query name with : colon -compile time error -LiveData if any changes happens -More details in demo code
  24. (2) Dao -Insert list on single item -insert replace annotation -update -delete -raw query -parameter and query name with : colon -compile time error -LiveData if any changes happens -More details in demo code
  25. 1.Better Data Persistent than SQL 2.Less boiler plate (SQLite documentation and creating a lot of constant) 3.Life Cycle Register unregister onStart and OnStop (Untimely UI updates) 4. Common errors (SQL queries compile time errors) 5. Modular and Structures,testable and maintainable
  26. 1.Better Data Persistent than SQL 2.Less boiler plate (SQLite documentation and creating a lot of constant) 3.Life Cycle Register unregister onStart and OnStop (Untimely UI updates) 4. Common errors (SQL queries compile time errors) 5. Modular and Structures,testable and maintainable
  27. 1.Better Data Persistent than SQL 2.Less boiler plate (SQLite documentation and creating a lot of constant) 3.Life Cycle Register unregister onStart and OnStop (Untimely UI updates) 4. Common errors (SQL queries compile time errors) 5. Modular and Structures,testable and maintainable