CodeLab:Android fundamentals 07.2:AsyncTask and AsyncTaskLoader

这个教程介绍了如何在Android中使用AsyncTask和AsyncTaskLoader从Google Books API获取背景数据。首先,通过Google APIs Explorer了解API并发送请求。然后,创建一个名为'Who Wrote It?'的App,它使用AsyncTask获取图书作者和标题,并在UI上显示。接着,将App转换为使用更高效的AsyncTaskLoader。这个教程涵盖了网络请求、JSON解析、UI更新和配置变化时的数据持久化。
摘要由CSDN通过智能技术生成

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:

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 an AsyncTask.


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.

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Oiu8N5oB-1618215777682)(7.2 AsyncTask and AsyncTaskLoader.assets/image-20210412161859208.png)]



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

  1. Go to the Google APIs Explorer at https://developers.google.com/apis-explorer/.
  2. Click Services in the left nav, and then Books API.
  3. 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.

  1. In the q field, enter a book name or a partial book name, for example “Romeo”. The q parameter is the only required field.
  2. In the maxResults field, enter 10 to limit the results to the top 10 matching books.
  3. In the printType field, enter books to limit the results to books that are in print.
  4. Make sure that the Authorize requests using OAuth 2.0 switch at the top of the form is off.
  5. Click Execute without OAuth link at the bottom of the form.
  6. 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.

  1. Find the value for the "title" name for one book. Notice that this result contains a single value.
  2. 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)

  1. Create a new project called “WhoWroteIt”, using the Empty Activity template. Accept the defaults for all the other options.
  2. Open the activity_main.xml layout file. Click the Text tab.
  3. Add the layout_margin attribute to the top-level ConstraintLayout:
android:layout_margin="16dp"
  1. Delete the existing TextView.
  2. 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"
  1. 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>
  1. The onClick attribute for the button will be highlighted in yellow, because the searchBooks() method is not yet implemented in MainActivity. To create the method stub in MainActivity, place your cursor in the highlighted text, press Alt+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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值