SlideShare a Scribd company logo
1 of 48
Loaders, Cursor Loaders
And Threads
Idan Felix, 16/3/2015
Agenda
Loaders CursorLoader
What What
Why Why
How How
and how does it all fit in?
First things first
Elections day tomorrow,
Don’t forget to vote.
Last week: How to talk to databases
2 weeks ago: Activity lifecycle
Source:
developer.android.com/training/basics/activity-lifecycle/starting.html
Where would you load your data?
onCreate? onStart? onResume?
What happens when the phone rotates?
how to get fresh data as soon as it’s ready?
How to get the data? AsyncTask?
a Loader is an Android Specific pattern,
Designed so that async data retrieval is…
Easy to implement PROPERLY.
So, What are Loaders?
Available since Android 3.0 (Honeycomb, API level 11 and support libs),
to Activities and Fragments,
Also use that Observer Pattern we’ve seen
last week,
Are cached between configuration changes.
So, What are Loaders?
- Recommended way to load data
BUT NOT ONLY!
- Works best with Cursors,
BUT NOT ONLY!
Why to use loaders?
API Breakdown
Loader Abstract class that performs async
loading of data.
It can monitor its data-source while
active.
API Breakdown
More commonly, we’ll see these:
a loader implementation that provies an
AsyncTask to do to loading,
an AsyncTaskLoader that is used to query
data from a ContentProvider and returns a
Cursor.
Loader
Async Task
Loader
Cursor
Loader
API Breakdown
This is where the magic is:
LoaderManager helps an activity
manage long-running operations
with the activity lifecylce.
Loader
Async Task
Loader
Cursor
Loader
LoaderManager
API Breakdown
The callbacks are used to abstract
the specific loader from the loader
manager.
3 Methods: onCreateLoader (int id, Bundle args),
onLoadFinished(Loader<D>
loader, D data),
onLoaderReset(Loader<D>
loader)
Loader
Async Task
Loader
Cursor
Loader
LoaderManager
LoaderCallbacks <D>
How to use loaders?
Step 1: Create a unique ID for your loader.
Step 2: LoaderManager.Loadercallbacks<D>
Step 3: init the loader with the id.
How to use loaders? - Step 1
Have a constant int, unique for the loader in
the activity.
private static final int LOADER_ID = 31415;
How to use loaders? - Step 2
Implement the
LoaderManager.LoaderCallbacks<D>.
Our demo will use a Long, so:
implements
LoaderManager.LoaderCallbacks<Long>
How to use loaders? - Step 3
in the Activity’s onCreate,
or in the Fragment’s onActivityCreate,
init the loader as such:
getLoaderManager().initLoader( LOADER_ID,
Parameter,
LoaderCallback);
in the Activity’s onCreate,
or in the Fragment’s onActivityCreate,
init the loader as such:
getLoaderManager().initLoader( LOADER_ID,
Parameter,
LoaderCallback);
How to use loaders?
If the activity has multiple loaders,
each should have its own unique ID.
This enables the LoaderManager to re-
use the Loader.
How to use loaders?
in the Activity’s onCreate,
or in the Fragment’s onActivityCreate,
init the loader as such:
getLoaderManager().initLoader( LOADER_ID,
Parameter,
LoaderCallback);
The parameter is passed to the loader.
How to use loaders?
in the Activity’s onCreate,
or in the Fragment’s onActivityCreate,
init the loader as such:
getLoaderManager().initLoader( LOADER_ID,
Parameter,
LoaderCallback);
the manager uses this instance of
LoaderManager.LoaderCallbacks to
manage the loader’s lifecycle.
Loader Initialization - 1
when LM.initLoader is called, if the loader
does not exist, the callback’s onCreateLoader
method is called.
That’s where you create the loader.
Loader Initialization - 2
when LM.initLoader is called, if the loader
does exist, the callback’s onCreateLoader
method is not called - but the new Listener
replaces the old listener.
That’s how you get away with Configuration
Changes.
Demo
We’ll see 2 activities.
in onCreate, one starts a 5 second async task,
and the other starts a 5 second loader.
We’ll rotate the device after ~2 seconds in each.
Check out the LogCat too - to see just the 1 creation.
Yonatan’s Demo
adb shell dumpsys
com.example.felixidan.loadersdemo
Story time: AsyncTaskLoader - Fail
How I thought it would look:
public class DemoLoader extends AsyncTaskLoader<Long> {
public DemoLoader(Context context) {
super(context);
}
@Override
public Long loadInBackground() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {}
return new Long(SystemClock.upTimeMillies());
}
}
This code moved to
“TheBrain”.
Story time: AsyncTaskLoader - Fail
However, it was not that simple -
the DemoLoader class is about 100 lines long
(and the “real” data loading is a one-liner).
Why?
Story time: AsyncTaskLoader - Epif.
I did not consider the responsibilities of the
loader:
Getting
Data
Keeping
Data
Observing
Data source
Lifecycle
Quiz Time
Is it OK to have 2 loaders with the same ID?
→ Yes, if they’re not on the same Activity.
Can an activity have multiple loaders?
→ Yes, but they have to have a different ID.
What types can a loader return?
→ Everything, as long as it’s an Object.
Quiz Time
How does this mechanism handles configuration changes?
→ The loader manager keeps the loader, but replaces
the
callbacks object - so the most recent activity gets
notified when the loader is done.
What happens when the data is changed?
→ The Loader is notified (by the Observer) and pushes
new information to the onLoaderFinished method.
Quiz Time
When to init the loader? (to call LoaderManager.init)
→ In onCreate(), or onActivityCreated()
Yeah, but when exactly to init the loader?
→ TRICKY…
→ If the loader already has an answer for you, then
the
onLoaderFinished callback will fire - so you should
init the loader after you’re ready for this callback.
Quiz Time
What to do when a loader needs to change?
→ Call RestartLoader. The loader will get an
onReset(),
and the activity will get an onLoaderReset() call.
You should release everything there, and let a new
loader do the entire cycle for you.
How to restart a loader
The loader manager has a method for that:
getLoaderManager().restartLoader( LOADER_ID,
Parameter,
LoaderCallback);
Any Questions?
So, What’s a cursor loader?
a CursorLoader is an AsyncTaskLoader,
designed to handle Cursors -
Which is what our ContentProvider provides,
with its SQLite database and the
SQLiteOpenHelper
How to use a Cursor Loader
1)Create a Loader ID constant. Simple int.
1)Fill-in Loader callbacks - for Cursor
1)Init a loader with LoaderManager
How to use a Cursor Loader - Step 1
private static final int
WORDS_LOADER_ID=1337;
private WordsAdapter adapter;
// initialize in onCreate()
How to use a Cursor Loader - Step 2
Implement the loader callbacks, keep the
adapter.
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
How to use a Cursor Loader - Step 3
Step 3 - Initialize as usual
getLoaderManager()
.initLoader(WORDS_LOADER_ID,
null,
this);
Cursor Loader - What’s the benifit?
Super easy to implement (‫)יחסית‬
All the benefits of loaders -
Minimum lines of code.
Implement the Adapter
See code,
public View newView(Context context, Cursor cursor, ViewGroup parent)
public void bindView(View view, Context context, Cursor cursor)
Let’s go over the agenda
In our previous sessions, We talked about:
Handlers and AsyncTasks (2)
The activity lifecycle (4a)
Databases and Cursors (4b)
Let’s go over the agenda
Loaders are object that abstract data retrieval
and observation, and simplify its
implementation regarding:
Activity Lifecycle
Data Observation
Cache
And is implemented in 3 simple steps.
Let’s go over the agenda
CursorLoaders are loaders that are specific
to accessing ContentProviders, and make the
best-practices implementation really easy.
Any Questions?
References - This lecture
Slides
http://goo.gl/aXMfI0
GitHub
https://github.com/felixidan/Session4C
References - Loaders
Loaders API Guide
http://developer.android.com/guide/components/loaders.html
Implementing Loaders @ Android Design Patterns
http://www.androiddesignpatterns.com/2012/08/implementing-loaders.html
AsyncTaskLoader documentation
http://developer.android.com/reference/android/content/AsyncTaskLoader.html
Thank you,
We’ll stick around for any questions you might
have, or any issues you’ve stumbled upon
when implementing Sunhine or your app.
Drive home safely.
Thank you,
We’ll stick around for any questions you might
have, or any issues you’ve stumbled upon
when implementing Sunhine or your app.
Drive home safely.

