Android fundamentals 07.2:AsyncTask and AsyncTaskLoader
Tutorial source : Google CodeLab
Date : 2021/04/06
Complete course : 教程目录 (java).
Note : The link in this article requires Google access
1、Welcome
This practical codelab is part of Unit 3: Working in the background in the Android Developer Fundamentals (Version 2) course. You will get the most value out of this course if you work through the codelabs in sequence:
- For the complete list of codelabs in the course, see Codelabs for Android Developer Fundamentals (V2).
- For details about the course, including links to all the concept chapters, apps, and slides, see Android Developer Fundamentals (Version 2).
Note: This course uses the terms “codelab” and “practical” interchangeably.
Introduction
In this practical you use an AsyncTask
to start a background task that gets data from the internet using a simple REST API. You use the Google APIs Explorer to query the Books API, implement this query in a worker thread using an AsyncTask
, and display the result in your UI.
Then you reimplement the same background task using AsyncTaskLoader
, which is a more efficient way to update your UI.
What you should already know
You should be able to:
- Create an activity.
- Add a
TextView
to the layout for the activity. - Implement
onClick
functionality for a button in your layout. - Implement an
AsyncTask
and displaying the result in your UI. - Pass information between activities as extras.
What you’ll learn
- How to use the Google APIs Explorer to investigate Google APIs and to view JSON responses to HTTP requests.
- How to use the Google Books API to retrieve data over the internet and keep the UI fast and responsive. You won’t learn the Books API in detail—your app will only use the simple book-search function.
- How to parse the JSON results from your API query.
- How to implement an
AsyncTaskLoader
that preserves data on configuration changes. - How to update your UI using the loader callbacks.
What you’ll do
- Use the Google APIs Explorer to learn about the Books API.
- Create the “Who Wrote It?” app, which queries the Books API using a worker thread and displays the result in the UI.
- Modify the “Who Wrote it?” app to use an
AsyncTaskLoader
instead of anAsyncTask
.
2、App overview
You will build an app that contains an EditText
and a Button
.
- The user enters the name of the book in the
EditText
and taps the button. - The button executes an
AsyncTask
that queries the Google Books API to find the author and title of the book the user is looking for. - The results are retrieved and displayed in a
TextView
below the button.
Once the app is working, you modify the app to use AsyncTaskLoader
instead of the AsyncTask
class.
3、Task 1. Explore the Google Books API
In this practical you use the Google Books API to search for information about a book, such as the book’s author and title. The Books API provides programmatic access to the Google Book Search service using REST APIs. This is the same service used behind the scenes when you manually execute a search on Google Books. You can use the Google APIs Explorer and Google Book Search in your browser to verify that your Android app is getting the expected results.
1.1 Send a Books API Request
- Go to the Google APIs Explorer at https://developers.google.com/apis-explorer/.
- Click Services in the left nav, and then Books API.
- Find books.volumes.list and click that function name. To find within a page, you can press
Control+F
(Command+F
on Mac).
You should see a webpage that lists the parameters of the Books API function that performs book searches.
- In the
q
field, enter a book name or a partial book name, for example “Romeo”. Theq
parameter is the only required field. - In the
maxResults
field, enter10
to limit the results to the top 10 matching books. - In the
printType
field, enterbooks
to limit the results to books that are in print. - Make sure that the Authorize requests using OAuth 2.0 switch at the top of the form is off.
- Click Execute without OAuth link at the bottom of the form.
- Scroll down to see the HTTP request and HTTP response.
The HTPP request is a uniform resource identifier (URI). A URI is a string that identifies a resource, and a URL is a certain type of URI that identifies a web resource. For the Books API, the request is a URL. The search parameters that you entered into the form follow the ?
in the URL.
Notice the API key
field at the end of the URL. For security reasons, when you access a public API, you must obtain an API key and include it in your request. The Books API doesn’t require an API key, so you can leave out that portion of the request URI in your app.
1.2 Analyze the Books API response
The response to the query is towards the bottom of the page. The response uses the JSON format, which is a common format for API query responses. In the APIs Explorer web page, the JSON code is nicely formatted so that it is human readable. In your app, the JSON response will be returned from the API service as a single string, and you will need to parse that string to extract the information you need.
The response is made up of name/value pairs that are separated by commas. For example, "kind": "books#volumes"
is a name/value pair, where "kind"
is the name and "books#volumes"
is the value. This is the JSON format.
- Find the value for the
"title"
name for one book. Notice that this result contains a single value. - Find the value for the
"authors"
name for one book. Notice that this result is an array that can contain more than one value.
The book search includes all the books that contain the search string, with multiple objects to represent each book. In this practical, you only return the title and authors of the first item in the response.
4、Task 2. Create the “Who Wrote It?” app
Now that you’re familiar with the Books API, it’s time to set up the layout of your app.
2.1 Create the project and user interface (UI)
- Create a new project called “WhoWroteIt”, using the Empty Activity template. Accept the defaults for all the other options.
- Open the
activity_main.xml
layout file. Click the Text tab. - Add the
layout_margin
attribute to the top-levelConstraintLayout
:
android:layout_margin="16dp"
- Delete the existing
TextView
. - Add the following UI elements and attributes to the layout file. Note that the string resources will appear in red; you define those in the next step.
View | Attributes | Values |
---|---|---|
TextView |
android:layout_widthandroid:layout_heightandroid:idandroid:textandroid:textAppearanceapp:layout_constraintStart_toStartOfapp:layout_constraintTop_toTopOf |
"match_parent""wrap_content""@+id/instructions""@string/instructions""@style/TextAppearance. AppCompat.Title""parent""parent" |
EditText |
android:layout_widthandroid:layout_heightandroid:idandroid:layout_marginTopandroid:inputTypeandroid:hintapp:layout_constraintEnd_toEndOfapp:layout_constraintStart_toStartOfapp:layout_constraintTop_toBottomOf |
"match_parent""wrap_content""@+id/bookInput""8dp""text""@string/input_hint""parent""parent""@+id/instructions" |
Button |
android:layout_widthandroid:layout_heightandroid:idandroid:layout_marginTopandroid:textandroid:onClickapp:layout_constraintStart_toStartOfapp:layout_constraintTop_toBottomOf |
"wrap_content""wrap_content""@+id/searchButton""8dp""@string/button_text""searchBooks""parent""@+id/bookInput" |
TextView |
android:layout_widthandroid:layout_heightandroid:idandroid:layout_marginTopandroid:textAppearanceapp:layout_constraintStart_toStartOfapp:layout_constraintTop_toBottomOf |
"wrap_content""wrap_content""@+id/titleText""16dp""@style/TextAppearance.AppCompat.Headline""parent""@+id/searchButton" |
TextView |
android:layout_widthandroid:layout_heightandroid:idandroid:layout_marginTopandroid:textAppearanceapp:layout_constraintStart_toStartOfapp:layout_constraintTop_toBottomOf |
"wrap_content""wrap_content""@+id/authorText""8dp""@style/TextAppearance. AppCompat.Headline""parent""@+id/titleText" |
- In the
strings.xml
file, add these string resources:
<string name="instructions">Enter a book name to find out who wrote the book. </string>
<string name="button_text">Search Books</string>
<string name="input_hint">Book Title</string>
- The
onClick
attribute for the button will be highlighted in yellow, because thesearchBooks()
method is not yet implemented inMainActivity
. To create the method stub inMainActivity
, place your cursor in the highlighted text, pressAlt+Enter
(Option+Enter
on a Mac) and choose Create ‘searchBooks(View) in ‘MainActivity’.
Solution code for activity_main.xml
:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
tools:context=".MainActivity">
<TextView
android:id="@+id/instructions"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/instructions"
android:textAppearance="@style/TextAppearance.AppCompat.Title"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<EditText
android:id="@+id/bookInput"
android:layout_width="match_parent"
andr