Android Application WebAPI Development Training

50 %
50 %
Information about Android Application WebAPI Development Training
Technology

Published on March 7, 2014

Author: OESF_Education

Source: slideshare.net

Description

OESF Authorized Training Course official textbook
Course: Android Application WebAPI Development Training
Language: English
Contributed by
Created by: Leading Edge Co.,Ltd.
Translated by: ISB Vietnam Co.,Ltd.

[Attention!]
This textbook is licensed under the Creative Commons License BY-NC-SA 4.0. It is prohibited to use this material for commercial use otherwise you are OESF member or OESF education consortium member.

Android application development WebAPI course

Training Objectives • Android WebAPI is required for application development Acquire knowledge: • How to access WebAPI - Asynchronous Graphical - Reason to consider garbage collection • To analyze - XML - use the service • Exercises, ask why you need to experience these issues. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 2

Training Schedule • Day 1 - Chapter 1 Introduction - Chapter 2 WebAPI development knowledge - Chapter 3 Preparing the Development Environment - Chapter 4 Tutorial • Day 2 - Chapter 5 use ListView - Chapter 6 Exercises - Chapter 7 Conclusion This material is licensed under the Creative Commons License BY-NC-SA 4.0. 3

Getting the necessary skills Niatari attend a seminar, and found that minimum skills are required. • Experience in Java language • The exercises are actually programming in Java. • The basic problem is understand Java language specification. • Experience in using Eclipse - A drill in Eclipse where it is used to implement the program. - Basic understanding of Eclipse (the problem of how to use Eclipse). • OESF official Android is already skilled or equivalent introductory course application development. • Android applications have basic skills • Can easily create a multiple-screen applications This material is licensed under the Creative Commons License BY-NC-SA 4.0. 4

1. Introduction

Chapter 1 Introduction Chapter summary • • • Exercise the Development environment. Practice Applications used. About Exercise This material is licensed under the Creative Commons License BY-NC-SA 4.0. 6

1.1. Development Development Description • the following development tools is for this training. • Training tools in development machine has already been built • Tools are included with the SDK path through the environment variable Software Version Integrated development environment Eclipse 3.5 (Galileo) Java SDK JDK 6 Update 21 Android SDK 2.1 Android Plug-in Android Development Tools (ADT) Ver.0.9.9 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 7

1.2. About Exercise Overview • Eclipse Workspace: specified by C:android_trainingdevtoolseclipseworkspace • Emulator: emulator used in practice, unless otherwise specified in particular, is WVGA-normalhdpi • SDK path: has become C:android_trainingtoolsandroid-sdk-windows This material is licensed under the Creative Commons License BY-NC-SA 4.0. 8

1.3. The application for exercise • • • • • • Exercise, create a video download application. Features Video Downloader HTTP communication with WebAPI Treatment works in the background ListView applied technology Parsing XML This material is licensed under the Creative Commons License BY-NC-SA 4.0. 9

1.4. Application for exercise (2) • Video Downloader Screen and Features Overview Function Name Thumbnail Thumbnail Features Overview • To view the video's thumbnail graphic Title • To view the attached video title Description • To view the video description Title Description This material is licensed under the Creative Commons License BY-NC-SA 4.0. 10

1.5. About Exercise Explicit Intent with screen transitions Connect to WebAPI Get the results from the WebAPI server Internet SD Card SD Card to store videos Enter your search terms, press "Search" button Click to download the video line Parse the XML Processing Customize List Click to play the line Use Download Service This material is licensed under the Creative Commons License BY-NC-SA 4.0. 11

2. WebAPI development knowledge

Chapter 2 - Overview – What is WebAPI? – The need for asynchronous display – Reason to consider a garbage collection – DOM, SAX, XMLPullParser – Use of services This material is licensed under the Creative Commons License BY-NC-SA 4.0. 13

2.1. What is WebAPI? • Web Application Programming Interface of the application program on the Web. • Basically, to use the SOAP or REST, XML is used to exchange data. • As a typical thing, Yahoo API, Google API, Youtube API … etc Get / Post send Sent in XML This material is licensed under the Creative Commons License BY-NC-SA 4.0. 14

2.2. The need for asynchronous display • • If it takes longer to process what on-screen, then the screen is not enough to display, As a result, users would feel the stress. • • So the process can be divided to view the text and images separately. Text-only displayed first, later, image displayed. • Can relieve some stress for the user. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 15

2.3. reason to consider GC • Without considering the garbage collection (GC), less memory available for Android. • To make the program stops as soon as the Full GC occurs. • Full GC occurs and, in order to maintain consistency, all threads will be stopped. • After user program (user), GC treatment starts, because nothing will be waiting. Java VM This material Full GC occurs Principle of is licensed under the Creative Commons License BY-NC-SA 4.0. 16

2.4. DOM, SAX, and XMLPullParser (1) DOM (tree type) • DOM as a tree with the heap, when parsing XML to hold the entire contents of memory, after parsing any element that can be accessed at any time. • To keep everything in memory, it consumes more memory, • Mobile devices that run Android have a problem. • A small XML DOM document can be used to be implemented easily. Okay Oso DOM Large memory consumption This material is licensed under the Creative Commons License BY-NC-SA 4.0. 17

2.4. DOM, SAX, and XMLPullParser (2) SAX (event-driven) • Parser to parse Application that calls the image. • Iki XML document read from the beginning, And hit the start and end tags, etc…, to call the determined application callback routine. • Control DOM By the application can not load the XML document. • • Memory consumption is less than the DOM. Er is Android is the conventional method of using the SAX, onsoooo ♪ SAX there are ways to use a wrapper. My more !!!!! ・ ・ ・ easy to use mon SAX DOM This material is licensed under the Creative Commons License BY-NC-SA 4.0. 18

2.4. DOM, SAX, and XMLPullParser (3) XMLPullParser( Pull Type ) • StAX JAVA by what shall have the same functionality. Android will have the same function that StAX does not support. • XMLPullParser are provided. • StAX as an XML document read from the head of the load • Performed by the application control information from the parser as needed • Can be obtained. • To make an application from the control, early in the parsing It can be stopped, it takes a lot of time parsing • Can be reduced. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 19