More Related Content

Similar to Lecture #4 c loaders and co.

Renegades Guide to Hacking Rails Internals
Renegades Guide to Hacking Rails InternalsRenegades Guide to Hacking Rails Internals
Renegades Guide to Hacking Rails InternalsAllan Grant
 
How it's made - MyGet (CloudBurst)
How it's made - MyGet (CloudBurst)How it's made - MyGet (CloudBurst)
How it's made - MyGet (CloudBurst)Maarten Balliauw
 
Containers & Dependency in Ember.js
Containers & Dependency in Ember.jsContainers & Dependency in Ember.js
Containers & Dependency in Ember.jsMatthew Beale
 
Hadoop cluster performance profiler
Hadoop cluster performance profilerHadoop cluster performance profiler
Hadoop cluster performance profilerIhor Bobak
 
OGCE Project Overview
OGCE Project OverviewOGCE Project Overview
OGCE Project Overviewmarpierc
 
Understanding and Extending Prometheus AlertManager
Understanding and Extending Prometheus AlertManagerUnderstanding and Extending Prometheus AlertManager
Understanding and Extending Prometheus AlertManagerLee Calcote
 
OSMC 2021 | inspectIT Ocelot: Dynamic OpenTelemetry Instrumentation at Runtime
OSMC 2021 | inspectIT Ocelot: Dynamic OpenTelemetry Instrumentation at RuntimeOSMC 2021 | inspectIT Ocelot: Dynamic OpenTelemetry Instrumentation at Runtime
OSMC 2021 | inspectIT Ocelot: Dynamic OpenTelemetry Instrumentation at RuntimeNETWAYS
 
