Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
CPRE 388: JSON 
 
 
 
JSON 
 
Lab Objectives: 
● Import an existing Android project into Android Studio 
● Learn how to use AsyncTask 
● Learn how to use a ListActivity 
● Send and receive a JSON request from Itunes 
● Complete a simple Itunes application 
 
What to Turn in: 
● The lab evaluation form checked off and signed by your TA 
● Submit online lab feedback survey 
 
Overview: 
This lab is about sending and receiving requests in a separate thread using the AsyncTask class as well as 
learning and understanding how to parse a JSON, JavaScript Object Notation, result received from a web   
request. After importing the project open the MainActivity.java file and look at the AsyncTask class given called 
DownloadWebpageTask. This class has three distinct methods called doInBackground, onPostExecute, and 
onProgressUpdate. Please read the Android documentation about the AsyncTask.class and those three 
methods. Any time a user sends a web request it should be executed in a separate thread. 
 
The basic idea of this lab is to send a request to Itunes to retrieve 20 songs for an artist and receive a result. 
The basic code for sending a request has been given, and it will be your goal to implement the URL to retrieve 
the records and then parse and display the result in a separate thread. When opening the starting code there is 
one XML file named activity_main.xml. This file contains a text field input and a search button. Once the 
search button is pressed the application will send a request to Itunes to retrieve records for the artist entered in 
the text field. 
 
Now that you have a basic understanding of the lab, let’s take a look at Itunes. 
 
Itunes: 
For this lab the Itunes API will be used to display songs for a particular artist. Please read the content of this 
webpage:   h t t p s : / / w w w . a p p l e . c o m / i t u n e s / a f f i l i a t e s / r e s o u r c e s / d o c u m e n t a t i o n / i t u n e s -
s t o r e - w e b - s e r v i c e - s e a r c h - a p i . h t m l  
 
This webpage gives an overview of how the Itunes API can be used to retrieve information for a particular artist. 
Here is an example of how to execute a request to get 20 songs from the artist Jack Johnson: 
 
 
 
Please ask the TA to clarify any questions about how this service works. 
Execute a request in the search on click listener in the MainActivity.java file. 
request.execute("https://itunes.apple.com/search?term=jack+johnson&entity=song&limit=20"
); 
CPRE 388: JSON 
 
Callback Interfaces: 
The DownloadWebpageTask.java file in this lab contains an internal interface, ResultHandler.  This interface 
describes any class that is able to handle the result from the web search.  The DownloadWebpageTask takes in 
an object who implements the interface in its constructor, and its handResult method is called in the 
onPostExecute of the task.  This kind of design pattern is considered desirable in code because it reduces 
coupling in code and eliminates the need for a separate thread to make UI changes, which is considered bad 
practice.  MainActivity implements this interface.  You can pass in the MainActivity when starting a 
DownloadWebpageTask, and then handle any changes you want to make in its overridden method. 
JSON: 
Because this lab will be using a JSON object returned by an Itunes request here is a simple JSON String and 
an example of how to parse it using Java. JSON data utilizes a key:value pair and in the example below, the first 
line has “wrapperType” as the key and “track” as the value (this text is cut off, but you can see the idea). 
 
 
 
In order to parse this using Java we will need to use the JSONObject.class. Assume that “s” in the below 
example represents the JSON string above. Here is an example of how to parse the JSON string: 
 
 
Now try to parse the Itunes result in the MainActivity.java file in the method handleResult and get the album 
name and song title for the 20 entries returned from the query. Refer back to the Itunes API for the fields in 
the JSON result that represent the needed fields. The JSON string that needs to be parsed is contained in 
the input to the method handleResult(String result). The results that are returned from the Itunes API 
represent a JSON array. The above example was for parsing a single JSON object. To parse the array, first 
convert the object to a JSON array then iterate through and get each individual JSON object. Notice that each 
time a Tweet is parsed it is added to the data ArrayList and the list is of type ItunesRecord. More to come on 
this later. 
 
 
 
 
 
 
 
{"wrapperType":"track", 
 "kind":"song", 
 "artistId":909253, 
 "collectionId":879273552, 
 "trackId":879273565, 
 "artistName":"Jack Johnson", (continues) 
 "collectionName":"In Between Dreams", "trackName":"Better Together", 
"collectionCensoredName":"In Between Dreams", "trackCensoredName":"Better Together", 
"artistViewUrl":"https://itunes.apple.com/us/artist/jack-johnson/id909253?uo=4", 
"coll ctionViewUrl":"https://itunes.appl .com/us/album/better-
together/id879273552?i=879273565&uo=4", 
"trackViewUrl":"https://itunes.apple.com/us/album/better-
together/id879273552?i=879273565&uo=4", 
"previewUrl":"http://a898.phobos.apple.com/us/r1000/039/Music6/v4/13/22/67/1322678b-e40d-
fb4d-8d9b-3268fe03b000/mzaf_8818596367816221008.plus.aac.p.m4a",  
"artworkUrl30":"http://is2.mzstatic.com/image/thumb/Music4/v4/41/df/6f/41df6fb5-d08f-5573-
fb4b-a56a9b6ea0cb/UMG_cvrart_00602537868858_01_RGB72_900x810_06UMGIM25847.jpg/30x30bb-
85.jpg",  
"artworkUrl60":"http://is4.mzstatic.com/image/thumb/Music4/v4/41/df/6f/41df6fb5-d08f-5573-
fb4b-a56a9b6ea0cb/UMG_cvrart_00602537868858_01_RGB72_900x810_06UMGIM25847.jpg/60x60bb-
85.jpg",  
"artworkUrl100":"http://is4.mzstatic.com/image/thumb/Music4/v4/41/df/6f/41df6fb5-d08f-5573-
fb4b-a56a9b6ea0cb/UMG_cvrart_00602537868858_01_RGB72_900x810_06UMGIM25847.jpg/100x100bb-
85.jpg", "collectionPrice":9.99, "trackPrice":1.29, "releaseDate":"2014-05-27T07:00:00Z", 
"collectionExplicitness":"notExplicit", "trackExplicitness":"notExplicit", "discCount":1, 
"discNumber":1, "trackCount":15, "trackNumber":1, "trackTimeMillis":207679, "country":"USA", 
"currency":"USD", "primaryGenreName":"Rock", 
"radioStationUrl":"https://itunes.apple.com/station/idra.879273565", "isStreamable":true} 
//The JSON object JSONObject 
result = null; 
 