2.4. DOM, SAX, and XMLPullParser (4) Summary DOM SAX XML PullParser Parser Nature Tree structure Event-driven (no control) Event-driven (controllable) Access to the elements Random Sequential Sequential Get element The DOM tree Access Callback Routine When iterated Get Exporting XML Possible Impossible Possible Memory consumption More The least Low Ease of handling Easy Difficult Easy This material is licensed under the Creative Commons License BY-NC-SA 4.0. 20

2.5. far from being used for service • In the resident program, services are put in word. • As a recipe, Web services are very similar. (WSDL, AIDL) • The biggest difference between threads and services that they are running even after exiting the Activity. • The service can be remain started. • In addition, Activity can also access the service restarts. • Is used primarily in music players, GPS log information and timers. Commonly use time-consuming process. Thread This material is licensed under the Creative Commons License BY-NC-SA 4.0. Service 21

3. Preparing the Development Environment

3.1. Setting up Development Environment • Install the following development tools. Software Version Integrated development environment Eclipse 3.5 Galileo Java SDK Java SDK 1.6.x Android SDK 2.1 Android Plug-In Android Development Tools (ADT) This material is licensed under the Creative Commons License BY-NC-SA 4.0. 23

3.1. Setting up Development Environment (1) •Install Android SDK 1. Launch Windows Explorer from the Start menu, Open C: android_training devtools . 2. Right-click the android-sdk_r **- windows.zip file, Expand All selected. 3. Deployment wizard steps along the C: android_training android_sdk deployed to ensure that organized as the right figure. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 24

3.1. Setting up Development Environment (2) •Set Environment Variables 1. Select Control Panel from Start menu ,Double click[System]. 2. Click the Advanced tab in The System Properties, Click Environment Variables button. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 25

3.1. Setting up Development Environment (3) 3. At Environment Variables window, click [Path], from Environment Variables System and then Edit button. 4. Add c: android_trainingtoolsandroid_sdktools. at the beginning of the Edit System Variable window Variable value This material is licensed under the Creative Commons License BY-NC-SA 4.0. 26

3.1. Setting up Development Environment (4) •5. In Edit System Variable window, click [OK] button. •6. In Environment Variables window, click [OK] button. •7. To ensure that the environment changes is reflected. 7-1. Start Menu->All Programs -> Accessories ->command Prompt, and then start a command prompt. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 27

3.1. Setting up Development Environment (5) •7-2. Run the following command from the command prompt: set [<sp>] | <sp> find <sp> "android“ •To ensure that you receive the Path settings. •※ <sp> · · · meaning of space This material is licensed under the Creative Commons License BY-NC-SA 4.0. 28

3.1. Setting up Development Environment (6) • Android Development Tools (ADT) Installation 1. Start Eclipse. 2. Click Help in Eclipse menu, select Install New Software. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 29

3.1. Setting up Development Environment (7) •3. In the Install window, click Add, •4. Adding a site to the location of the window –http://dl-ssl.google.com/android/eclipse/ –Enter [OK] button. ※ The name of any location. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 30

3.1. Setting up Development Environment (8) 5. In Installation Details window, check Developer Tools, Press [Install] button. 6. Then click Next button in the install window. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 31

3.1. Setting up Development Environment (9) 7. In Install window, check [I accept the terms of use], click [Finish] button to start the installation. •If the warning dialog for unsigned software installation appears, continue clicking [OK]. 8. Installation is complete, click [Yes] when you see the Software Updates message, restart Eclipse Progress is being installed Software Installation warning dialog This material is licensed under the Creative 32 unsigned Commons License BY-NC-SA 4.0.

3.1. Setting up Development Environment (10) •9. After restarting Eclipse, In the Development Tools toolbar make sure that the Android button has been added. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 33

3.1. Setting up Development Environment (11) • Installing the Android Platform 1. Eclipse menu: from [Window] select [Android SDK and AVD Manager]. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 34

3.1. Setting up Development Environment (12) 2. from a tree on the left select [Available Packages], Tick [SDK Platform Android 2.1, API 7 revision 2], click [Install Selected]. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 35

3.1. Setting up Development Environment (13) 3. Tick [Accept All], and then click Install. If you see a dialog box that mean " Do you want to Update?" click "yes" 4. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 36

3.1. Setting up Development Environment (14) 5. When you see the screen shown at right, Click "close" to Close Window 6. Check below C:android_trainingandroid_sdkplatforms, "android-7" to make sure that the folders are made This material is licensed under the Creative Commons License BY-NC-SA 4.0. 37

3.1. Setting up Development Environment (15) 7. Restart eclipse. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 38

3.1. Setting up Development Environment (16) • Set the Eclipse-ADT to recognize the Android SDK. 1. From Eclipse [Window] menu, select [Preferences]. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 39

3.1. Setting up Development Environment (17) •2. In Preferences window select [Android]. •An error message appears, close the message window: –Set error message at the top of the window –Make sure to disappear, click [OK] button. • Select SDK location C:devlopandroidsdk-windows and press enter, then click [OK]. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 40

3.1. Setting up Development Environment (18) How to Display Task From the "Window" menu , select "Tasks" on "ShowView" In "Tasks" select the Eclipse task list that appears at the end This material is licensed under the Creative Commons License BY-NC-SA 4.0. 41

3.1. Setting up Development Environment (19) • Get more training for the skeleton project - Each exercise includes a project to create a skeleton file • Please proceed to import the project to study the skeleton project. From "File" select "Import“, import dialog is displayed From "General" select "Existing Projects into Workspace" press"Next" This material is licensed under the Creative Commons License BY-NC-SA 4.0. Select a file for each skeleton practice. Please press "Finish" 42

4. Tutorials

4.1. Creating a Simple Application • Create a simple screen transitions application. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 44

4.1. Creating a Simple Application (1) •Application Summary <Project Settings> Items Setting Project name ActivitySample Build Target 2.1 Application name ActivitySample Package name jp.oesf.activitysample Create Activity MainActivity <Additional setting Activity> Items Setting Class Activity SubActivity This material is licensed under the Creative Commons License BY-NC-SA 4.0. 45