Android Intermediatte IAK full
Android Intermediatte IAK fullAndroid Intermediatte IAK full
Android Intermediatte IAK fullAhmad Arif Faizin
 
Spinnaker Summit 2019: Where are we heading? The Future of Continuous Delivery
Spinnaker Summit 2019: Where are we heading? The Future of Continuous DeliverySpinnaker Summit 2019: Where are we heading? The Future of Continuous Delivery
Spinnaker Summit 2019: Where are we heading? The Future of Continuous DeliveryAndrew Phillips
 
Meteor Meet-up San Diego December 2014
Meteor Meet-up San Diego December 2014Meteor Meet-up San Diego December 2014
Meteor Meet-up San Diego December 2014Lou Sacco
 
Meetup 2022 - APIs with Quarkus.pdf
Meetup 2022 - APIs with Quarkus.pdfMeetup 2022 - APIs with Quarkus.pdf
Meetup 2022 - APIs with Quarkus.pdfLuca Mattia Ferrari
 
OpenTelemetry For Developers
OpenTelemetry For DevelopersOpenTelemetry For Developers
OpenTelemetry For DevelopersKevin Brockhoff
 
Load-testing 101 for Startups with Artillery.io
Load-testing 101 for Startups with Artillery.ioLoad-testing 101 for Startups with Artillery.io
Load-testing 101 for Startups with Artillery.ioHassy Veldstra
 
Containerizing your Security Operations Center
Containerizing your Security Operations CenterContainerizing your Security Operations Center
Containerizing your Security Operations CenterJimmy Mesta
 
Advanced Container Management and Scheduling
Advanced Container Management and SchedulingAdvanced Container Management and Scheduling
Advanced Container Management and SchedulingAmazon Web Services
 
Android app code mediator
Android app code mediatorAndroid app code mediator
Android app code mediatorFatimaYousif11
 
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...Paul Jensen
 
Deep dive into Android async operations
Deep dive into Android async operationsDeep dive into Android async operations
Deep dive into Android async operationsMateusz Grzechociński
 

Similar to Lecture #4 c loaders and co. (20)

Renegades Guide to Hacking Rails Internals
Renegades Guide to Hacking Rails InternalsRenegades Guide to Hacking Rails Internals
Renegades Guide to Hacking Rails Internals
 