// Convert string to object try { 
esult = new JSONObject(s); 
} catch (JSONException e) { 
e.printStackTrace(); 
} 
 
try { 
String title = result.getString("collectionName"); 
String album = result.getString("trackName"); 
} catch (JSONException ex) { 
Log.e("Exception:", "Request not completed"); 
} 
CPRE 388: JSON 
 
ListActivity Class: 
Please read the Android documentation about the ListActivity class located at the following link: 
http://developer.android.com/reference/android/app/ListActivity.html 
 
This lab uses a ListActivity and it will be your job to implement the final steps to display the Itunes records. By 
now a list of Itunes records will be added to the data ArrayList in the handleResult method. Check LogCat  and 
verify that when you send a request you get a response back. In order to use this information with our list 
activity, a list adapter must be made. There is a class given called ItunesAdapter.java which will serve as the 
adapter for this lab. 
 
A ListView is a collection of rows and each row will have a layout associated with it. In order to add the Tweets 
to a row in the list, an XML file must be made that will serve as the layout for each row added to the ListView. This 
layout file will be a completely new XML layout file and each row in the list view will reflect the layout of this file. 
Create a new row layout XML file. Refer to the Android documentation which describes how these rows are used 
within the activity. Try to make your row layout resemble something like: 
 
 
 
Try using a Relativelayout with several text fields within. Android Studio has a nice graphical editor for XML 
layouts and allows a drag and drop interface. Take a few minutes to experiment with creating a new layout. Make 
sure that when you add a new XML file it is contained within res>layout. This is the location where most, if not all, 
of your layout files will be. 
 
Here is a link to the Android developer page regarding layout files: 
http://developer.android.com/guide/topics/ui/declaring-layout.html 
 
Once you have completed your row layout please verify with a TA that it is correct. 
 
Now that a row layout has been made, the list adapter must be set in order to tell the ListView about the data that 
it should display. An Adapter is something that serves as a link between information and the display. 
 
Here is a link to the Android developer page regarding adapters and views: 
http://developer.android.com/guide/topics/ui/declaring-layout.html#AdapterViews 
 
This lab uses an ArrayAdapter in order to display the information. Use the method setListAdapter with a new 
ItunesAdapter object, which extends ArrayAdapter, in order to do this. The ItunesAdapter object takes in two 
arguments. The first argument refers to the activity that holds the ListView. This argument is known as the 
context. Since the context in the AsyncTask class does not refer to the MainActivity using the this keyword will 
not work. Try to figure out how to use the MainActivity class as the context. The second refers to the row layout 
that was just created. Use R.layout instead of R.id in order to get a layout file. The last part of linking the list 
adapter with the view is to add the specific fields to the adapter class that represent the elements in the row 
layout. The ItunesAdapter class contains a static class called ItunesHolder. The purpose of this class is to have 
an object that will reference the fields in the row layout that was created earlier. For example, if the holder object 
had a field called “date” and the row layout had a field with id “date”, then holder.date would refer to the R.id.date 
in the row. Please set the holder view IDs in the ItunesAdapter file.  View holder classes are not strictly 
necessary, but will reduce unnecessary findViewById calls. 
 
Now that the row is linked to its specific fields, the holder object can be used to set the text for each field. Use the 
holder object to set the album name and song title field for each row. After this is done the application should be 
able to fetch 20 songs for the artist entered in the search field. 
Song: Better Together 
Album: In Between Dreams 
CPRE 388: JSON 
 
 
Testing the App: 
Test your application and fix any major problems with the ListView. Demo your application to your TA and have 
them fill out the lab evaluation form. Once you have completed your lab, fill out the feedback form on an   
individual basis evaluating this lab and write-up. 
 
 
 
 
  
 
Lab Evaluation Form - JSON 
 
Student’s Name(s):   
CPRE 388: JSON 
 
Lab Section/Time:   
 
 
Evaluation: 
 
  Implement the Itunes fetch request ( 5 points  ) 
 
  Parse the JSON response from the Itunes request ( 10 points   ) 
 
  Create a new row layout for the list view and display all of the Itunes records ( 35 points ) 
 
 
Turn in: 
● Evaluation form signed by TA 
● Lab feedback form 
 
 
 
 
 
 
TA Signature Date:   
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4