4.1. Creating a Simple Application (2) •Application Summary <main.xml> View Id (@+id / id名) layout_width Text On click TextView text_title wrap_content @string/main_activity Not Set EditText edit_message fill_parent Not Set Not Set Button button_sub fill_parent @string/go_to_subActivity onClickSubButton Button Button_end fill_parent @string/main_end onClickEndButton <sub.xml> View Id (@+id / id名) layout_width Text On click TextView text_title wrap_content @string/sub_activity Not Set TextView text_message wrap_content Not Set Not Set Button button_main fill_parent @string/go_to_mainActi vity onClickMainButton This material is licensed under the Creative Commons License BY-NC-SA 4.0. 46

4.1. Creating a Simple Application (3) •Classes: to create class MainActivity and SubActivity. The Main Screen Passing Data to Sub-screen Intent to execute a move to create a sub-screen class. Intent intent = new Intent(this, SubActivity.class); EditText editText = (EditText)findViewById(R.id.edit_message); Intent#putExtra using data stored in Intent String message = editText.getText().toString(); intent.putExtra("TEXT", message); startActivity(intent); The Sub-screen Data obtained from the main screen. Intent to create and run a class move to the main screen. Intent intent = getIntent(); String message = intent.getStringExtra("TEXT"); TextView textView = (TextView)findViewById(R.id.text_message); textView.setText(message); Back to the main screen. finish(); This material is licensed under the Creative Commons License BY-NC-SA 4.0. 47

4.1. Creating a Simple Application (4) •Answer <MainActivity.java> public class MainActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void onClickSubButton(View v){ Intent intent = new Intent(this, SubActivity.class); EditText editText = (EditText)findViewById(R.id.edit_message); String message = editText.getText().toString(); intent.putExtra("TEXT", message); startActivity(intent); } public void onClickEndButton(View v){ finish(); } } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 48

4.1. Creating a Simple Application (5) Answer <SubActivity.java> public class SubActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sub); Intent intent = getIntent(); String message = intent.getStringExtra("TEXT"); TextView textView = (TextView)findViewById(R.id.text_message); textView.setText(message); } public void onClickSubButton(View v){ finish(); } } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 49

4.1. Creating a Simple Application (6) Answer < main.xml > <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/text_title" android:text="@string/main_activity"> </TextView> <EditText android:layout_height="wrap_content" android:id="@+id/edit_message" android:layout_width="fill_parent"> </EditText> <Button android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="@string/go_to_subActivity" android:id="@+id/button_sub" android:onClick="onClickSubButton"> </Button> <Button android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="@string/end" android:id="@+id/button_end" android:onClick="onClickEndButton"> </Button> </LinearLayout> This material is licensed under the Creative Commons License BY-NC-SA 4.0. 50

4.1. Creating a Simple Application (7) Answer < sub.xml > <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/text_title" android:text="@string/sub_activity"> </TextView> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/text_message"> </TextView> <Button android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="@string/go_to_mainActivity" android:id="@+id/button_main" android:onClick="onClickSubButton"> </Button> </LinearLayout> This material is licensed under the Creative Commons License BY-NC-SA 4.0. 51

4.1. Creating a Simple Application (8) Answer < strings.xml > <?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello World, MainActivity!</string> <string name="app_name">ActivitySample</string> <string name="main_activity">MainActivity</string> <string name="go_to_subActivity">Go to SubActivity</string> <string name="main_end">End</string> <string name="sub_activity">SubActivity</string> <string name="go_to_mainActivity">Go to MainActivity</string> <string name="sub_end">End</string> </resources> This material is licensed under the Creative Commons License BY-NC-SA 4.0. 52

4.1. Creating a Simple Application (9) Answer < AndroidManifest.xml > <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="jp.oesf.activitysample" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".MainActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".SubActivity" android:label="@string/app_name"> </activity> </application> <uses-sdk android:minSdkVersion="7" /> </manifest> This material is licensed under the Creative Commons License BY-NC-SA 4.0. 53

5. Using ListView

5 Chapter Summary • • • Using ListView Sample application using ListView Create a customized list view This material is licensed under the Creative Commons License BY-NC-SA 4.0. 55

5 Chapter Summary • <Listview Overview > • ListView view group is to display data in a list format. • ListView is also possible to change the layout of the item. Displayed in list format You can also change the layout This material is licensed under the Creative Commons License BY-NC-SA 4.0. 56

5 Chapter Summary <Adapterno Overview > View data with a role Adapter stitching. View Adapter will be displayed from the job of assembling the data. View the data and the role of tie Adapter Data Assemble View Show This material is licensed under the Creative Commons License BY-NC-SA 4.0. 57

5 Chapter Summary View assembly mechanism Adapter is responsible for coordination of data and views, and the role of assembling views data to be displayed. Array and List (ArrayList, etc.) are the elements of View to determine whether to display the structure getView method or not. getView method getView method will be called when new data appears. ListView, then scroll to the screen, when new data appears from off screen. Nature, because it is called many times at the scroll, getView method have inappropriate logic, and cause discomfort to scroll the screen, a negative impact on performance. Return value Method Name View getView (int position, View contentView, ViewGroup parent) This material is licensed under the Creative Commons License BY-NC-SA 4.0. 58

5.2. Creating a Sample Application • <Overview of the sample projects> Items Setting Project name ListSample Build Target 2.1 Application name ListSample Package name jp.oesf.listsample Create Activity ListSample Min SDK Version 7 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 59

5.2. Creating a Sample Application • 1. Define the layout 1-1in eclipse, Create res/layout/list.xml in res/layout. – right-click [More] –New, in the [Android] select [Android XML File] and click [Next] This material is licensed under the Creative Commons License BY-NC-SA 4.0. 60

5.2. Creating a Sample Application – enter the file name list.xml and click Finish. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 61

5.2. Creating a Sample Application • 1-3 ListView Paste List.xml is created, select Layout tab, Select ListView from Layouts, Drag & Drop it This material is licensed under the Creative Commons License BY-NC-SA 4.0. 62

5.2. Creating a Sample Application • (2) The Outline is added to ListView01 • (3) Change the properties of the id field. If you are using ListActivity, make sure you have this id [@ android:id/list] This material is licensed under the Creative Commons License BY-NC-SA 4.0. 63

5.2. Creating a Sample Application • • • • Create layout row by create List_row.xml. Select the XML file folder layout, Right-click "New"→"Other"→ select " Android XML File " To add TextView to the layout Select, Create TextView This material is licensed under the Creative Commons License BY-NC-SA 4.0. 64