How it's made - MyGet (CloudBurst)
How it's made - MyGet (CloudBurst)How it's made - MyGet (CloudBurst)
How it's made - MyGet (CloudBurst)
 
Containers & Dependency in Ember.js
Containers & Dependency in Ember.jsContainers & Dependency in Ember.js
Containers & Dependency in Ember.js
 
Hadoop cluster performance profiler
Hadoop cluster performance profilerHadoop cluster performance profiler
Hadoop cluster performance profiler
 
OGCE Project Overview
OGCE Project OverviewOGCE Project Overview
OGCE Project Overview
 
Understanding and Extending Prometheus AlertManager
Understanding and Extending Prometheus AlertManagerUnderstanding and Extending Prometheus AlertManager
Understanding and Extending Prometheus AlertManager
 
OSMC 2021 | inspectIT Ocelot: Dynamic OpenTelemetry Instrumentation at Runtime
OSMC 2021 | inspectIT Ocelot: Dynamic OpenTelemetry Instrumentation at RuntimeOSMC 2021 | inspectIT Ocelot: Dynamic OpenTelemetry Instrumentation at Runtime
OSMC 2021 | inspectIT Ocelot: Dynamic OpenTelemetry Instrumentation at Runtime
 
Android Intermediatte IAK full
Android Intermediatte IAK fullAndroid Intermediatte IAK full
Android Intermediatte IAK full
 
Android intermediatte Full
Android intermediatte FullAndroid intermediatte Full
Android intermediatte Full
 
Spinnaker Summit 2019: Where are we heading? The Future of Continuous Delivery
Spinnaker Summit 2019: Where are we heading? The Future of Continuous DeliverySpinnaker Summit 2019: Where are we heading? The Future of Continuous Delivery
Spinnaker Summit 2019: Where are we heading? The Future of Continuous Delivery
 
Meteor Meet-up San Diego December 2014
Meteor Meet-up San Diego December 2014Meteor Meet-up San Diego December 2014
Meteor Meet-up San Diego December 2014
 
Meetup 2022 - APIs with Quarkus.pdf
Meetup 2022 - APIs with Quarkus.pdfMeetup 2022 - APIs with Quarkus.pdf
Meetup 2022 - APIs with Quarkus.pdf
 
OpenTelemetry For Developers
OpenTelemetry For DevelopersOpenTelemetry For Developers
OpenTelemetry For Developers
 
Load-testing 101 for Startups with Artillery.io
Load-testing 101 for Startups with Artillery.ioLoad-testing 101 for Startups with Artillery.io
Load-testing 101 for Startups with Artillery.io
 
Containerizing your Security Operations Center
Containerizing your Security Operations CenterContainerizing your Security Operations Center
Containerizing your Security Operations Center
 
Advanced Container Management and Scheduling
Advanced Container Management and SchedulingAdvanced Container Management and Scheduling
Advanced Container Management and Scheduling
 
Android app code mediator
Android app code mediatorAndroid app code mediator
Android app code mediator
 
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
 
RxJava@Android
RxJava@AndroidRxJava@Android
RxJava@Android
 
Deep dive into Android async operations
Deep dive into Android async operationsDeep dive into Android async operations
Deep dive into Android async operations
 

More from Vitali Pekelis

Droidkaigi2019thagikura 190208135940
Droidkaigi2019thagikura 190208135940Droidkaigi2019thagikura 190208135940
Droidkaigi2019thagikura 190208135940Vitali Pekelis
 
Google i o &amp; android q changes 2019
Google i o &amp; android q changes 2019Google i o &amp; android q changes 2019
Google i o &amp; android q changes 2019Vitali Pekelis
 
Advanced #6 clean architecture
Advanced #6  clean architectureAdvanced #6  clean architecture
Advanced #6 clean architectureVitali Pekelis
 
Advanced #4 GPU & Animations
Advanced #4   GPU & AnimationsAdvanced #4   GPU & Animations
Advanced #4 GPU & AnimationsVitali Pekelis
 
Advanced #2 networking
Advanced #2   networkingAdvanced #2   networking
Advanced #2 networkingVitali Pekelis
 
Advanced #1 cpu, memory
Advanced #1   cpu, memoryAdvanced #1   cpu, memory
Advanced #1 cpu, memoryVitali Pekelis
 
