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

New Microsoft Word Document.doc
New Microsoft Word Document.docNew Microsoft Word Document.doc
New Microsoft Word Document.doc
butest
 
Programming Server side with Sevlet
 Programming Server side with Sevlet  Programming Server side with Sevlet
Programming Server side with Sevlet
backdoor
 

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 Introduction
msimkin
 
Android webservices
Android webservicesAndroid webservices
Android webservices
Krazy Koder
 

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

Android async task
Android async taskAndroid async task
Android async task
Madhu 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 - day8
Utkarsh Mankad
 
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
ankitcomputer11
 
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
amrit47
 
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
amrit47
 
Android tutorial ppt
Android tutorial pptAndroid tutorial ppt
Android tutorial ppt
Rehna Renu
 
Android programming -_pushing_the_limits
Android programming -_pushing_the_limitsAndroid programming -_pushing_the_limits
Android programming -_pushing_the_limits
Droidcon Berlin
 

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 ppt
Android tutorial pptAndroid tutorial ppt
Android tutorial ppt
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorial
 
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

Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 

Recently uploaded (20)

WSO2CON 2024 - Architecting AI in the Enterprise: APIs and Applications
WSO2CON 2024 - Architecting AI in the Enterprise: APIs and ApplicationsWSO2CON 2024 - Architecting AI in the Enterprise: APIs and Applications
WSO2CON 2024 - Architecting AI in the Enterprise: APIs and Applications
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
WSO2CON 2024 - Lessons from the Field: Legacy Platforms – It's Time to Let Go...
WSO2CON 2024 - Lessons from the Field: Legacy Platforms – It's Time to Let Go...WSO2CON 2024 - Lessons from the Field: Legacy Platforms – It's Time to Let Go...
WSO2CON 2024 - Lessons from the Field: Legacy Platforms – It's Time to Let Go...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
WSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - KanchanaWSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - Kanchana
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
Evolving Data Governance for the Real-time Streaming and AI Era
Evolving Data Governance for the Real-time Streaming and AI EraEvolving Data Governance for the Real-time Streaming and AI Era
Evolving Data Governance for the Real-time Streaming and AI Era
 
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdfAzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
 
WSO2CON 2024 - Software Engineering for Digital Businesses
WSO2CON 2024 - Software Engineering for Digital BusinessesWSO2CON 2024 - Software Engineering for Digital Businesses
WSO2CON 2024 - Software Engineering for Digital Businesses
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
WSO2Con2024 - Low-Code Integration Tooling
WSO2Con2024 - Low-Code Integration ToolingWSO2Con2024 - Low-Code Integration Tooling
WSO2Con2024 - Low-Code Integration Tooling
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 

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