5.2. Creating a Sample Application 1-4 creating row layout by List_row.xml • In the Properties window, change the Id of the TextView to “text_title” • Change [Layout width] to the “fill_parent” • in [Text appearance] Property Type: “? android: attr / textAppearanceLarge” Property changes Changed value id @+id/title_text Layout width @+id/fill_parent Text appearance ?android:attr/textAppearanceLarge This material is licensed under the Creative Commons License BY-NC-SA 4.0. 65

5.2. Creating a Sample Application • 2. Use of ListActivity – – – 2-1 ListSample class that inherits from the ListActivity 2-2 setContentView arguments to change R.layout.list 2-3 Set ArrayAdapter The layout of the row by TextView Resource Id <Arrayadapternokonsutorakuta> ArrayAdapter<T>( Context context, int textViewResourceId, T[] objects) Wish list Array of items Name Type Mean The first argument(context) Context Specifies the object class. Second argument(textViewResourceId) int TextView resource ID is specified. The third argument(objects) T[] Specify the data array of objects show This material is licensed under the Creative Commons License BY-NC-SA 4.0. 66

5.2. Creating a Sample Application • < ListSample.java> public class ListSample extends ListActivity{ static public final String mItems [] = {"Shiba", "dog"Hokkaido, "Kai Dog", "Kishu dog, " "tosa”"Dog Shikoku", "Akita", "dog"Jomon, "Ryukyu dog", "dog Kawakami, " "Dog Satsuma", "Mino Shiba”"Sanin Shiba", "bush beans"}; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.list); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, mItems); setListAdapter(adapter); } } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 67

5.2. Creating a Sample Application • < list_row.xml> <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium"> </TextView> This material is licensed under the Creative Commons License BY-NC-SA 4.0. 68

5.2. Creating a Sample Application • 3. result Automatic scrolling This material is licensed under the Creative Commons License BY-NC-SA 4.0. 69

5.3. Customizing the list view •Create rich user interfaces using little ListView. •<target figure ( list of three items: titles, description and thumbnails)> Thumbnail Title Description This material is licensed under the Creative Commons License BY-NC-SA 4.0. 70

5.3. Customizing the list view •Screen structure - to be able to see the three elements, "thumbnail", "title“ and "description" in one line, 1. editing list_row.xml layout - thumbnails => ImageView - title, description => TextView to make the full use of the above sequence use the following LinearLayout : View @+Id ImageView @+Id/image_thumbnail LinearLayout @+Id/LinearLayout01 TextView @+Id/text_title TextView @+Id/text_summary This material is licensed under the Creative Commons License BY-NC-SA 4.0. 71

5.3. Customizing the list view <Linearlayout(Outside)>: No change. Remain as created by default. <LinearLayout( Inside )> Items Value id @+id/LinearLayout01 layout_height wrap_content layout width wrap_content orientation vertical <ImageView> Items Value id @+id/image_thumbnail layout_height wrap_content layout width wrap_content This material is licensed under the Creative Commons License BY-NC-SA 4.0. 72

5.3. Customizing the list view <TextView( Title )> Items Value id @+id/text_title layout_height wrap_content layout width wrap_content textAppearance ?android:attr/textAppearanceMedium < TextView( More ) > Items Value id @+id/text_summary layout_height wrap_content layout width wrap_content textAppearance ?android:attr/textAppearanceSmall This material is licensed under the Creative Commons License BY-NC-SA 4.0. 73

5.3. Customizing the list view Create a custom Adapter class <Procedure> 1 RowModel: To create a data class •Members → to hold "title, description, thumbnail“. 2 ArrayAdapter to create a class that inherits from TableAdapter •override getView () to implement the necessary processing –The null check is required for convertView –Set the value of each item to view This to setListAdapter 4 change Adapter material is licensed under the Creative Commons License BY-NC-SA 4.0. 74

5.3. Customizing the list view •Create a custom Adapter class (1) 1. Create RowModel 1. Create "Src" folder under the package [jp.oesf.listsample.model] 2. Create a RowModel class. 3. define a member variable to hold "title, description, thumbnail“ . 4. Define Getter and Setter for each variable. public class RowModel { private String title; private Drawable thumbnailImage; private String summary; "getter setter for each variable listed" } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 75