All the support you need. Support libs in Android
All the support you need. Support libs in AndroidAll the support you need. Support libs in Android
All the support you need. Support libs in AndroidVitali Pekelis
 
How to build Sdk? Best practices
How to build Sdk? Best practicesHow to build Sdk? Best practices
How to build Sdk? Best practicesVitali Pekelis
 
Android design patterns
Android design patternsAndroid design patterns
Android design patternsVitali Pekelis
 
Advanced #3 threading
Advanced #3  threading Advanced #3  threading
Advanced #3 threading Vitali Pekelis
 
Mobile ui fruit or delicious sweets
Mobile ui  fruit or delicious sweetsMobile ui  fruit or delicious sweets
Mobile ui fruit or delicious sweetsVitali Pekelis
 
Session #4 b content providers
Session #4 b  content providersSession #4 b  content providers
Session #4 b content providersVitali Pekelis
 
Advanced #2 - ui perf
 Advanced #2 - ui perf Advanced #2 - ui perf
Advanced #2 - ui perfVitali Pekelis
 
Android design lecture #3
Android design   lecture #3Android design   lecture #3
Android design lecture #3Vitali Pekelis
 

More from Vitali Pekelis (20)

Droidkaigi2019thagikura 190208135940
Droidkaigi2019thagikura 190208135940Droidkaigi2019thagikura 190208135940
Droidkaigi2019thagikura 190208135940
 
Droidkaigi 2019
Droidkaigi 2019Droidkaigi 2019
Droidkaigi 2019
 
Google i o &amp; android q changes 2019
Google i o &amp; android q changes 2019Google i o &amp; android q changes 2019
Google i o &amp; android q changes 2019
 
Android Q 2019
Android Q 2019Android Q 2019
Android Q 2019
 
Advanced #6 clean architecture
Advanced #6  clean architectureAdvanced #6  clean architecture
Advanced #6 clean architecture
 
Advanced #4 GPU & Animations
Advanced #4   GPU & AnimationsAdvanced #4   GPU & Animations
Advanced #4 GPU & Animations
 
Advanced #2 networking
Advanced #2   networkingAdvanced #2   networking
Advanced #2 networking
 
Advanced #2 threading
Advanced #2   threadingAdvanced #2   threading
Advanced #2 threading
 
Advanced #1 cpu, memory
Advanced #1   cpu, memoryAdvanced #1   cpu, memory
Advanced #1 cpu, memory
 
All the support you need. Support libs in Android
All the support you need. Support libs in AndroidAll the support you need. Support libs in Android
All the support you need. Support libs in Android
 
How to build Sdk? Best practices
How to build Sdk? Best practicesHow to build Sdk? Best practices
How to build Sdk? Best practices
 
Di &amp; dagger
Di &amp; daggerDi &amp; dagger
Di &amp; dagger
 
Android design patterns
Android design patternsAndroid design patterns
Android design patterns
 
Advanced #3 threading
Advanced #3  threading Advanced #3  threading
Advanced #3 threading
 
Mobile ui fruit or delicious sweets
Mobile ui  fruit or delicious sweetsMobile ui  fruit or delicious sweets
Mobile ui fruit or delicious sweets
 
Session #4 b content providers
Session #4 b  content providersSession #4 b  content providers
Session #4 b content providers
 
Advanced #2 - ui perf
 Advanced #2 - ui perf Advanced #2 - ui perf
Advanced #2 - ui perf
 
Android meetup
Android meetupAndroid meetup
Android meetup
 
Android design lecture #3
Android design   lecture #3Android design   lecture #3
Android design lecture #3
 
From newbie to ...
From newbie to ...From newbie to ...
From newbie to ...
 

Recently uploaded

software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxnada99848
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 

Recently uploaded (20)

software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptx
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 

