SlideShare a Scribd company logo
1 of 9
Android
AsyncTask
Perfect APK
Android AsyncTask Tutorial
Almost every Android app has some tasks that need to be executed in the background, such as network operations and CPU intensive
operations. Many times these tasks are required by the UI thread, however executing them in the UI the will compromise the
responsiveness of the app.
The AsyncTask class is is a convenience generic abstract class for executing relatively short tasks in a background thread and updating the
UI thread. AsyncTask has 3 type parameters:
● Params - the class of the params array that is passed to the execute() method which is called in the UI thread and received in the
doInBackground() method which is called in the background thread.
● Progress - the class of the values array that is passed by the publishProgress() method which is called in the background thread
and returned by the onProgressUpdate() method which is called in the UI thread.
● Result - the class of the result that is passed returned by the execute() method and returned by the onPostExecute() method which
is called in the UI thread.
The doInBackground() method is an abstract method that defines the actual background task.
Updating an adapter from a background thread
In this tutorial we will use an AsynTask for loading data for a GridView. The example in this tutorial is based on the GridView Tutorial, only
this time the view will be created using an empty data-set, and the data set will be updated using an AsyncTask.
The data that is loaded for this GridView is the icons and labels of the applications that are installed on the device. This data is loaded using
the PackageManager. The list of installed applications is obtained by calling the getInstalledApplications() method, and the icon and label
of each application is obtained by calling the getApplicationIcon()and getApplicationLabel() methods. The example in this tutorial includes
the following components:
● AsyncAppInfoLoader - the base class used for loading the application info.
● GridViewAdapter - the adapter used in the GridView Tutorial.
● Item Layout File - a GridView item XML layout file to be used by the adapter. It is similar to the file used in the GridView Tutorial
with some minor changes.
● Fragment View Layout File - the file used in the GridView Tutorial.
● AsyncTaskDemoFragment - the fragment that contains the GridView.
AsyncAppInfoLoader
The base class used for loading the application info. This class extends the AsycTask class, with the following type parameters:
● Params - the PackageManager class. Used for loading the application info.
● Progress - the GridViewItem class used in the GridView tutorial.
● Result - Integer representing for the number of loaded items.
Below is code for AsyncAppInfoLoader class:
1. public class AsyncAppInfoLoader extends AsyncTask<PackageManager, GridViewItem, Integer> {
2.
3. @Override
4. protected Integer doInBackground(PackageManager... params) {
5. // this method executes the task in a background thread
6. PackageManager packageManager = params[0]; // the PackageManager for loading the data
7. List<ApplicationInfo> appInfoList = packageManager.getInstalledApplications(PackageManager.GET_META_DATA);
8. int index = 0;
9.
Item Layout File
The item view is described in the res/layout/gridview_item.xml file below:
1. <?xml version="1.0" encoding="utf-8"?>
2. <!-- the parent view -->
3. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
4. android:layout_width="match_parent"
5. android:layout_height="match_parent"
6. android:layout_gravity="center"
7. android:gravity="center"
8. android:padding="5dp" >
9.
10. <!-- the ImageView for the icon -->
11. <ImageView android:id="@+id/ivIcon"
12. android:layout_width="50dp"
AsyncTaskDemoFragment
The fragment that contains the GridView. This class also includes the GridViewAppInfoLoader class below which extends the
AsyncAppInfoLoader class and overrides the onProgressUpdate() and onPostExecute()methods for updating the adapter in the UI thread:
1. public class AsyncTaskDemoFragment extends Fragment implements OnItemClickListener {
2. private List<GridViewItem> mItems; // GridView items list
3. private GridViewAdapter mAdapter; // GridView adapter
4. private Activity mActivity; // the parent activity
5. private GridViewAppInfoLoader mLoader; // the application info loader
6.
7. @Override
8. public void onAttach(Activity activity) {
9. super.onAttach(activity);
10. mActivity = activity;
11.
AsyncTaskDemoFragment
1. @Override
2. public View onCreateView(LayoutInflater inflater, ViewGroup container,
3. Bundle savedInstanceState) {
4. // inflate the root view of the fragment
5. View fragmentView = inflater.inflate(R.layout.fragment_gridview, container, false);
6.
7. // initialize the adapter
8. mAdapter = new GridViewAdapter(getActivity(), mItems);
9.
10. // initialize the GridView
11. GridView gridView = (GridView) fragmentView.findViewById(R.id.gridView);
12. gridView.setAdapter(mAdapter);
13. gridView.setOnItemClickListener(this);
14.
15. // start loading
16. mLoader = new GridViewAppInfoLoader();
17. mLoader.execute(mActivity.getPackageManager());
18.
19. return fragmentView;
20. }
AsyncTaskDemoFragment
1. @Override
2. public void onItemClick(AdapterView<?> parent, View view, int position,
3. long id) {
4. // retrieve the GridView item
5. GridViewItem item = mItems.get(position);
6.
7. // do something
8. Toast.makeText(getActivity(), item.title, Toast.LENGTH_SHORT).show();
9. }
10.
11. private class GridViewAppInfoLoader extends AsyncAppInfoLoader {
12. @Override
13. protected void onProgressUpdate(GridViewItem... values) {
14.
15. // check that the fragment is still attached to activity
16. if(mActivity != null) {
17. // add the new item to the data set
18. mItems.add(values[0]);
19.
20. // notify the adapter
21. mAdapter.notifyDataSetChanged();
22. }
23. }
AsyncTaskDemoFragment
1. As@Override
2. protected void onPostExecute(Integer result) {
3. // check that the fragment is still attached to activity
4. if(mActivity != null) {
5. Toast.makeText(mActivity, getString(R.string.post_execute_message, result),
Toast.LENGTH_SHORT).show();
6. }
7. }
8. }
9. }
yncTaskDemoFragment

More Related Content

What's hot

Java.NET: Integration of Java and .NET
Java.NET: Integration of Java and .NETJava.NET: Integration of Java and .NET
Java.NET: Integration of Java and .NETDr Sukhpal Singh Gill
 
IT talk: Как я перестал бояться и полюбил TestNG
IT talk: Как я перестал бояться и полюбил TestNGIT talk: Как я перестал бояться и полюбил TestNG
IT talk: Как я перестал бояться и полюбил TestNGDataArt
 
Identifing Listeners and Filters
Identifing Listeners and FiltersIdentifing Listeners and Filters
Identifing Listeners and FiltersPeople Strategists
 
Servlets - filter, listeners, wrapper, internationalization
Servlets -  filter, listeners, wrapper, internationalizationServlets -  filter, listeners, wrapper, internationalization
Servlets - filter, listeners, wrapper, internationalizationsusant sahu
 
New Microsoft Word Document.doc
New Microsoft Word Document.docNew Microsoft Word Document.doc
New Microsoft Word Document.docbutest
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technologyMinal Maniar
 
Will it run or will it not run? Background processes in Android 6 - Anna Lifs...
Will it run or will it not run? Background processes in Android 6 - Anna Lifs...Will it run or will it not run? Background processes in Android 6 - Anna Lifs...
Will it run or will it not run? Background processes in Android 6 - Anna Lifs...DroidConTLV
 
Programming Server side with Sevlet
 Programming Server side with Sevlet  Programming Server side with Sevlet
Programming Server side with Sevlet backdoor
 
Usage Note of Microsoft Dependency Walker
Usage Note of Microsoft Dependency WalkerUsage Note of Microsoft Dependency Walker
Usage Note of Microsoft Dependency WalkerWilliam Lee
 
Databases in Android Application
Databases in Android ApplicationDatabases in Android Application
Databases in Android ApplicationMark Lester Navarro
 

What's hot (20)

Java.NET: Integration of Java and .NET
Java.NET: Integration of Java and .NETJava.NET: Integration of Java and .NET
Java.NET: Integration of Java and .NET
 
React hooks
React hooksReact hooks
React hooks
 
IT talk: Как я перестал бояться и полюбил TestNG
IT talk: Как я перестал бояться и полюбил TestNGIT talk: Как я перестал бояться и полюбил TestNG
IT talk: Как я перестал бояться и полюбил TestNG
 
Identifing Listeners and Filters
Identifing Listeners and FiltersIdentifing Listeners and Filters
Identifing Listeners and Filters
 
Servlets - filter, listeners, wrapper, internationalization
Servlets -  filter, listeners, wrapper, internationalizationServlets -  filter, listeners, wrapper, internationalization
Servlets - filter, listeners, wrapper, internationalization
 
Lab 5-Android
Lab 5-AndroidLab 5-Android
Lab 5-Android
 
New Microsoft Word Document.doc
New Microsoft Word Document.docNew Microsoft Word Document.doc
New Microsoft Word Document.doc
 
Types of MessageRouting in Mule
Types of MessageRouting in MuleTypes of MessageRouting in Mule
Types of MessageRouting in Mule
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
 
Will it run or will it not run? Background processes in Android 6 - Anna Lifs...
Will it run or will it not run? Background processes in Android 6 - Anna Lifs...Will it run or will it not run? Background processes in Android 6 - Anna Lifs...
Will it run or will it not run? Background processes in Android 6 - Anna Lifs...
 
Exceptions
ExceptionsExceptions
Exceptions
 
Concurrency and parallel in .net
Concurrency and parallel in .netConcurrency and parallel in .net
Concurrency and parallel in .net
 
Programming Server side with Sevlet
 Programming Server side with Sevlet  Programming Server side with Sevlet
Programming Server side with Sevlet
 
Servlet Filter
Servlet FilterServlet Filter
Servlet Filter
 
Usage Note of Microsoft Dependency Walker
Usage Note of Microsoft Dependency WalkerUsage Note of Microsoft Dependency Walker
Usage Note of Microsoft Dependency Walker
 
Java 8 new features
Java 8 new features Java 8 new features
Java 8 new features
 
yii1
yii1yii1
yii1
 
Servlet session 9
Servlet   session 9Servlet   session 9
Servlet session 9
 
Databases in Android Application
Databases in Android ApplicationDatabases in Android Application
Databases in Android Application
 
Struts
StrutsStruts
Struts
 

Viewers also liked

Sandbox Introduction
Sandbox IntroductionSandbox Introduction
Sandbox Introductionmsimkin
 
Security threats in Android OS + App Permissions
Security threats in Android OS + App PermissionsSecurity threats in Android OS + App Permissions
Security threats in Android OS + App PermissionsHariharan Ganesan
 
Android training day 4
Android training day 4Android training day 4
Android training day 4Vivek Bhusal
 
Tips dan Third Party Library untuk Android - Part 1
Tips dan Third Party Library untuk Android - Part 1Tips dan Third Party Library untuk Android - Part 1
Tips dan Third Party Library untuk Android - Part 1Ibnu Sina Wardy
 
Web Services and Android - OSSPAC 2009
Web Services and Android - OSSPAC 2009Web Services and Android - OSSPAC 2009
Web Services and Android - OSSPAC 2009sullis
 
Anatomizing online payment systems: hack to shop
Anatomizing online payment systems: hack to shopAnatomizing online payment systems: hack to shop
Anatomizing online payment systems: hack to shopAbhinav Mishra
 
Android permission system
Android permission systemAndroid permission system
Android permission systemShivang Goel
 
Android permission system
Android permission systemAndroid permission system
Android permission systemShivang Goel
 
Android secuirty permission - upload
Android secuirty   permission - uploadAndroid secuirty   permission - upload
Android secuirty permission - uploadBin Yang
 
Android 6.0 permission change
Android 6.0 permission changeAndroid 6.0 permission change
Android 6.0 permission change彥彬 洪
 
Simple JSON parser
Simple JSON parserSimple JSON parser
Simple JSON parserDongjun Lee
 
Android webservices
Android webservicesAndroid webservices
Android webservicesKrazy Koder
 
Android porting for dummies @droidconin 2011
Android porting for dummies @droidconin 2011Android porting for dummies @droidconin 2011
Android porting for dummies @droidconin 2011pundiramit
 
Android json parser tutorial – example
Android json parser tutorial – exampleAndroid json parser tutorial – example
Android json parser tutorial – exampleRajat Ghai
 

Viewers also liked (20)

Sandbox Introduction
Sandbox IntroductionSandbox Introduction
Sandbox Introduction
 
Security threats in Android OS + App Permissions
Security threats in Android OS + App PermissionsSecurity threats in Android OS + App Permissions
Security threats in Android OS + App Permissions
 
Android training day 4
Android training day 4Android training day 4
Android training day 4
 
Tips dan Third Party Library untuk Android - Part 1
Tips dan Third Party Library untuk Android - Part 1Tips dan Third Party Library untuk Android - Part 1
Tips dan Third Party Library untuk Android - Part 1
 
Web Services and Android - OSSPAC 2009
Web Services and Android - OSSPAC 2009Web Services and Android - OSSPAC 2009
Web Services and Android - OSSPAC 2009
 
Anatomizing online payment systems: hack to shop
Anatomizing online payment systems: hack to shopAnatomizing online payment systems: hack to shop
Anatomizing online payment systems: hack to shop
 
Android permission system
Android permission systemAndroid permission system
Android permission system
 
Android permission system
Android permission systemAndroid permission system
Android permission system
 
Android(1)
Android(1)Android(1)
Android(1)
 
Android secuirty permission - upload
Android secuirty   permission - uploadAndroid secuirty   permission - upload
Android secuirty permission - upload
 
Json Tutorial
Json TutorialJson Tutorial
Json Tutorial
 
Android 6.0 permission change
Android 6.0 permission changeAndroid 6.0 permission change
Android 6.0 permission change
 
Basic Android Push Notification
Basic Android Push NotificationBasic Android Push Notification
Basic Android Push Notification
 
Android new permission model
Android new permission modelAndroid new permission model
Android new permission model
 
JSON overview and demo
JSON overview and demoJSON overview and demo
JSON overview and demo
 
Simple JSON parser
Simple JSON parserSimple JSON parser
Simple JSON parser
 
App Permissions
App PermissionsApp Permissions
App Permissions
 
Android webservices
Android webservicesAndroid webservices
Android webservices
 
Android porting for dummies @droidconin 2011
Android porting for dummies @droidconin 2011Android porting for dummies @droidconin 2011
Android porting for dummies @droidconin 2011
 
Android json parser tutorial – example
Android json parser tutorial – exampleAndroid json parser tutorial – example
Android json parser tutorial – example
 

Similar to Android AsyncTask Tutorial

Session 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdfSession 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdfEngmohammedAlzared
 
Angular performance slides
Angular performance slidesAngular performance slides
Angular performance slidesDavid Barreto
 
Angularjs2 presentation
Angularjs2 presentationAngularjs2 presentation
Angularjs2 presentationdharisk
 
Android async task
Android async taskAndroid async task
Android async taskMadhu Venkat
 
Threads handlers and async task, widgets - day8
Threads   handlers and async task, widgets - day8Threads   handlers and async task, widgets - day8
Threads handlers and async task, widgets - day8Utkarsh Mankad
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorialmaster760
 
Answer1)Responsive design is the idea where all the developed pag.pdf
Answer1)Responsive design is the idea where all the developed pag.pdfAnswer1)Responsive design is the idea where all the developed pag.pdf
Answer1)Responsive design is the idea where all the developed pag.pdfankitcomputer11
 