5.3. Customizing the list view Create a custom Adapter class (2) 2. ArrayAdapter to create a class that inherits from TableAdapter 1. ListSample.java the generic file to create a TableAdapter that extend TableAdapter class that specifies RowModel 2. creates an overridden GetView method 3. View Item generation and that time taken to set the check null. class TableAdapter extends ArrayAdapter<RowModel>{ public TableAdapter(Context context) { super(context, R.layout.list_row); } @Override public View getView(int position, View convertView, ViewGroup parent) { View row = convertView; RowModel item = getItem(position); if(row == null){ LayoutInflater inflater = getLayoutInflater(); } row = inflater.inflate(R.layout.list_row,under the Creative This material is licensed null); Commons License BY-NC-SA 4.0. 76

5.3. Customizing the list view Create a custom Adapter class (2) 2. Create ArrayAdapter to extend TableAdapter classes, more if( item != null){ // Image ImageView imageView = (ImageView)row.findViewById(R.id.image_thumbnail); if( imageView != null){ imageView.setImageDrawable(item.getThumbnailImage()); } //Title TextView textTitle = (TextView)row.findViewById(R.id.text_title); if(textTitle != null){ textTitle.setText(item.getTitle()); } // summary TextView textSummary = (TextView)row.findViewById(R.id.text_summary); if(textSummary != null){ textSummary.setText(item.getSummary()); } } return row; } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 77

5.3. Customizing the list view create a custom Adapter class (3) 3. Adapter with a set of values 1. set SetListAdapter methods in the TableAdapter in onCreate ListSample 2. get the text array from the resource public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.list); TableAdapter adpter = new TableAdapter(this); setListAdapter(adpter); / / RowModel Create String titles[] = getResources().getStringArray(R.array.titles); String summaries[] = getResources().getStringArray(R.array.summaries); Drawable image = getResources().getDrawable(R.drawable.icon); int num = titles.length; This material is licensed under the Creative Commons License BY-NC-SA 4.0. 78

5.3. Customizing the list view Adapter to create a custom class (3) 3. Adapter at a set of values 3. RowModel: set the acquired the sequence value 4. RowModel: set to the Adapter for(int i = 0; i < num; i++){ RowModel row = new RowModel(); row.setTitle(titles[i]); row.setSummary(summaries[i]); row.setThumbnailImage(image); adpter.add(row); } } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 79

5.3. Customizing the list view Tags on string-array xml files that describe the data, you can retrieve data from the application of a string array. Syntax <?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="string_array_name"> <item>text_string</item> <item>text_string</item> </string-array> </resources> string-array lists the defined name. ID is used as a resource. lists the data stored in the String-array. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 80

5.3. Customizing the list view •<strings.xml> <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">ListSample</string> <string-array name="titles"> <item> Shiba </ item> <item> Hokkaidou dog </ item> Kai Dog <item> </ item> <item> Kishu dog </ item> tosa <item> </ item> <item> Shikoku dog </ item> Akita <item> </ item> <item> Jomon dog </ item> <item> Ryukyu dog </ item> Kawakami <item> dog </ item> Satsuma <item> dog </ item> <item> Mino Shiba </ item> Sanin Shiba <item> </ item> <item> bush beans </ item> </string-array> This material is licensed under the Creative Commons License BY-NC-SA 4.0. 81

5.3. Customizing the list view •<String.xml(Continued)> <string-array name="summaries"> <item> Japanese mind. Small dogs only dog in Japan. </ Item> Ainu Dog <item> alias. Dogs and the sum of thinking and pure species and </ item> Kakoi <item> 虎毛! Between medium and small size </ item> Many white <item>. Feed the tail end of a book more often </ item> 闘犬 <item> Tosa. Bulldog and Mastiff dogs Great Dane was created and arranged </ item> Canis lupus hodophilax <item> can be mistaken! </ Item> <item> only large Japanese dog dog. "Matagi Akita" Matagi dog. Hachi! </ Item> <item> indigenous Japanese dog </ item> <item> to leave the old dog traits since the Jomon Period </ item> Nagano <item> protected species </ item> Takamori Saigo <item> dog </ item> Dog <item> Mino, Hida both bush </ item> Inaba base <item> dog. Feed the tail, forming the evening. Change shape as you keep SHEPHERD E?! </ Item> Shiba Inu Small <item> nickname. Preservation Society and the Japanese dog JKC in the "bush beans" pedigree that does not exist </ item></string-array> </resources> •As a resource to get the code // getting resource array data String titles[] = getResources().getStringArray(R.array.titles); String summaries[] = getResources().getStringArray(R.array.summaries); This material is licensed under the Creative Commons License BY-NC-SA 4.0. 82

5.3. Customizing the list view •<result> This material is licensed under the Creative Commons License BY-NC-SA 4.0. 83

5.3. Customizing the list view •<RowModel.java> public class private private private RowModel { String title; Drawable thumbnailImage; String summary; public final String getTitle() { return title; } public final void setTitle(String title) { this.title = title; } public final Drawable getThumbnailImage() { return thumbnailImage; } public final void setThumbnailImage(Drawable thumbnailImage) { this.thumbnailImage = thumbnailImage; } public final String getSummary() { return summary; } public final void setSummary(String summary) { this.summary = summary; } } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 84

5.3. Customizing the list view •< ListSample.java> public class ListSample extends ListActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.list); TableAdapter adapter = new TableAdapter(this); setListAdapter(adapter); // add data String titles[] = getResources().getStringArray(R.array.titles); String summaries[] = getResources().getStringArray(R.array.summaries); Drawable image = getResources().getDrawable(R.drawable.icon); adapter.clear(); int num = titles.length; for(int i=0; i<num; i++){ RowModel row = new RowModel(); row.setTitle(titles[i]); row.setSummary(summaries[i]); row.setThumbnailImage(image); adapter.add(row); } } private class TableAdapter extends ArrayAdapter<RowModel> { Activity context; TableAdapter(final Activity context) { super(context, R.layout.list_row); the Creative This material is licensed under this.context = context; Commons License BY-NC-SA 4.0. } 85