Lecture #4 c loaders and co.

  • 1. Loaders, Cursor Loaders And Threads Idan Felix, 16/3/2015
  • 2. Agenda Loaders CursorLoader What What Why Why How How and how does it all fit in?
  • 3. First things first Elections day tomorrow, Don’t forget to vote.
  • 4. Last week: How to talk to databases
  • 5. 2 weeks ago: Activity lifecycle Source: developer.android.com/training/basics/activity-lifecycle/starting.html
  • 6. Where would you load your data? onCreate? onStart? onResume? What happens when the phone rotates? how to get fresh data as soon as it’s ready? How to get the data? AsyncTask?
  • 7. a Loader is an Android Specific pattern, Designed so that async data retrieval is… Easy to implement PROPERLY. So, What are Loaders?
  • 8. Available since Android 3.0 (Honeycomb, API level 11 and support libs), to Activities and Fragments, Also use that Observer Pattern we’ve seen last week, Are cached between configuration changes. So, What are Loaders?
  • 9. - Recommended way to load data BUT NOT ONLY! - Works best with Cursors, BUT NOT ONLY! Why to use loaders?
  • 10. API Breakdown Loader Abstract class that performs async loading of data. It can monitor its data-source while active.
  • 11. API Breakdown More commonly, we’ll see these: a loader implementation that provies an AsyncTask to do to loading, an AsyncTaskLoader that is used to query data from a ContentProvider and returns a Cursor. Loader Async Task Loader Cursor Loader
  • 12. API Breakdown This is where the magic is: LoaderManager helps an activity manage long-running operations with the activity lifecylce. Loader Async Task Loader Cursor Loader LoaderManager
  • 13. API Breakdown The callbacks are used to abstract the specific loader from the loader manager. 3 Methods: onCreateLoader (int id, Bundle args), onLoadFinished(Loader<D> loader, D data), onLoaderReset(Loader<D> loader) Loader Async Task Loader Cursor Loader LoaderManager LoaderCallbacks <D>
  • 14. How to use loaders? Step 1: Create a unique ID for your loader. Step 2: LoaderManager.Loadercallbacks<D> Step 3: init the loader with the id.
  • 15. How to use loaders? - Step 1 Have a constant int, unique for the loader in the activity. private static final int LOADER_ID = 31415;
  • 16. How to use loaders? - Step 2 Implement the LoaderManager.LoaderCallbacks<D>. Our demo will use a Long, so: implements LoaderManager.LoaderCallbacks<Long>
  • 17. How to use loaders? - Step 3 in the Activity’s onCreate, or in the Fragment’s onActivityCreate, init the loader as such: getLoaderManager().initLoader( LOADER_ID, Parameter, LoaderCallback);
  • 18. in the Activity’s onCreate, or in the Fragment’s onActivityCreate, init the loader as such: getLoaderManager().initLoader( LOADER_ID, Parameter, LoaderCallback); How to use loaders? If the activity has multiple loaders, each should have its own unique ID. This enables the LoaderManager to re- use the Loader.
  • 19. How to use loaders? in the Activity’s onCreate, or in the Fragment’s onActivityCreate, init the loader as such: getLoaderManager().initLoader( LOADER_ID, Parameter, LoaderCallback); The parameter is passed to the loader.
  • 20. How to use loaders? in the Activity’s onCreate, or in the Fragment’s onActivityCreate, init the loader as such: getLoaderManager().initLoader( LOADER_ID, Parameter, LoaderCallback); the manager uses this instance of LoaderManager.LoaderCallbacks to manage the loader’s lifecycle.
  • 21. Loader Initialization - 1 when LM.initLoader is called, if the loader does not exist, the callback’s onCreateLoader method is called. That’s where you create the loader.
  • 22. Loader Initialization - 2 when LM.initLoader is called, if the loader does exist, the callback’s onCreateLoader method is not called - but the new Listener replaces the old listener. That’s how you get away with Configuration Changes.
  • 23. Demo We’ll see 2 activities. in onCreate, one starts a 5 second async task, and the other starts a 5 second loader. We’ll rotate the device after ~2 seconds in each. Check out the LogCat too - to see just the 1 creation.
  • 24. Yonatan’s Demo adb shell dumpsys com.example.felixidan.loadersdemo
  • 25. Story time: AsyncTaskLoader - Fail How I thought it would look: public class DemoLoader extends AsyncTaskLoader<Long> { public DemoLoader(Context context) { super(context); } @Override public Long loadInBackground() { try { Thread.sleep(5000); } catch (InterruptedException e) {} return new Long(SystemClock.upTimeMillies()); } } This code moved to “TheBrain”.
  • 26. Story time: AsyncTaskLoader - Fail However, it was not that simple - the DemoLoader class is about 100 lines long (and the “real” data loading is a one-liner). Why?
  • 27. Story time: AsyncTaskLoader - Epif. I did not consider the responsibilities of the loader: Getting Data Keeping Data Observing Data source Lifecycle
  • 28. Quiz Time Is it OK to have 2 loaders with the same ID? → Yes, if they’re not on the same Activity. Can an activity have multiple loaders? → Yes, but they have to have a different ID. What types can a loader return? → Everything, as long as it’s an Object.
  • 29. Quiz Time How does this mechanism handles configuration changes? → The loader manager keeps the loader, but replaces the callbacks object - so the most recent activity gets notified when the loader is done. What happens when the data is changed? → The Loader is notified (by the Observer) and pushes new information to the onLoaderFinished method.
  • 30. Quiz Time When to init the loader? (to call LoaderManager.init) → In onCreate(), or onActivityCreated() Yeah, but when exactly to init the loader? → TRICKY… → If the loader already has an answer for you, then the onLoaderFinished callback will fire - so you should init the loader after you’re ready for this callback.
  • 31. Quiz Time What to do when a loader needs to change? → Call RestartLoader. The loader will get an onReset(), and the activity will get an onLoaderReset() call. You should release everything there, and let a new loader do the entire cycle for you.
  • 32. How to restart a loader The loader manager has a method for that: getLoaderManager().restartLoader( LOADER_ID, Parameter, LoaderCallback);
  • 34. So, What’s a cursor loader? a CursorLoader is an AsyncTaskLoader, designed to handle Cursors - Which is what our ContentProvider provides, with its SQLite database and the SQLiteOpenHelper
  • 35. How to use a Cursor Loader 1)Create a Loader ID constant. Simple int. 1)Fill-in Loader callbacks - for Cursor 1)Init a loader with LoaderManager
  • 36. How to use a Cursor Loader - Step 1 private static final int WORDS_LOADER_ID=1337; private WordsAdapter adapter; // initialize in onCreate()
  • 37. How to use a Cursor Loader - Step 2 Implement the loader callbacks, keep the adapter. @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { adapter.swapCursor(data); } @Override public void onLoaderReset(Loader<Cursor> loader) { adapter.swapCursor(null); }
  • 38. How to use a Cursor Loader - Step 3 Step 3 - Initialize as usual getLoaderManager() .initLoader(WORDS_LOADER_ID, null, this);
  • 39. Cursor Loader - What’s the benifit? Super easy to implement (‫)יחסית‬ All the benefits of loaders - Minimum lines of code.
  • 40. Implement the Adapter See code, public View newView(Context context, Cursor cursor, ViewGroup parent) public void bindView(View view, Context context, Cursor cursor)
  • 41. Let’s go over the agenda In our previous sessions, We talked about: Handlers and AsyncTasks (2) The activity lifecycle (4a) Databases and Cursors (4b)
  • 42. Let’s go over the agenda Loaders are object that abstract data retrieval and observation, and simplify its implementation regarding: Activity Lifecycle Data Observation Cache And is implemented in 3 simple steps.
  • 43. Let’s go over the agenda CursorLoaders are loaders that are specific to accessing ContentProviders, and make the best-practices implementation really easy.
  • 45. References - This lecture Slides http://goo.gl/aXMfI0 GitHub https://github.com/felixidan/Session4C
  • 46. References - Loaders Loaders API Guide http://developer.android.com/guide/components/loaders.html Implementing Loaders @ Android Design Patterns http://www.androiddesignpatterns.com/2012/08/implementing-loaders.html AsyncTaskLoader documentation http://developer.android.com/reference/android/content/AsyncTaskLoader.html
  • 47. Thank you, We’ll stick around for any questions you might have, or any issues you’ve stumbled upon when implementing Sunhine or your app. Drive home safely.
  • 48. Thank you, We’ll stick around for any questions you might have, or any issues you’ve stumbled upon when implementing Sunhine or your app. Drive home safely.