Android Studio (Java)Modify the Networking app (code given below.docx
Android Studio (Java)Modify the Networking app (code given below.docxAndroid Studio (Java)Modify the Networking app (code given below.docx
Android Studio (Java)Modify the Networking app (code given below.docxamrit47
 
Android Studio (Java)Modify the Networking app (code given bel.docx
Android Studio (Java)Modify the Networking app (code given bel.docxAndroid Studio (Java)Modify the Networking app (code given bel.docx
Android Studio (Java)Modify the Networking app (code given bel.docxamrit47
 
Android Tutorials - Powering with Selection Widget
Android Tutorials - Powering with Selection WidgetAndroid Tutorials - Powering with Selection Widget
Android Tutorials - Powering with Selection WidgetPrajyot Mainkar
 
Android lifecycle
Android lifecycleAndroid lifecycle
Android lifecycleKumar
 
Android tutorial ppt
Android tutorial pptAndroid tutorial ppt
Android tutorial pptRehna Renu
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorialDanish_k
 
Android programming -_pushing_the_limits
Android programming -_pushing_the_limitsAndroid programming -_pushing_the_limits
Android programming -_pushing_the_limitsDroidcon Berlin
 
Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desaijinaldesailive
 

Similar to Android AsyncTask Tutorial (20)

Session 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdfSession 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdf
 
Angular performance slides
Angular performance slidesAngular performance slides
Angular performance slides
 
Android session-5-sajib
Android session-5-sajibAndroid session-5-sajib
Android session-5-sajib
 
Angularjs2 presentation
Angularjs2 presentationAngularjs2 presentation
Angularjs2 presentation
 
Android async task
Android async taskAndroid async task
Android async task
 
Threads handlers and async task, widgets - day8
Threads   handlers and async task, widgets - day8Threads   handlers and async task, widgets - day8
Threads handlers and async task, widgets - day8
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorial
 
Answer1)Responsive design is the idea where all the developed pag.pdf
Answer1)Responsive design is the idea where all the developed pag.pdfAnswer1)Responsive design is the idea where all the developed pag.pdf
Answer1)Responsive design is the idea where all the developed pag.pdf
 
Android Studio (Java)Modify the Networking app (code given below.docx
Android Studio (Java)Modify the Networking app (code given below.docxAndroid Studio (Java)Modify the Networking app (code given below.docx
Android Studio (Java)Modify the Networking app (code given below.docx
 
Android Studio (Java)Modify the Networking app (code given bel.docx
Android Studio (Java)Modify the Networking app (code given bel.docxAndroid Studio (Java)Modify the Networking app (code given bel.docx
Android Studio (Java)Modify the Networking app (code given bel.docx
 
Android Tutorials - Powering with Selection Widget
Android Tutorials - Powering with Selection WidgetAndroid Tutorials - Powering with Selection Widget
Android Tutorials - Powering with Selection Widget
 
Android lifecycle
Android lifecycleAndroid lifecycle
Android lifecycle
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorial
 
Android tutorial ppt
Android tutorial pptAndroid tutorial ppt
Android tutorial ppt
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorial
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorial
 
Android programming -_pushing_the_limits
Android programming -_pushing_the_limitsAndroid programming -_pushing_the_limits
Android programming -_pushing_the_limits
 
Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desai
 
Android classes in mumbai
Android classes in mumbaiAndroid classes in mumbai
Android classes in mumbai
 
Angularj2.0
Angularj2.0Angularj2.0
Angularj2.0
 

Recently uploaded

Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
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.
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
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.
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 

Recently uploaded (20)

Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
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 ...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
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...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 

Android AsyncTask Tutorial

  • 2. Android AsyncTask Tutorial Almost every Android app has some tasks that need to be executed in the background, such as network operations and CPU intensive operations. Many times these tasks are required by the UI thread, however executing them in the UI the will compromise the responsiveness of the app. The AsyncTask class is is a convenience generic abstract class for executing relatively short tasks in a background thread and updating the UI thread. AsyncTask has 3 type parameters: ● Params - the class of the params array that is passed to the execute() method which is called in the UI thread and received in the doInBackground() method which is called in the background thread. ● Progress - the class of the values array that is passed by the publishProgress() method which is called in the background thread and returned by the onProgressUpdate() method which is called in the UI thread. ● Result - the class of the result that is passed returned by the execute() method and returned by the onPostExecute() method which is called in the UI thread. The doInBackground() method is an abstract method that defines the actual background task.
  • 3. Updating an adapter from a background thread In this tutorial we will use an AsynTask for loading data for a GridView. The example in this tutorial is based on the GridView Tutorial, only this time the view will be created using an empty data-set, and the data set will be updated using an AsyncTask. The data that is loaded for this GridView is the icons and labels of the applications that are installed on the device. This data is loaded using the PackageManager. The list of installed applications is obtained by calling the getInstalledApplications() method, and the icon and label of each application is obtained by calling the getApplicationIcon()and getApplicationLabel() methods. The example in this tutorial includes the following components: ● AsyncAppInfoLoader - the base class used for loading the application info. ● GridViewAdapter - the adapter used in the GridView Tutorial. ● Item Layout File - a GridView item XML layout file to be used by the adapter. It is similar to the file used in the GridView Tutorial with some minor changes. ● Fragment View Layout File - the file used in the GridView Tutorial. ● AsyncTaskDemoFragment - the fragment that contains the GridView.
  • 4. AsyncAppInfoLoader The base class used for loading the application info. This class extends the AsycTask class, with the following type parameters: ● Params - the PackageManager class. Used for loading the application info. ● Progress - the GridViewItem class used in the GridView tutorial. ● Result - Integer representing for the number of loaded items. Below is code for AsyncAppInfoLoader class: 1. public class AsyncAppInfoLoader extends AsyncTask<PackageManager, GridViewItem, Integer> { 2. 3. @Override 4. protected Integer doInBackground(PackageManager... params) { 5. // this method executes the task in a background thread 6. PackageManager packageManager = params[0]; // the PackageManager for loading the data 7. List<ApplicationInfo> appInfoList = packageManager.getInstalledApplications(PackageManager.GET_META_DATA); 8. int index = 0; 9.
  • 5. Item Layout File The item view is described in the res/layout/gridview_item.xml file below: 1. <?xml version="1.0" encoding="utf-8"?> 2. <!-- the parent view --> 3. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 4. android:layout_width="match_parent" 5. android:layout_height="match_parent" 6. android:layout_gravity="center" 7. android:gravity="center" 8. android:padding="5dp" > 9. 10. <!-- the ImageView for the icon --> 11. <ImageView android:id="@+id/ivIcon" 12. android:layout_width="50dp"
  • 6. AsyncTaskDemoFragment The fragment that contains the GridView. This class also includes the GridViewAppInfoLoader class below which extends the AsyncAppInfoLoader class and overrides the onProgressUpdate() and onPostExecute()methods for updating the adapter in the UI thread: 1. public class AsyncTaskDemoFragment extends Fragment implements OnItemClickListener { 2. private List<GridViewItem> mItems; // GridView items list 3. private GridViewAdapter mAdapter; // GridView adapter 4. private Activity mActivity; // the parent activity 5. private GridViewAppInfoLoader mLoader; // the application info loader 6. 7. @Override 8. public void onAttach(Activity activity) { 9. super.onAttach(activity); 10. mActivity = activity; 11.
  • 7. AsyncTaskDemoFragment 1. @Override 2. public View onCreateView(LayoutInflater inflater, ViewGroup container, 3. Bundle savedInstanceState) { 4. // inflate the root view of the fragment 5. View fragmentView = inflater.inflate(R.layout.fragment_gridview, container, false); 6. 7. // initialize the adapter 8. mAdapter = new GridViewAdapter(getActivity(), mItems); 9. 10. // initialize the GridView 11. GridView gridView = (GridView) fragmentView.findViewById(R.id.gridView); 12. gridView.setAdapter(mAdapter); 13. gridView.setOnItemClickListener(this); 14. 15. // start loading 16. mLoader = new GridViewAppInfoLoader(); 17. mLoader.execute(mActivity.getPackageManager()); 18. 19. return fragmentView; 20. }
  • 8. AsyncTaskDemoFragment 1. @Override 2. public void onItemClick(AdapterView<?> parent, View view, int position, 3. long id) { 4. // retrieve the GridView item 5. GridViewItem item = mItems.get(position); 6. 7. // do something 8. Toast.makeText(getActivity(), item.title, Toast.LENGTH_SHORT).show(); 9. } 10. 11. private class GridViewAppInfoLoader extends AsyncAppInfoLoader { 12. @Override 13. protected void onProgressUpdate(GridViewItem... values) { 14. 15. // check that the fragment is still attached to activity 16. if(mActivity != null) { 17. // add the new item to the data set 18. mItems.add(values[0]); 19. 20. // notify the adapter 21. mAdapter.notifyDataSetChanged(); 22. } 23. }
  • 9. AsyncTaskDemoFragment 1. As@Override 2. protected void onPostExecute(Integer result) { 3. // check that the fragment is still attached to activity 4. if(mActivity != null) { 5. Toast.makeText(mActivity, getString(R.string.post_execute_message, result), Toast.LENGTH_SHORT).show(); 6. } 7. } 8. } 9. } yncTaskDemoFragment