5.3. Customizing the list view < ListSample.java> @Override public View getView(int position, View convertView, ViewGroup parent) { View row = convertView; if (row == null) { // new create LayoutInflater inflater = context.getLayoutInflater(); row = inflater.inflate(R.layout.list_row, null); } // set disp RowModel item = getItem(position); if (item != null) { // Image ImageView imageView = (ImageView) row .findViewById(R.id.thumbnail_image); if (imageView != null) { imageView.setImageDrawable(item.getThumbnailImage()); } // Title TextView textTitle = (TextView) row.findViewById(R.id.title_text); if (textTitle != null) { textTitle.setText(item.getTitle()); } // summary TextView textSummary = (TextView)row.findViewById(R.id.summary_text); if(textSummary!=null){ textSummary.setText(item.getSummary()); } } return row; } } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 86

5.3. Customizing the list view •<list_row.xml> <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/image_thumbnail"></ImageView> <LinearLayout android:id="@+id/LinearLayout01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/text_title" android:textAppearance="?android:attr/textAppearanceMedium"> </TextView> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/text_summary" android:textAppearance="?android:attr/textAppearanceSmall"> </TextView> </LinearLayout> </LinearLayout> This material is licensed under the Creative Commons License BY-NC-SA 4.0. 87

6. Exercises

Chapter 6 Overview Create a Video Downloader, you will learn the following techniques: • HTTP communication with WebAPI • Parsing XML • Using Traceview • Screen with an asynchronous • Service Creation This material is licensed under the Creative Commons License BY-NC-SA 4.0. 89

6.1. display of asynchronous (preparation) • • • • Eclipse project to incorporate training for skeleton Locations Answer folder android_training_webapi skeleton_project In this case, capture "MediaDownloaderSkeleton01" • • • How to Get? Start the Eclipse "File" menu, select "Import", "Import" dialog is shown "Import" dialog, from "General” select "Existing Projects into Workspace“, press "Next" button to capture the root directory of the project skeleton check "Copy projects into workspace". • This material is licensed under the Creative Commons License BY-NC-SA 4.0. 90

6.1. display of asynchronous (1) •Exercise: To experience the state of synchronization, Try to run first. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 91

6.1. display of asynchronous (2) •When asynchronously •Downloading images is a time consuming process, to be shown later, •You can reduce the stress of the user. Now loading Icon appears Gradually icon Appear This material is licensed under the Creative Commons License BY-NC-SA 4.0. Complete 92

6.1. display of asynchronous (3) •Using AsyncTask AsyncTask subclass that inherits the class AsyncTask subclass of the run-time arguments (Params), Progress units (Progress), Processing result needs to be handled by specifying the (Result) type. Generic Description Params doInBackground Method Arguments Progress onProgressUpdate Method Arguments Result onPostExecute Method Arguments doInBackground that must match the method return values This material is licensed under the Creative Commons License BY-NC-SA 4.0. 93

6.1. display of asynchronous (4) • Define AsyncTask Specify the type corresponding to the arguments of each method class MyAsyncTask extends AsyncTask<Params, Progress, Result>{ @Override protected Result doInBackground(Params... params) { return null; } The doInBackground Override Required } Return value Method Name Description abstract Result doInBackground(Params... params) Background execution void onPostExecute(Result result) Upon completion of the process run in the background void onPreExecute() Previous operation to run in the background void onProgressUpdate(Progress... values) Progress Update for Background Processing void onCancelled() Cancel Background Processing ※ doInBackground onProgressUpdate for varargs and, even when passing non array in param [0] should be referenced This material is licensed under the Creative Commons License BY-NC-SA 4.0. 94

6.1. display of asynchronous (5) Execute AsyncTask • General way to create and execute an instance of subclass of AsyncTask, AsyncTask can be canceled during the execution / / get an instance of AsyncTask MyAsyncTask task = new MyAsyncTask (); / / execute AsyncTask task.execute ("MyAsyncTask execute"); • execute AsyncTask at instantiation of a subclass •Used if there is no need to cancel asynchronous implementation. •does not hold an instance can not be canceled if AsyncTask is running / / AsyncTask to run when the instantiation new MyAsyncTask (). execute ("args as doInBackground"); This material is licensed under the Creative Commons License BY-NC-SA 4.0. 95

6.1. display of asynchronous (6) Example AsyncTask counting program for 10 seconds. Indicator to display the count in the top right. Count starts after start Indicator Displays Counting This material is licensed under the Creative Commons License BY-NC-SA 4.0. End after ten seconds Indicator disappears 96

6.1. display of asynchronous (7) Sample Program public class AsyncSample extends Activity { private TextView text; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); / / display the title bar indicators requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.main); this.text = (TextView)findViewById(R.id.TextView01); this.text.setText("" + 0); / / AsyncTask run new MyAsyncTask().execute("args as doInBackground"); } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 97

6.1. display of asynchronous (8) Sample Program class MyAsyncTask extends AsyncTask<String, Integer, Boolean>{ @Override protected void onPreExecute() { / / onPreExecute Handler uses the UI can be changed without / / Display indicators setProgressBarIndeterminateVisibility(true); } @Override protected Boolean doInBackground(String... params) { Log.v("MyAsyncTask", "param:" + params[0]); for( int i = 0; i <= 10; i++){ try { / / progress update notification publishProgress(i); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); return false; } } return true; } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 98

6.1. display of asynchronous (9) Sample Program @Override protected void onPostExecute(Boolean result) { / / onPostExecute Handler uses the UI can be changed without if( result ){ text.setText(" Complete "); }else{ text.setText(" Failure "); } // To hide the indicator setProgressBarIndeterminateVisibility(false); } @Override protected void onProgressUpdate(Integer... values) { // In onProgressUpdate UI Handler can be modified without text.setText("" + values[0]); } } } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 99

6.1. display of asynchronous (10) • Creating a Sample Program AsyncTask image acquisition process is performed by updating the screen at the time you get. Indicator to display on the right of the screen Completed chart Now loading Icon appears Gradually icon Appear This material is licensed under the Creative Commons License BY-NC-SA 4.0. Complete 100

6.1. display of asynchronous (11) Sample Program Description SampleList.java public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // TODO No.01 in the title bar to display the indicator setContentView(R.layout.list); adpter = new TableAdapter(this); setListAdapter(adpter); // Creating RowModel // Get a text array from the resource String titles[] = getResources().getStringArray(R.array.titles); String summaries[] = getResources().getStringArray(R.array.summaries); Drawable loadingImage = getResources().getDrawable(R.drawable.ic_contact_picture); int num = titles.length; RowModel[] models = new RowModel[num]; // RowModel created for each single line // Into array for(int i = 0; i < num; i++){ RowModel row = new RowModel(); row.setTitle(titles[i]); row.setSummary(summaries[i]); row.setThumbnailImage(loadingImage); adpter.add(row); models[i] = row; } // TODO No.08 asynchronous call } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 101

6.1. display of asynchronous (12) Sample Program Description SampleList.java //Set each data element in the list to display each line @Override public View getView(int position, View convertView, ViewGroup parent) { View row = convertView; RowModel item = getItem(position); if(row == null){ // Creating View LayoutInflater inflater = getLayoutInflater(); row = inflater.inflate(R.layout.list_row_rich, null); } if( item != null){ // Image ImageView imageView = (ImageView)row.findViewById(R.id.image_thumbnail); This material is licensed under the Creative Commons License BY-NC-SA 4.0. 102

6.1. display of asynchronous (13) Sample Program Description SampleList.java if( imageView != null){ imageView.setImageDrawable(item.getThumbnailImage()); } //Title TextView textTitle = (TextView)row.findViewById(R.id.text_title); if(textTitle != null){ textTitle.setText(item.getTitle()); } // summary TextView textSummary = (TextView)row.findViewById(R.id.text_summary); if(textSummary != null){ textSummary.setText(item.getSummary()); } } return row; } } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 103

6.1. display of asynchronous () Asynchronous processing of image acquisition Process The image acquisition asynchronously INNER ListSample class "LoadImageTask" is defined. Implement the following actions: <Procedure> 1. To implement the onPreExecute methods . 1. Show Injiketadaiarogu process 2. To implement the methods doInBackground 1. RowModel arguments one by one to get data from an array to set the thumbnail. ※ListSample#getImage method to get the thumbnail image 1. Once thumbnail setup is complete, display ListView one at a time ※ using onProgressUpdate # onProgressUpdate which is callback method for AsyncTask # publishProgress . 3. to implement the onProgressUpdate method. 1. Renewal notices a TableAdapter ※ Adapter #. NotifyDataSetChanged Adapter Using methods that are bound to redraw View 4. to implement the methods onPostExecute This material 1. To hide Injiketadaiarogu is licensed under the Creative 104 Commons License BY-NC-SA 4.0.

6.1. display of asynchronous () Method Implementation Methods onPreExecute protected void onPreExecute() { // Indicator Display setProgressBarIndeterminateVisibility(true); } Methods onProgressUpdate protected void onProgressUpdate(Void... values) { / / change notification data adpter.notifyDataSetChanged(); } Methods onPostExecute protected void onPostExecute(Void result) { // To hide the indicator setProgressBarIndeterminateVisibility(false); } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 105

6.1. display of asynchronous () Method Implementation Methods doInBackground protected Void doInBackground(RowModel... arg0) { android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); // Read data from the arguments one by one, RowModel setting of Drawable for(RowModel rowModel : arg0){ if(isCancelled()){ Log.v("ListSample", "LoadImageTask#doInBackground() canceled."); break; } // Get thumbnail rowModel.setThumbnailImage(getImage()); // Update Notification publishProgress((Void)null); } return null; } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 106

6.1. display of asynchronous () Method Implementation ListSample.java public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Indicator to display the title bar requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.list); adpter = new TableAdapter(this); setListAdapter(adpter); - almost / / asynchronous call new LoadImageTask().execute(models); } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 107

6.1. Web services to connect • HTTP communication with WebAPI, For HTTP communication • • • • • • • • • • • • DefaultHttpClient: to communicate HTTP with the class. Set the request method. GET method: use HttpGet class. POST method: use HttpPost class. Issue requests to the specified URL. Pass HttpGet DefaultHttpClient # execute method arguments. To check the status response. To get the status code return HttpResponse class. ※ The HttpStatus status code constants are available in the class. Status Code: 200 HttpStatus.SC_OK are defined. Toridasu the necessary information from the response data. Return (HttpResponse) from HttpEntity (HTTP object for incoming and outgoing) can be obtained. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 108

6.1. Web services to connect • Sample Code // Destination URL String url = "http://www.oesf.jp/"; // Object Creation DefaultHttpClient DefaultHttpClient client = new DefaultHttpClient(); // GET request to the connection object creation method HttpGet get = new HttpGet(url); try { // To get a response to a request issued HttpResponse res = client.execute(get); // Check the status code if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ // Response to obtain information HttpEntity entity = res.getEntity(); } } catch (Exception e) { e.printStackTrace(); } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 109

6.1. Web services to connect • Creating a Sample Program Communicates HTTP GET method, the program checks the status code. Completed chart Click Logs This material is licensed under the Creative Commons License BY-NC-SA 4.0. 110

6.1. Creating a sample program (Overview) Create a sample HTTP communication program Items Setting Project name HttpSample Build Target 2.1 Application name HttpSample Package name jp.oesf.httpsample Create Activity HttpSample This material is licensed under the Creative Commons License BY-NC-SA 4.0. 111

6.1. Creating a sample program (provision) • Eclipse project to incorporate training for skeleton Location: Folder where you unzipped "HttpSample_skeleton01.zip" android_training_webapiChapter 6 HTTP Makoto Tooru From "File" select "Import” and "Import" dialog is displayed In "General" select "Existing Projects into Workspace“ then Press"Next" This material is licensed under the Creative Commons License BY-NC-SA 4.0. Select the Zip file and press "Finish" 112

6.1. Web services to connect to (1) Creating a Sample Program <Procedure> Fixed string.xml "HTTP communication " to add the string Fixed main.xml "HTTP Communication " to add button Add an HTTP communication processing class Activity When the button is pressed for HTTP connections. Destination "http://www.oesf.jp/" To ensure that the status code 200 To print “OK” in Log status Fixed AndroidManifest.xml Add internet communication Permissions This material is licensed under the Creative Commons License BY-NC-SA 4.0. 113

6.1. Web services to connect to (1) Creating a Sample Program How to Display Task On the menu “Window“, from ”ShowView” select “Tasks” At the bottom of "Tasks" select the Eclipse task list. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 114

6.1. Web services to connect to (1) Creating a Sample Program Modify a resource file string.xml property tables name String connect_http HTTP communication app_name HttpSample main.xml property tables Items Value View Button @+id / id name button_connect_http layout_width fill_parent Text connect_http On click onClickButton This material is licensed under the Creative Commons License BY-NC-SA 4.0. 115

6.1. Web services to connect to (1) Activity class to add the HTTP communication processing 1. implementation of the onClickButton method * Handling HTTP GET method to additional communicate Generating DefaultHttpClient object HttpGet to create objects. Argument to specify url: "http://www.oesf.jp/" To get a response to a request issued DefaultHttpClient # execute method to execute, HttpResponse objects to be returned Check the status code HttpResponse # getStatusLine () # getStatusCode () to check the status code 2. If the log output status output log 200: Log.v (TAG, "status ok"); This material is licensed under the Creative Commons License BY-NC-SA 4.0. 116

6.1. Web services to connect to (1) Fixed AndroidManifest.xml 1. Add internet communication Permissions AndroidManifest.xml file Append permission to allow Internet access. </activity> </application> <! - Add internet communication allowed permissions -> <uses-permission android:name="android.permission.INTERNET"> </uses-permission> <uses-sdk android:minSdkVersion="7" /> </manifest> This material is licensed under the Creative Commons License BY-NC-SA 4.0. 117

6.1. Web services to connect to (1) The answer to create a sample program string.xml <?xml version="1.0" encoding="utf-8"?> <resources> <! - HTTP communication "defines a string -> <string name="connect_http"> HTTP communication </string> <string name="app_name">HttpSample</string> </resources> This material is licensed under the Creative Commons License BY-NC-SA 4.0. 118

6.1. Web services to connect to (1) The answer to create a sample program main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <! - Button Add -> <Button android:layout_height="wrap_content" android:id="@+id/button_connect_http" android:text="@string/connect_http" android:layout_width="fill_parent" android:onClick="onClickButton"> </Button> </LinearLayout> This material is licensed under the Creative Commons License BY-NC-SA 4.0. 119

6.1. Web services to connect to (1) The answer to create a sample program HttpSample.java public class HttpSample extends Activity { private static final String TAG = "HttpClientSample"; // Destination URL private static final String URL = "http://www.oesf.jp/"; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void onClickButton(View v) { // No.01 DefaultHttpClient object generating DefaultHttpClient client = new DefaultHttpClient(); // No.02 GET request to the connection object generating method HttpGet get = new HttpGet(URL); This material is licensed under the Creative Commons License BY-NC-SA 4.0. 120

6.1. Web services to connect to (1) The answer to create a sample program HttpSample.java(2) try { // No.03 to get a response to a requested issue HttpResponse res = client.execute(get); // To check the status code No.04 if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // No.05 log output Log.v(TAG, "status ok"); } } catch (Exception e) { Log.e(TAG, Log.getStackTraceString(e)); } } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 121

6.1. Web services to connect to (1) The answer to create a sample program AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="jp.oesf.httpsample" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".HttpSample" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <! - Add internet communication allowed permissions -> <uses-permission android:name="android.permission.INTERNET"> </uses-permission> <uses-sdk android:minSdkVersion="7" /> </manifest> This material is licensed under the Creative Commons License BY-NC-SA 4.0. 122

6.1. Web services to connect to (1) The sample program creates two answers The sample program was created to add functionality to display the content. Completed chart Click This material is licensed under the Creative Commons License BY-NC-SA 4.0. 123

6.1. Web services to connect to (1) Get response data 1. Gets the HttpResponse HttpEntity. Get the content from the InputStream HttpEntity use. HttpEntity # getContent method can get the InputStream. OutputStream using the read data from InputStream. To convert imported data to a string. Stream Close InputStream in = null; ByteArrayOutputStream out = null; try { // InputStream retrieve content by using the in = res.getEntity().getContent(); out = new ByteArrayOutputStream(); // HTTP response data is read byte[] line = new byte[1024]; int size = 0; while (true) { size = in.read(line); if (size <= 0) { break; } out.write(line, 0, size); } // To convert the data into a string String http = new String(out.toByteArray()); } catch licensed under This material is (Exception e) { the Creative Commons License BY-NC-SA 4.0. 124

6.1. Web services to connect to (1) The sample program creates two answers <Procedure> Fixed main.xml TextView content for display of additional data Activity in response to a class data acquisition process getContents method implementation Get the InputStream from the response Read the data content Returns data converted to a string Data obtained on the screen Properties main.xml View @+ id / id name layout_width Text On click Button button_connect_http fill_parent connect_http onClickButton TextView text_content wrap_content No No This material is licensed under the Creative Commons License BY-NC-SA 4.0. 125

6.1. Web services to connect to (1) Answer mainxml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <! - Button Add -> <Button android:layout_height="wrap_content" android:id="@+id/button_connect_http" android:text="@string/connect_http" android:layout_width="fill_parent" android:onClick="onClickButton"> </Button> <! - TextView Add -> <TextView android:layout_width=“wrap_content” android:layout_height="wrap_content" android:id="@+id/text_content"> </TextView> </LinearLayout> This material is licensed under the Creative Commons License BY-NC-SA 4.0. 126

6.1. Web services to connect to (1) The two answers to create a sample program HttpSample.java public void onClickButton(View v) { DefaultHttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(URL); try { HttpResponse res = client.execute(get); if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { Log.v(TAG, "status ok"); // Comment out the following release String content = getContents(res); // TextView display content data obtained TextView text = (TextView)findViewById(R.id.text_content); text.setText(content); } } catch (Exception e) { Log.e(TAG, Log.getStackTraceString(e)); } } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 127

6.1. Web services to connect to (1) The two answers to create a sample program HttpSample.java(2) private String getContents(HttpResponse res) { InputStream in = null; ByteArrayOutputStream out = null; byte[] line = new byte[1024]; String data = null; int size = 0; try { // Get the InputStream from the response in = res.getEntity().getContent(); out = new ByteArrayOutputStream(); // HTTP response data is read while (true) { size = in.read(line); if (size <= 0) { break; } out.write(line, 0, size); } // Convert byte array to a string data = new String(out.toByteArray()); This material is licensed under the Creative Commons License BY-NC-SA 4.0. 128

6.1. Web services to connect to (1) The two answers to create a sample program HttpSample.java(3) } catch (Exception e) { Log.e(TAG, Log.getStackTraceString(e)); }finally{ try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (Exception e) { Log.e(TAG, Log.getStackTraceString(e)); } } return data; } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 129

6.2. XML is analyzed (DOM) • What is XML? One of the markup language for describing the structure and meaning of the data. Markup language "tags" in the sentence struct

Add a comment

Related presentations

Related pages

Getting Started | Android Developers

Running Your Application; ... Welcome to Training for Android ... The first training guides below teach you the essentials for Android app development.
Read more

Mobile App Development Training | Mobile Application ...

Mobile app Development Training. Build apps for iOS, Android, ... Understand Android applications and their life cycle, the application manifest, ...
Read more

Android Training | Android App Development Training Course

Android Training, Android Mobile APP Development Training Crash ... Android Mobile Applications Development Training Course is for anyone interested in ...
Read more

Android development training - Eclipse, Android and Java ...

... Android development, expert Android development and to learn how to ... Android Development Training. Android ... Android application ...
Read more

Mobile Application Developer Training, Jobs ...

Mobile Application Developer Training. ... iPhone Application Development Training; Android Application Development Training; Mobile Video Game Design ...
Read more

Android Development Training - PHP, Android, Java, .Net ...

Best Android Application Development Project Training in Lucknow ... Android Development Training. ... Infoseek is into Android Application Development ...
Read more

Android Application Development Training Course ...

Android Application Development Training Course. ... The Android Application Development course was very well delivered and left me with a wealth of real ...
Read more

Introduction to Android Development Training | Accelebrate

This Introduction to Android Development training course teaches ... CLI RESTful Services with Web API using C# ... Android application ...
Read more

Android™ ATC - Advanced Training Consultants

Android ATC (Advanced Training Consultants) ... Android™ Application Development; Android™ Security Essentials; Monetize Android™ Applications;
Read more