SlideShare uma empresa Scribd logo
1 de 271
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 structure and meaning of information in a
particular string, will called the embedded language and decoration.
Users can specify their own tags
Type

Contents

Description

Tags

<id> ~ </id>

"<"and ">" tag of the part enclosed by a
start tag and end tag

Attribute (attribute)

<thumbnail url “ ~ ”>

Be used to add additional information
to the tag

Value (Value)

<title> ~ </title>
<thumbnail url =“ ~ ”>

Son of a string enclosed with tags, if
the attribute value specified by "="

Namespace (namespace)

<feed xmlns:media = “ ~ ”>
<media:group/>
</feed>

To use to resolve conflicts by the same
tag name, namespace URI must be
unique

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

130
6.2. XML parsing to create a mechanism to
(prepare)
6.1 Please refer to the HTTP traffic. Capture to create a sample program (coming
soon)
•How to Get
•Eclipse project to incorporate training for skeleton
Locations
Capture answer folder  android_training_webapi  Chapter 6  XML
parsing  "XmlSample_skeleton01.zip ~ XmlSample_skeleton03.zip"

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

131
6.2. XML to parse
•

Skeleton Program

XML parsing exercises to create a sample using DOM, SAX, XMLPullparser.
Skeleton project has been implemented using the following functions:
XmlSample_skeleton01: parsing Unimplemented
XmlSample_skeleton02: DOM parsing process has been implemented
XmlSample_skeleton03: DOM and SAX parsing process is implemented
Each project is described in the task of implementing the exercise.
※ For the confirmation of the task, Please refer to the "TODO: HTTP Makoto Tooru
XXX "

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

132
6.2. XML to parse
•

Skeleton Program
Resource definition information
XmlSample_skeleton01 to XmlSample_skeleton03
Resources are defined in the following contents:

View

id (@ + id / id name)

Text(@+string )

On click

LinearLayout

LinearLayout01

LinearLayout

LinearLayout02

Button

button_dom

@string/dom

onClickDOMButton

Button

button_sax

@string/sax

onClickSAXButton

Button

button_xmlpullpaser

@string/xml_pullpaser

onClickXMLPullpaserButton

TextView

text_result

No

No

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

133
6.2. XML to parse
•

Parsing XML

Use the following XML document, DOM · SAX · XMLPullparser in XML Analysis

<sample.xml> ※ sample.xml The following assets are stored in folders
<?xml version="1.0" encoding="UTF-8"?>
<feed>
<entry>
<id>hPzNl6NKAG0</id>
<group>
<description> Everything is included for better sliding. (Just playing only) </description>
<thumbnail url="image/cat.jpg"></thumbnail>
<title> Training a cat. </title>
</group>
</entry>
</feed>

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

134
6.2. XML to create a mechanism to analyze (2)
•From an XML document to get and analyze the
following elements
The acquired data set RowModel

Tags

Attributes

Get value

id

No

hPzNl6NKAG0

title

No

Training a cat.

description

No

Everything is included for better sliding.

thumbnail

url

image/cat.jpg

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

135
6.2. Parse XML
•

About RowModel

•Data were analyzed by the XML held in RowModel
•Xml file analysis, data obtained by video downloader
•This is a simplified information
•The following RowModel jp.oesf.xmldomsample.model
•Is defined in the file "RowModel.java".
•XML data document that defines the following member variable holds:
Variable

Get Data

id

<id>

title

<title>

Summary

<description>

thumbnailImageURL

<thumbnail url = "Get data">

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

136
6.2. XML to parse
•DOM (tree type)
• XML DOM with the contents of the heap as a tree.
• When parsing XML to hold the entire contents of memory after parsing, any
element 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 easily implement.
Okay Oso

DOM
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

Large memory consumption

137
6.2. XML is analyzed (DOM)
Analysis of the XML DOM tree
Element

<feed>

Description
Tags

Attributes

<entry>
<id>
Video ID

Value

<group>
<description>

<thumbnail>

<title>

url
Video Description

Thumbnail Image
The URL

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

Title
138
6.2. XML is analyzed (DOM)
•
Parsing XML with DOM
<Procedure>
•
Document object to retrieve XML data
•
DocumentBuilderFactory to create objects
•
Creates a DOM parser
•
Building parse XML into DOM tree
•

Get the root element of XML data

•

Follows the DOM tree to get the desired node

•

To obtain the data held by the nodes (tags and text
data)
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

139
6.2. XML is analyzed (DOM)
The following sample XML document parsing
<?xml version="1.0" encoding="UTF-8"?>
<root>
<node1>Node Value</node1>
</root>

※ The new line is not actually

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

140
6.2. XML is analyzed (DOM)
Sample Code
InputStream in = null;
try {
//Generate Dokyumentobirudafakutori
DocumentBuilderFactory dbfactory = DocumentBuilderFactory
.newInstance();
// Generate Dokyumentobiruda
DocumentBuilder builder = dbfactory.newDocumentBuilder();
// get a stream of xml file
in = getAssets().open("samplea.xml");
// To retrieve and parse the Document Object
Document doc = builder.parse(in);
// Gets the root element (tag name: root)
Element root = doc.getDocumentElement();
// Get <node1>
NodeList entryList = root.getElementsByTagName("node1");
// First get <node1>
Element node1Element = (Element) entryList.item(0);
// Get the value of <node1>
String nodevalue = node1Element.getFirstChild().getNodeValue();
// Display values
Log.v(TAG, nodevalue);
} catch (Exception e) {

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

141
6.2. XML is analyzed (DOM)
•

Creating a Sample Program

Completed chart

Click

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

142
6.2. XML is analyzed (DOM)
Creating a Sample Program
<Procedure>
1. XmlHelper parseDom class that implements the following processing
methods
1. Document object to retrieve XML data
2. Creates a DOM parser
3. Building parse XML into DOM tree
4. <id> <entry> to get the value in the tag, set the value to
RowModel
5. The id RowModel is set to the value obtained
6. <thumbnail> set the Rowmodel value to the value retrievd from
the “url” attribute.

1. Implementing Activity onClickDOMButton class
1. XmlHelper # parseDom shaping method to the data to obtain
RowModel ※ instance member variable "xmlHelper" is defined
in XmlHelper
This material is licensed under the Creative
143
2. TextView to display Commons License BY-NC-SA 4.0.
the analysis results
6.2. XML is analyzed (DOM)
The answer to create a sample program
XmlHelper.java
public RowModel parseDom(Context context, String xml) {
// RowModel row = new RowModel();
RowModel rowModel = new RowModel();
InputStream in = null;
try {
// Generate Dokyumentobirudafakutori
DocumentBuilderFactory dbfactory = DocumentBuilderFactory
.newInstance();
dbfactory.setNamespaceAware(true);
// Generate Dokyumentobiruda
DocumentBuilder builder = dbfactory.newDocumentBuilder();
// get a stream of xml file
in = context.getAssets().open("sample.xml");
// To retrieve and parse the Document Object
Document doc = builder.parse(in);
// Gets the root element (tag name: feed)
Element root = doc.getDocumentElement();
// Get <entry>
NodeList entryList = root.getElementsByTagName("entry");
// First get <entry>
Element entryElement = (Element) entryList.item(0);
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

144
6.2. XML is analyzed (DOM)
The answer to create a sample program
Continued XmlHelper.java
/* <id> processing * /
/ / Get <id> obtained from <entry>
Element idElement = (Element) entryElement.getFirstChild();
/ / get the Text data obtained from <id>
String id = idElement.getFirstChild().getNodeValue();
// RowModel value set
rowModel.setId(id);
/* <description> processing * /
// Get <description> <entry> obtained from
NodeList desriptionList = entryElement.getElementsByTagName("description");
// Node information from text.
String summary = desriptionList.item(0).getFirstChild().getNodeValue();
// Cut off after 20 characters.
if (summary != null && 0 < summary.length()) {
if (20 < summary.length()) {
summary = summary.substring(0, 20);
}
}

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

145
6.2. XML is analyzed (DOM)
The answer to create a sample program
Continued XmlHelper.java
// Node information from text.
String summary = desriptionList.item(0).getFirstChild().getNodeValue();
// Cut off after 20 characters.
if (summary != null && 0 < summary.length()) {
if (20 < summary.length()) {
summary = summary.substring(0, 20);
}
}
// RowModel value set
rowModel.setSummary(summary);
/* <thumbnail> Processing * /
// <thumbnail> Get
NodeList thumbnailList = entryElement.getElementsByTagName("thumbnail");

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

146
6.2. XML is analyzed (DOM)
The answer to create a sample program
Continued XmlHelper.java
// First get <thumbnail>
Element thumbnailElement = (Element) thumbnailList.item(0);
// <thumbnail> the "url" attribute gets the value of
String thumbnail = thumbnailElement.getAttribute("url");
// RowModel value set
rowModel.setThumbnailImageURL(thumbnail);
/* <title> processing * /
// <title> Get
NodeList titleList = entryElement.getElementsByTagName("title");
// Node information from text
String title = titleList.item(0).getFirstChild().getNodeValue();
// RowModel value set
rowModel.setTitle(title);

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

147
6.2. XML is analyzed (DOM)
The answer to create a sample program
XmlHelper.java
public void onClickDOMButton(View v) {
RowModel rowModel = null;
// RowModel XmlHelper # parseDom get a call
rowModel = this.xmlHelper.parseDom(this, this.xml);
if (rowModel == null) {
this.textResult.setText ("Failed to retrieve data. ")
} else {
// TextView to display the contents of rowModel
this.textResult.setText(rowModel.toString());
}
}

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

148
6.2. create a mechanism to analyze XML(1)
Parsing XML Data
•WebAPI is retrieved using the HTTP data
communication with the following
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/"
xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:gd="http://schemas.google.com/g/2005"
xmlns:yt="http://gdata.youtube.com/schemas/2007">
:
- <entry>
<id>http://gdata.youtube.com/feeds/api/videos/fzzjgBAaWZw</id>
:
<media:group>
<media:description type="plain">ブログ・モア*モアレmoire.lowdope.com</media:description>
:
<media:thumbnail url="http://i.ytimg.com/vi/fzzjgBAaWZw/2.jpg" height="90" width="120"
time="00:00:37" />
:
<media:title type="plain">だるまさんが転んにゃ - Stalking Cat -</media:title>
:
</media:group>
</entry>
</feed>
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

149
6.2. create a mechanism to analyze
XML(2)
•Exercise: making DOM, XMLPullParser,
SAX parsing process by using them.

•Retrieved from the XML data, analyzing
the following elements into Entity.
–id
–description
–thumbnail url
–title
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

150
6.2. XML is analyzed (DOM)
•
Parsing XML with DOM
<Procedure>
•
Document object to retrieve XML data
•
DocumentBuilderFactory to create objects
•
Creates a DOM parser
•
DOM tree is built to amend the XML
•

Get the root element of XML data

•

Follows the DOM tree to get the desired node

•

To obtain the data held by the nodes (tags and text
data) .
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

151
6.2. XML is analyzed (DOM)
•Parsing XML with DOM
public List<RowModel> parseTableModelDom(final String data)
throws IllegalStateException, IOException,
ParserConfigurationException, SAXException {
final List<RowModel> result = new ArrayList<RowModel>(MAX_RESULTS);
// Generate Dokyumentobirudafakutori
DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
dbfactory.setNamespaceAware(true);
// Generate Dokyumentobiruda
DocumentBuilder builder = dbfactory.newDocumentBuilder();
// To retrieve and parse the Document Object
InputSource is = new InputSource(new StringReader(data));
Document doc = builder.parse(is);
// Gets the root element (tag name: message)
Element root = doc.getDocumentElement();

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

152
6.2. XML is analyzed (DOM)
•Parsing XML with DOM (cont'd)
NodeList entryList = root.getElementsByTagName("entry");
for (int i = 0; i < entryList.getLength(); i++) {
RowModel rowModel = new RowModel();
Element entryElement = (Element) entryList.item(i);
Element idElement = (Element) entryElement.getFirstChild();
String url = idElement.getFirstChild().getNodeValue();
rowModel.setUrl(url);
NodeList desriptionList = entryElement.getElementsByTagNameNS(
"http://search.yahoo.com/mrss/", "description");
String summary = desriptionList.item(0).getFirstChild()
.getNodeValue();
if (summary != null && 0 < summary.length()) {
if (20 < summary.length()) {
summary = summary.substring(0, 20);
}
}
rowModel.setSummary(summary);
NodeList thumbnailList = entryElement.getElementsByTagNameNS(
"http://search.yahoo.com/mrss/", "thumbnail");
Element thumbnailElement = (Element) thumbnailList.item(0);
String thumbnail = thumbnailElement.getAttribute("url");
rowModel.setThumbnailImageURL(thumbnail);
NodeList titleList = entryElement.getElementsByTagNameNS(
"http://search.yahoo.com/mrss/", "title");
String title = titleList.item(0).getFirstChild().getNodeValue();
rowModel.setTitle(title);
result.add(rowModel);
}
return result;
}

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

153
6.2. SAX (repetition)
•SAX (event-driven)
• Such images that invoke the application parsing the parser.
• Iki read XML documents from his head, and start and end tags
• To strike, call the application of a fixed callback routine.
• By the application of the XML
• To make DOM not to read the document control
• Memory consumption is less than the DOM.
• Android is the conventional method of using the SAX,
• On SAX there are ways to use a wrapper.

Er is soooo ♪

!!!!!

My more
・ ・ ・ easy to use mon

SAX
DOM

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

154
6.2. XML is analyzed (SAX)
Parsing XML with SAX
<Procedure>
•

Creating a SAX event handler class to receive callbacks from the parser

•

To get SAX parser, create Pasafakutori SAX,

•

Set the SAX event handler class created by a parser

•

Start parsing an XML to be called back by an event handler created when the event occurred

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

155
6.2. XML is analyzed (SAX)
•
•

DefaultHandler to create a subclass that inherits the class
Implement a process corresponding to each event

– Creating a SAX event handler class
to receive callbacks from the
parser at the start of implementation of the event
1.
Tag
2.
3.

Implementation of events at the end tag
Implementation of events in a text element

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

156
6.2. XML is analyzed (SAX)
<method to override>
Return
value

Method Name

Description

void

startElement(String uri,
String localName,
String qName,
Attributes attributes)

Receive notification of the start of an element
Parameters
uri - namespace URI
localName - The local name prefix qualifier
qName - qualified name with a prefix
attributes - attributes that were added to the element

void

endElement(String uri,
String localName,
String qName)

Receive notification of the end of an element
Parameters
uri - namespace URI
localName - The local name prefix qualifier
qName - qualified name with a prefix

void

void characters(char[] ch,
int start,
int length)

Receives notification of character data inside an element
Parameters
ch - the character
start - starting position in the character array
length - number of characters from a character array to be used

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

157
6.2. XML is analyzed (SAX)
•

Sample Code

The following sample XML document parsing
<?xml version="1.0" encoding="UTF-8"?>
<root>
<node1>Node Value</node1>
</root>
※ The actual document does not break space

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

158
6.2. XML is analyzed (SAX)
Sample Code
/ / get the stream to be parsed
InputSource is = new InputSource (new StringReader (xml));
/ / Create a parser Factory
SAXParserFactory saxParaser = SAXParserFactory.newInstance ();
try {
/ * Get the parser * /
SAXParser sp = saxParaser.newSAXParser ();
/ * Create an event handler * /
SaxHandler sh = new SaxHandler ();
/ * pass input data and event handlers to the event handler * /
sp.parse (is, sh);
} Catch (Exception e) {
e.printStackTrace ();
}

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

Create SAX parser

Parsing XML

159
6.2. XML is analyzed (SAX)
Sample Code
class SaxHandler extends DefaultHandler {
/ / Tag start flag
boolean isNode1;
@ Override
public void startElement (String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if ("node1". equals (localName)) {
/ / Node1 start tag
isNode1 = true;
}
}

Tag at the start of treatment

@ Override
public void endElement (String uri, String localName, String qName)
throws SAXException {
if ("node1". equals (localName)) {
/ / Node1 start tag
isNode1 = false;
}
}

@ Override
public void characters (char [] ch, int start, int length)
throws SAXException {
/ / Node1 tag if it is started, log text
if (isNode1) {
String nodevalue = new String (ch, start, length);
Log.v (TAG, nodevalue);
}
}
}

Tag at the end of treatment

Text Event Processing

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

160
6.2. XML is analyzed (SAX)
•

Creating a Sample Program

Completed chart

Click

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

161
6.2. XML is analyzed (SAX)
Creating a Sample Program
<Procedure>
XmlHelper DefaultHandler class to create a class that inherits the subclass
startElement, characters, endElement methods are implemented

XmlHelper parseSax class that implements the following processing
methods
Create a SAX parser object
XML parsing Hazime Hiraku
Implementing Activity onClickSAXButton class
XmlHelper # parseSax shaping method to the data to obtain RowModel
※ XmlHelper instance member variable "xmlHelper" is defined in
TextView to display the analysis results

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

162
6.2. XML is analyzed (SAX)
<XmlHelper.java>

•

Answer
public RowModel parseSax (Context context, String xml) {
/ / get the stream to be parsed
InputSource is = new InputSource (new StringReader (xml));
/ / Create a parser Factory
SAXParserFactory saxParaser = SAXParserFactory.newInstance ();
try {
/ / Get the parser
SAXParser sp = saxParaser.newSAXParser ();
/ / Create an event handler
SaxHandler sh = new SaxHandler ();
/ / pass the input data and an event handler to the event handler
sp.parse (is, sh);
return sh.rowModel;
} Catch (Exception e) {
e.printStackTrace ();
}
return null;
}
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

163
6.2. XML is analyzed (SAX)
•

Answer

<XmlHelper.java( More )>

class SaxHandler extends DefaultHandler {
RowModel rowModel = new RowModel ();
/ / Tag start flag
boolean isEntry;
boolean isId = false;
boolean isSummary = false;
boolean isTitle = false;
boolean isThumbnail = false;
String id = null;
String summary = null;
String thumbnail = null;
String title = null;

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

164
6.2. XML is analyzed (SAX)
<XmlHelper.java(More)>

•

Answer

@ Override
public void startElement (String uri, String localName, String qName,
Attributes attributes) throws SAXException {
/ / Entry to true if the tag is isEntry
if ("description". equals (localName)) {
/ / Entry tag begins
isEntry = true;
}
/ / Entry in the tag determines if
if (isEntry) {
if ("id". equals (localName)) {
isId = true;
}
if ("description". equals (localName)) {
isSummary = true;
}
if (! isThumbnail & & "thumbnail". equals (localName)) {
/ / Thumnail to get the url attribute of the tag
thumbnail = attributes.getValue ("url");
isThumbnail = true;

}
if ("title". equals (localName)) {
isTitle = true;
}
}
}

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

165
6.2. XML is analyzed (SAX)
•

Answer

<XmlHelper.java( More )>

@ Override
public void endElement (String uri, String localName, String qName)
throws SAXException {
if ("entry". equals (localName)) {
/ / RowModel to set the value to
rowModel.setId (id);
rowModel.setSummary (summary);
rowModel.setThumbnailImageURL (thumbnail);
rowModel.setTitle (title);
/ / clear values
id = null;
summary = null;
thumbnail = null;
title = null;
isThumbnail = false;
isEntry = false;
}
}

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

166
6.2. XML is analyzed (SAX)
•

Answer

<XmlHelper.java( More )>

@ Override
public void characters (char [] ch, int start, int length)
throws SAXException {
if (isEntry) {
if (isId) {
/ / Id to get
id = new String (ch, start, length);
isId = false;
}
if (isSummary) {
/ / Description to obtain
summary = new String (ch, start, length);
if (summary! = null & & 0 <summary.length ()) {
if (20 <length) {
summary = summary.substring (0, 20);
}
}
isSummary = false;
}
if (isTitle) {
/ / Title to get
title = new String (ch, start, length);
isTitle = false;
}
}
}

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

167
6.2. XML is analyzed (SAX)
•

Answer

<XmlSample.java>

public void onClickSAXButton (View v) {
RowModel rowModel = null;
/ / XmlHelper # parseSax RowModel get a call
rowModel = this.xmlHelper.parseDom (this, this.xml);
if (rowModel == null) {
this.textResult.setText ("Failed to retrieve data. ")
} else {
/ / TextView to display the contents of rowModel
this.textResult.setText (rowModel.toString ());
}
}

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

168
6.2. XMLPullParser (repetition)
•

XMLPullParser (Pull Type)

•

SAX JAVA by what shall have the same functionality, so Android will not
support the same functionality that is available to XMLPullParser.

•

SAX as an XML document read from the head, performed by the application
of the load control, and can retrieve information from the parser, if necessary.

•

To make an application from the control, it is possible to stop the parsing
early that can significantly reduce the time required to parse.

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

169
6.2. XML is analyzed (XMLPullpaser)
•

Parsing XML with XMLPullpaser

<Procedure>
•
Create an XmlPullParser object
•

Passing a string parser to parse

•

XML to retrieve one event analysis

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

170
6.2. XML is analyzed (XMLPullpaser)
•

Sample Code

The following sample XML document parsing
<?xml version="1.0" encoding="UTF-8"?>
<root>
<node1>Node Value</node1>
</root>
※ The actual document does not break space

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

171
6.2. XML is analyzed (XMLPullpaser)
Sample Code
InputStream in = null;
try {
/ / get the stream to be parsed
is = getAssets (). open ("samplea.xml");
/ / XmlPullParser XmlPullParser define
final XmlPullParser parser = Xml.newPullParser ();
/ / XmlPullParser pass a stream to parse the string
parser.setInput (new InputStreamReader (is));
parser.next (); / / root tag
parser.next (); / / node1 tags
/ / XmlPullParser to obtain the name of the tag
String tag = parser.getName ();
/ / XmlPullParser tag name is "node1", then
if ("node1". equals (tag)) {
parser.next ();
String nodevalue = parser.getText ();
Log.v (TAG, nodevalue);
}
} Catch (Exception e) {

Create parser XMLPullParser
Passing a string parser to parse

XML parsing events to get one at a time

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

172
6.2. XML is analyzed (XMLPullpaser)
•

Creating a Sample Program

Completed chart

Click

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

173
6.2. XML is analyzed (XMLPullpaser)
Creating a Sample Program
<Procedure>
XmlHelper parseXmlPullparser class method to implement the following
actions:
Define XmlPullParser
Passing a stream of string to parse
While processing one by one statement.
<id> <entry> to get the value in the tag, set the value to RowModel
<thumbnail> set the value to RowModel that retrived from the “url”
attribute.
Implementing Activity onClickXMLPullparserButton class
XmlHelper # parseXmlPullparser shaping method to the data to obtain
RowModel
※ XmlHelper instance member variable "xmlHelper" is defined in
TextView to display the analysis results
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

174
6.2. XML is analyzed (XMLPullpaser)
•

Answer

<XmlHelper.java>
public RowModel parseXmlPullparser (context, String xml) {
RowModel rowModel = null;
InputStream is = null;
try {
/ / Get the stream to be parsed
is = context.getAssets (). open ("sample.xml");
/ / XmlPullParser define
final XmlPullParser parser = Xml.newPullParser ();
/ / Pass the string to parse a stream of
parser.setInput (new InputStreamReader (is));
int eventType;
/ / XmlPullParser get the parsed hierarchy
final int depth = parser.getDepth ();
/ / XmlPullParser Perth exit conditions
/ / While processing the statements one at a time
while (((eventType = parser.next ())! = XmlPullParser.END_DOCUMENT | | parser.getDepth ()> depth)) {
/ / XmlPullParser eventType determine if a start tag
if (eventType == XmlPullParser.START_TAG) {
/ / XmlPullParser to obtain the name of the tag
String tag = parser.getName ();
/ / XmlPullParser tag name is "entry" if, parseToRowModel call
if ("entry". equals (tag)) {
rowModel = parseToRowModel (parser);
break;
}
}
}

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

175
6.2. XML is analyzed (XMLPullpaser)
•

Answer

<XmlHelper.java> ( More )
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return rowModel;
}

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

176
6.2. XML is analyzed (XMLPullpaser)
•

Answer
<XmlHelper.java> (More)
private RowModel parseToRowModel (XmlPullParser parser) throws XmlPullParserException, IOException {
RowModel rowModel = new RowModel ();
int eventType;
String tag = null;
/ / Get the hierarchy to Perth
final int depth = parser.getDepth ();
/ / End condition Perth
while (((eventType = parser.next ())! = XmlPullParser.END_DOCUMENT | | parser.getDepth ()> depth)) {
/ / EventType determine if a start tag
if (eventType == XmlPullParser.START_TAG) {
tag = parser.getName ();
/ / <entry> <id> To get the value in the tag, RowModel set the value to
if ("id". equals (tag)) {
/ / Move next.
parser.next ();
/ / Parser to get information from the text, rowModel set to the URL.
rowModel.setId (parser.getText ());
} Else if ("description". Equals (tag)) {
/ / Move next.
parser.next ();
/ / Parser to get information from the text.
String summary = parser.getText ();
/ / 20 characters, so cut fit.
if (summary! = null & & 0 <summary.length ()) {
if (20 <summary.length ()) {
summary = summary.substring (0, 20);
}
}

This material is licensed under the Creative
Commons License BY-NC-SA 4.0.

177
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training
Android Application WebAPI Development Training

Mais conteúdo relacionado

Mais procurados

foss-30oct-2012
foss-30oct-2012foss-30oct-2012
foss-30oct-2012
S Sridhar
 
Developing and-benchmarking-native-linux-applications-on-android
Developing and-benchmarking-native-linux-applications-on-androidDeveloping and-benchmarking-native-linux-applications-on-android
Developing and-benchmarking-native-linux-applications-on-android
Elvis Jon Freddy Sitinjak
 
Jeet Shah - CV
Jeet Shah - CVJeet Shah - CV
Jeet Shah - CV
jeet shah
 
SnehalBale_Java_Developer_2.4yrs exp
SnehalBale_Java_Developer_2.4yrs expSnehalBale_Java_Developer_2.4yrs exp
SnehalBale_Java_Developer_2.4yrs exp
Snehal Bale
 

Mais procurados (20)

Setting up a vscode development environment for mbed 5 application using the ...
Setting up a vscode development environment for mbed 5 application using the ...Setting up a vscode development environment for mbed 5 application using the ...
Setting up a vscode development environment for mbed 5 application using the ...
 
Open Source Licenses and Tools
Open Source Licenses and ToolsOpen Source Licenses and Tools
Open Source Licenses and Tools
 
Containers and Virtualisation for Continuous Testing
Containers and Virtualisation for Continuous Testing   Containers and Virtualisation for Continuous Testing
Containers and Virtualisation for Continuous Testing
 
Bhavin_Resume
Bhavin_ResumeBhavin_Resume
Bhavin_Resume
 
9780134433646 annuzzi ch02 (1)
9780134433646 annuzzi ch02 (1)9780134433646 annuzzi ch02 (1)
9780134433646 annuzzi ch02 (1)
 
foss-30oct-2012
foss-30oct-2012foss-30oct-2012
foss-30oct-2012
 
Video Streaming: from the native Android player to uncoventional devices
Video Streaming: from the native Android player to uncoventional devicesVideo Streaming: from the native Android player to uncoventional devices
Video Streaming: from the native Android player to uncoventional devices
 
Node.js vs. java
Node.js vs. javaNode.js vs. java
Node.js vs. java
 
Android Native Apps Development
Android Native Apps DevelopmentAndroid Native Apps Development
Android Native Apps Development
 
Developing and-benchmarking-native-linux-applications-on-android
Developing and-benchmarking-native-linux-applications-on-androidDeveloping and-benchmarking-native-linux-applications-on-android
Developing and-benchmarking-native-linux-applications-on-android
 
Jeet Shah - CV
Jeet Shah - CVJeet Shah - CV
Jeet Shah - CV
 
Apache Maven - eXo VN office presentation
Apache Maven - eXo VN office presentationApache Maven - eXo VN office presentation
Apache Maven - eXo VN office presentation
 
Android development basic _ZuoSyuanWang
Android development basic _ZuoSyuanWangAndroid development basic _ZuoSyuanWang
Android development basic _ZuoSyuanWang
 
ASP.NET vs ASP.NET Core
ASP.NET vs ASP.NET CoreASP.NET vs ASP.NET Core
ASP.NET vs ASP.NET Core
 
Java is evolving rapidly: Maven helps you staying on track
Java is evolving rapidly:  Maven helps you staying on trackJava is evolving rapidly:  Maven helps you staying on track
Java is evolving rapidly: Maven helps you staying on track
 
Android Development Tutorial V3
Android Development Tutorial   V3Android Development Tutorial   V3
Android Development Tutorial V3
 
Swing is not dead
Swing is not deadSwing is not dead
Swing is not dead
 
How the Atlassian Plugin SDK Cured Cancer and Reunited Soundgarden - Atlassia...
How the Atlassian Plugin SDK Cured Cancer and Reunited Soundgarden - Atlassia...How the Atlassian Plugin SDK Cured Cancer and Reunited Soundgarden - Atlassia...
How the Atlassian Plugin SDK Cured Cancer and Reunited Soundgarden - Atlassia...
 
SnehalBale_Java_Developer_2.4yrs exp
SnehalBale_Java_Developer_2.4yrs expSnehalBale_Java_Developer_2.4yrs exp
SnehalBale_Java_Developer_2.4yrs exp
 
Intro to Angular.js & Zend2 for Front-End Web Applications
Intro to Angular.js & Zend2  for Front-End Web ApplicationsIntro to Angular.js & Zend2  for Front-End Web Applications
Intro to Angular.js & Zend2 for Front-End Web Applications
 

Destaque

Destaque (6)

Androidアプリケーション応用 WebAPI開発
Androidアプリケーション応用 WebAPI開発Androidアプリケーション応用 WebAPI開発
Androidアプリケーション応用 WebAPI開発
 
Introduction of oesf education consortium
Introduction of oesf education consortiumIntroduction of oesf education consortium
Introduction of oesf education consortium
 
Android UIデザイン入門
Android UIデザイン入門Android UIデザイン入門
Android UIデザイン入門
 
Android組み込み開発テキスト pandaboard es編
Android組み込み開発テキスト pandaboard es編Android組み込み開発テキスト pandaboard es編
Android組み込み開発テキスト pandaboard es編
 
Android™組込み開発基礎コース BeagleBoard編
Android™組込み開発基礎コース BeagleBoard編Android™組込み開発基礎コース BeagleBoard編
Android™組込み開発基礎コース BeagleBoard編
 
Androidアプリケーション開発入門
Androidアプリケーション開発入門Androidアプリケーション開発入門
Androidアプリケーション開発入門
 

Semelhante a Android Application WebAPI Development Training

Introduction to android sessions new
Introduction to android   sessions newIntroduction to android   sessions new
Introduction to android sessions new
Joe Jacob
 
UKLUG 2012 - XPages, Beyond the basics
UKLUG 2012 - XPages, Beyond the basicsUKLUG 2012 - XPages, Beyond the basics
UKLUG 2012 - XPages, Beyond the basics
Ulrich Krause
 

Semelhante a Android Application WebAPI Development Training (20)

Introduction to android sessions new
Introduction to android   sessions newIntroduction to android   sessions new
Introduction to android sessions new
 
Introduction to Android Development and Security
Introduction to Android Development and SecurityIntroduction to Android Development and Security
Introduction to Android Development and Security
 
iOS Application Penetration Testing for Beginners
iOS Application Penetration Testing for BeginnersiOS Application Penetration Testing for Beginners
iOS Application Penetration Testing for Beginners
 
XPages -Beyond the Basics
XPages -Beyond the BasicsXPages -Beyond the Basics
XPages -Beyond the Basics
 
Android Studio development model and.pptx
Android Studio development model and.pptxAndroid Studio development model and.pptx
Android Studio development model and.pptx
 
Developing for Android-Types of Android Application
Developing for Android-Types of Android ApplicationDeveloping for Android-Types of Android Application
Developing for Android-Types of Android Application
 
Lick my Lollipop
Lick my LollipopLick my Lollipop
Lick my Lollipop
 
Expanding XPages with Bootstrap Plugins for Ultimate Usability
Expanding XPages with Bootstrap Plugins for Ultimate UsabilityExpanding XPages with Bootstrap Plugins for Ultimate Usability
Expanding XPages with Bootstrap Plugins for Ultimate Usability
 
Extension Library - Viagra for XPages
Extension Library - Viagra for XPagesExtension Library - Viagra for XPages
Extension Library - Viagra for XPages
 
Django simplified : by weever mbakaya
Django simplified : by weever mbakayaDjango simplified : by weever mbakaya
Django simplified : by weever mbakaya
 
How to create android applications
How to create android applicationsHow to create android applications
How to create android applications
 
Profiling and Tuning a Web Application - The Dirty Details
Profiling and Tuning a Web Application - The Dirty DetailsProfiling and Tuning a Web Application - The Dirty Details
Profiling and Tuning a Web Application - The Dirty Details
 
Android Lollipop
Android LollipopAndroid Lollipop
Android Lollipop
 
IBM Index 2018 Conference Workshop: Modernizing Traditional Java App's with D...
IBM Index 2018 Conference Workshop: Modernizing Traditional Java App's with D...IBM Index 2018 Conference Workshop: Modernizing Traditional Java App's with D...
IBM Index 2018 Conference Workshop: Modernizing Traditional Java App's with D...
 
Android app development: a top-down perspective
Android app development: a top-down perspectiveAndroid app development: a top-down perspective
Android app development: a top-down perspective
 
Make Cross-platform Mobile Apps Quickly - SIGGRAPH 2014
Make Cross-platform Mobile Apps Quickly - SIGGRAPH 2014Make Cross-platform Mobile Apps Quickly - SIGGRAPH 2014
Make Cross-platform Mobile Apps Quickly - SIGGRAPH 2014
 
iOS Application Exploitation
iOS Application ExploitationiOS Application Exploitation
iOS Application Exploitation
 
UKLUG 2012 - XPages, Beyond the basics
UKLUG 2012 - XPages, Beyond the basicsUKLUG 2012 - XPages, Beyond the basics
UKLUG 2012 - XPages, Beyond the basics
 
iOS Application Pentesting
iOS Application PentestingiOS Application Pentesting
iOS Application Pentesting
 
AEM - A Collection of developer friendly tools
AEM - A Collection of developer friendly toolsAEM - A Collection of developer friendly tools
AEM - A Collection of developer friendly tools
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Último (20)

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 

Android Application WebAPI Development Training

  • 2. 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
  • 3. 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
  • 4. 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
  • 6. 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
  • 7. 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
  • 8. 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
  • 9. 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
  • 10. 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
  • 11. 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
  • 13. 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
  • 14. 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
  • 15. 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
  • 16. 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
  • 17. 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
  • 18. 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
  • 19. 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
  • 20. 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
  • 21. 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
  • 22. 3. Preparing the Development Environment
  • 23. 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
  • 24. 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
  • 25. 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
  • 26. 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
  • 27. 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
  • 28. 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
  • 29. 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
  • 30. 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
  • 31. 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
  • 32. 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.
  • 33. 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
  • 34. 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
  • 35. 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
  • 36. 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
  • 37. 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
  • 38. 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
  • 39. 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
  • 40. 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
  • 41. 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
  • 42. 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
  • 44. 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
  • 45. 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
  • 46. 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
  • 47. 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
  • 48. 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
  • 49. 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
  • 50. 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
  • 51. 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
  • 52. 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
  • 53. 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
  • 55. 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
  • 56. 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
  • 57. 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
  • 58. 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
  • 59. 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
  • 60. 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
  • 61. 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
  • 62. 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
  • 63. 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
  • 64. 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
  • 65. 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
  • 66. 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
  • 67. 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
  • 68. 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
  • 69. 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
  • 70. 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
  • 71. 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
  • 72. 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
  • 73. 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
  • 74. 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
  • 75. 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
  • 76. 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
  • 77. 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
  • 78. 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
  • 79. 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
  • 80. 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
  • 81. 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
  • 82. 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
  • 83. 5.3. Customizing the list view •<result> This material is licensed under the Creative Commons License BY-NC-SA 4.0. 83
  • 84. 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
  • 85. 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
  • 86. 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
  • 87. 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
  • 89. 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
  • 90. 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
  • 91. 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
  • 92. 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
  • 93. 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
  • 94. 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
  • 95. 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
  • 96. 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
  • 97. 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
  • 98. 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
  • 99. 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
  • 100. 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
  • 101. 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
  • 102. 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
  • 103. 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
  • 104. 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.
  • 105. 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
  • 106. 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
  • 107. 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
  • 108. 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
  • 109. 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
  • 110. 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
  • 111. 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
  • 112. 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
  • 113. 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
  • 114. 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
  • 115. 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
  • 116. 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
  • 117. 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
  • 118. 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
  • 119. 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
  • 120. 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
  • 121. 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
  • 122. 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
  • 123. 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
  • 124. 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
  • 125. 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
  • 126. 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
  • 127. 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
  • 128. 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
  • 129. 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
  • 130. 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 structure and meaning of information in a particular string, will called the embedded language and decoration. Users can specify their own tags Type Contents Description Tags <id> ~ </id> "<"and ">" tag of the part enclosed by a start tag and end tag Attribute (attribute) <thumbnail url “ ~ ”> Be used to add additional information to the tag Value (Value) <title> ~ </title> <thumbnail url =“ ~ ”> Son of a string enclosed with tags, if the attribute value specified by "=" Namespace (namespace) <feed xmlns:media = “ ~ ”> <media:group/> </feed> To use to resolve conflicts by the same tag name, namespace URI must be unique This material is licensed under the Creative Commons License BY-NC-SA 4.0. 130
  • 131. 6.2. XML parsing to create a mechanism to (prepare) 6.1 Please refer to the HTTP traffic. Capture to create a sample program (coming soon) •How to Get •Eclipse project to incorporate training for skeleton Locations Capture answer folder android_training_webapi Chapter 6 XML parsing "XmlSample_skeleton01.zip ~ XmlSample_skeleton03.zip" This material is licensed under the Creative Commons License BY-NC-SA 4.0. 131
  • 132. 6.2. XML to parse • Skeleton Program XML parsing exercises to create a sample using DOM, SAX, XMLPullparser. Skeleton project has been implemented using the following functions: XmlSample_skeleton01: parsing Unimplemented XmlSample_skeleton02: DOM parsing process has been implemented XmlSample_skeleton03: DOM and SAX parsing process is implemented Each project is described in the task of implementing the exercise. ※ For the confirmation of the task, Please refer to the "TODO: HTTP Makoto Tooru XXX " This material is licensed under the Creative Commons License BY-NC-SA 4.0. 132
  • 133. 6.2. XML to parse • Skeleton Program Resource definition information XmlSample_skeleton01 to XmlSample_skeleton03 Resources are defined in the following contents: View id (@ + id / id name) Text(@+string ) On click LinearLayout LinearLayout01 LinearLayout LinearLayout02 Button button_dom @string/dom onClickDOMButton Button button_sax @string/sax onClickSAXButton Button button_xmlpullpaser @string/xml_pullpaser onClickXMLPullpaserButton TextView text_result No No This material is licensed under the Creative Commons License BY-NC-SA 4.0. 133
  • 134. 6.2. XML to parse • Parsing XML Use the following XML document, DOM · SAX · XMLPullparser in XML Analysis <sample.xml> ※ sample.xml The following assets are stored in folders <?xml version="1.0" encoding="UTF-8"?> <feed> <entry> <id>hPzNl6NKAG0</id> <group> <description> Everything is included for better sliding. (Just playing only) </description> <thumbnail url="image/cat.jpg"></thumbnail> <title> Training a cat. </title> </group> </entry> </feed> This material is licensed under the Creative Commons License BY-NC-SA 4.0. 134
  • 135. 6.2. XML to create a mechanism to analyze (2) •From an XML document to get and analyze the following elements The acquired data set RowModel Tags Attributes Get value id No hPzNl6NKAG0 title No Training a cat. description No Everything is included for better sliding. thumbnail url image/cat.jpg This material is licensed under the Creative Commons License BY-NC-SA 4.0. 135
  • 136. 6.2. Parse XML • About RowModel •Data were analyzed by the XML held in RowModel •Xml file analysis, data obtained by video downloader •This is a simplified information •The following RowModel jp.oesf.xmldomsample.model •Is defined in the file "RowModel.java". •XML data document that defines the following member variable holds: Variable Get Data id <id> title <title> Summary <description> thumbnailImageURL <thumbnail url = "Get data"> This material is licensed under the Creative Commons License BY-NC-SA 4.0. 136
  • 137. 6.2. XML to parse •DOM (tree type) • XML DOM with the contents of the heap as a tree. • When parsing XML to hold the entire contents of memory after parsing, any element 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 easily implement. Okay Oso DOM This material is licensed under the Creative Commons License BY-NC-SA 4.0. Large memory consumption 137
  • 138. 6.2. XML is analyzed (DOM) Analysis of the XML DOM tree Element <feed> Description Tags Attributes <entry> <id> Video ID Value <group> <description> <thumbnail> <title> url Video Description Thumbnail Image The URL This material is licensed under the Creative Commons License BY-NC-SA 4.0. Title 138
  • 139. 6.2. XML is analyzed (DOM) • Parsing XML with DOM <Procedure> • Document object to retrieve XML data • DocumentBuilderFactory to create objects • Creates a DOM parser • Building parse XML into DOM tree • Get the root element of XML data • Follows the DOM tree to get the desired node • To obtain the data held by the nodes (tags and text data) This material is licensed under the Creative Commons License BY-NC-SA 4.0. 139
  • 140. 6.2. XML is analyzed (DOM) The following sample XML document parsing <?xml version="1.0" encoding="UTF-8"?> <root> <node1>Node Value</node1> </root> ※ The new line is not actually This material is licensed under the Creative Commons License BY-NC-SA 4.0. 140
  • 141. 6.2. XML is analyzed (DOM) Sample Code InputStream in = null; try { //Generate Dokyumentobirudafakutori DocumentBuilderFactory dbfactory = DocumentBuilderFactory .newInstance(); // Generate Dokyumentobiruda DocumentBuilder builder = dbfactory.newDocumentBuilder(); // get a stream of xml file in = getAssets().open("samplea.xml"); // To retrieve and parse the Document Object Document doc = builder.parse(in); // Gets the root element (tag name: root) Element root = doc.getDocumentElement(); // Get <node1> NodeList entryList = root.getElementsByTagName("node1"); // First get <node1> Element node1Element = (Element) entryList.item(0); // Get the value of <node1> String nodevalue = node1Element.getFirstChild().getNodeValue(); // Display values Log.v(TAG, nodevalue); } catch (Exception e) { This material is licensed under the Creative Commons License BY-NC-SA 4.0. 141
  • 142. 6.2. XML is analyzed (DOM) • Creating a Sample Program Completed chart Click This material is licensed under the Creative Commons License BY-NC-SA 4.0. 142
  • 143. 6.2. XML is analyzed (DOM) Creating a Sample Program <Procedure> 1. XmlHelper parseDom class that implements the following processing methods 1. Document object to retrieve XML data 2. Creates a DOM parser 3. Building parse XML into DOM tree 4. <id> <entry> to get the value in the tag, set the value to RowModel 5. The id RowModel is set to the value obtained 6. <thumbnail> set the Rowmodel value to the value retrievd from the “url” attribute. 1. Implementing Activity onClickDOMButton class 1. XmlHelper # parseDom shaping method to the data to obtain RowModel ※ instance member variable "xmlHelper" is defined in XmlHelper This material is licensed under the Creative 143 2. TextView to display Commons License BY-NC-SA 4.0. the analysis results
  • 144. 6.2. XML is analyzed (DOM) The answer to create a sample program XmlHelper.java public RowModel parseDom(Context context, String xml) { // RowModel row = new RowModel(); RowModel rowModel = new RowModel(); InputStream in = null; try { // Generate Dokyumentobirudafakutori DocumentBuilderFactory dbfactory = DocumentBuilderFactory .newInstance(); dbfactory.setNamespaceAware(true); // Generate Dokyumentobiruda DocumentBuilder builder = dbfactory.newDocumentBuilder(); // get a stream of xml file in = context.getAssets().open("sample.xml"); // To retrieve and parse the Document Object Document doc = builder.parse(in); // Gets the root element (tag name: feed) Element root = doc.getDocumentElement(); // Get <entry> NodeList entryList = root.getElementsByTagName("entry"); // First get <entry> Element entryElement = (Element) entryList.item(0); This material is licensed under the Creative Commons License BY-NC-SA 4.0. 144
  • 145. 6.2. XML is analyzed (DOM) The answer to create a sample program Continued XmlHelper.java /* <id> processing * / / / Get <id> obtained from <entry> Element idElement = (Element) entryElement.getFirstChild(); / / get the Text data obtained from <id> String id = idElement.getFirstChild().getNodeValue(); // RowModel value set rowModel.setId(id); /* <description> processing * / // Get <description> <entry> obtained from NodeList desriptionList = entryElement.getElementsByTagName("description"); // Node information from text. String summary = desriptionList.item(0).getFirstChild().getNodeValue(); // Cut off after 20 characters. if (summary != null && 0 < summary.length()) { if (20 < summary.length()) { summary = summary.substring(0, 20); } } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 145
  • 146. 6.2. XML is analyzed (DOM) The answer to create a sample program Continued XmlHelper.java // Node information from text. String summary = desriptionList.item(0).getFirstChild().getNodeValue(); // Cut off after 20 characters. if (summary != null && 0 < summary.length()) { if (20 < summary.length()) { summary = summary.substring(0, 20); } } // RowModel value set rowModel.setSummary(summary); /* <thumbnail> Processing * / // <thumbnail> Get NodeList thumbnailList = entryElement.getElementsByTagName("thumbnail"); This material is licensed under the Creative Commons License BY-NC-SA 4.0. 146
  • 147. 6.2. XML is analyzed (DOM) The answer to create a sample program Continued XmlHelper.java // First get <thumbnail> Element thumbnailElement = (Element) thumbnailList.item(0); // <thumbnail> the "url" attribute gets the value of String thumbnail = thumbnailElement.getAttribute("url"); // RowModel value set rowModel.setThumbnailImageURL(thumbnail); /* <title> processing * / // <title> Get NodeList titleList = entryElement.getElementsByTagName("title"); // Node information from text String title = titleList.item(0).getFirstChild().getNodeValue(); // RowModel value set rowModel.setTitle(title); This material is licensed under the Creative Commons License BY-NC-SA 4.0. 147
  • 148. 6.2. XML is analyzed (DOM) The answer to create a sample program XmlHelper.java public void onClickDOMButton(View v) { RowModel rowModel = null; // RowModel XmlHelper # parseDom get a call rowModel = this.xmlHelper.parseDom(this, this.xml); if (rowModel == null) { this.textResult.setText ("Failed to retrieve data. ") } else { // TextView to display the contents of rowModel this.textResult.setText(rowModel.toString()); } } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 148
  • 149. 6.2. create a mechanism to analyze XML(1) Parsing XML Data •WebAPI is retrieved using the HTTP data communication with the following <feed xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:gd="http://schemas.google.com/g/2005" xmlns:yt="http://gdata.youtube.com/schemas/2007"> : - <entry> <id>http://gdata.youtube.com/feeds/api/videos/fzzjgBAaWZw</id> : <media:group> <media:description type="plain">ブログ・モア*モアレmoire.lowdope.com</media:description> : <media:thumbnail url="http://i.ytimg.com/vi/fzzjgBAaWZw/2.jpg" height="90" width="120" time="00:00:37" /> : <media:title type="plain">だるまさんが転んにゃ - Stalking Cat -</media:title> : </media:group> </entry> </feed> This material is licensed under the Creative Commons License BY-NC-SA 4.0. 149
  • 150. 6.2. create a mechanism to analyze XML(2) •Exercise: making DOM, XMLPullParser, SAX parsing process by using them. •Retrieved from the XML data, analyzing the following elements into Entity. –id –description –thumbnail url –title This material is licensed under the Creative Commons License BY-NC-SA 4.0. 150
  • 151. 6.2. XML is analyzed (DOM) • Parsing XML with DOM <Procedure> • Document object to retrieve XML data • DocumentBuilderFactory to create objects • Creates a DOM parser • DOM tree is built to amend the XML • Get the root element of XML data • Follows the DOM tree to get the desired node • To obtain the data held by the nodes (tags and text data) . This material is licensed under the Creative Commons License BY-NC-SA 4.0. 151
  • 152. 6.2. XML is analyzed (DOM) •Parsing XML with DOM public List<RowModel> parseTableModelDom(final String data) throws IllegalStateException, IOException, ParserConfigurationException, SAXException { final List<RowModel> result = new ArrayList<RowModel>(MAX_RESULTS); // Generate Dokyumentobirudafakutori DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance(); dbfactory.setNamespaceAware(true); // Generate Dokyumentobiruda DocumentBuilder builder = dbfactory.newDocumentBuilder(); // To retrieve and parse the Document Object InputSource is = new InputSource(new StringReader(data)); Document doc = builder.parse(is); // Gets the root element (tag name: message) Element root = doc.getDocumentElement(); This material is licensed under the Creative Commons License BY-NC-SA 4.0. 152
  • 153. 6.2. XML is analyzed (DOM) •Parsing XML with DOM (cont'd) NodeList entryList = root.getElementsByTagName("entry"); for (int i = 0; i < entryList.getLength(); i++) { RowModel rowModel = new RowModel(); Element entryElement = (Element) entryList.item(i); Element idElement = (Element) entryElement.getFirstChild(); String url = idElement.getFirstChild().getNodeValue(); rowModel.setUrl(url); NodeList desriptionList = entryElement.getElementsByTagNameNS( "http://search.yahoo.com/mrss/", "description"); String summary = desriptionList.item(0).getFirstChild() .getNodeValue(); if (summary != null && 0 < summary.length()) { if (20 < summary.length()) { summary = summary.substring(0, 20); } } rowModel.setSummary(summary); NodeList thumbnailList = entryElement.getElementsByTagNameNS( "http://search.yahoo.com/mrss/", "thumbnail"); Element thumbnailElement = (Element) thumbnailList.item(0); String thumbnail = thumbnailElement.getAttribute("url"); rowModel.setThumbnailImageURL(thumbnail); NodeList titleList = entryElement.getElementsByTagNameNS( "http://search.yahoo.com/mrss/", "title"); String title = titleList.item(0).getFirstChild().getNodeValue(); rowModel.setTitle(title); result.add(rowModel); } return result; } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 153
  • 154. 6.2. SAX (repetition) •SAX (event-driven) • Such images that invoke the application parsing the parser. • Iki read XML documents from his head, and start and end tags • To strike, call the application of a fixed callback routine. • By the application of the XML • To make DOM not to read the document control • Memory consumption is less than the DOM. • Android is the conventional method of using the SAX, • On SAX there are ways to use a wrapper. Er is soooo ♪ !!!!! My more ・ ・ ・ easy to use mon SAX DOM This material is licensed under the Creative Commons License BY-NC-SA 4.0. 154
  • 155. 6.2. XML is analyzed (SAX) Parsing XML with SAX <Procedure> • Creating a SAX event handler class to receive callbacks from the parser • To get SAX parser, create Pasafakutori SAX, • Set the SAX event handler class created by a parser • Start parsing an XML to be called back by an event handler created when the event occurred This material is licensed under the Creative Commons License BY-NC-SA 4.0. 155
  • 156. 6.2. XML is analyzed (SAX) • • DefaultHandler to create a subclass that inherits the class Implement a process corresponding to each event – Creating a SAX event handler class to receive callbacks from the parser at the start of implementation of the event 1. Tag 2. 3. Implementation of events at the end tag Implementation of events in a text element This material is licensed under the Creative Commons License BY-NC-SA 4.0. 156
  • 157. 6.2. XML is analyzed (SAX) <method to override> Return value Method Name Description void startElement(String uri, String localName, String qName, Attributes attributes) Receive notification of the start of an element Parameters uri - namespace URI localName - The local name prefix qualifier qName - qualified name with a prefix attributes - attributes that were added to the element void endElement(String uri, String localName, String qName) Receive notification of the end of an element Parameters uri - namespace URI localName - The local name prefix qualifier qName - qualified name with a prefix void void characters(char[] ch, int start, int length) Receives notification of character data inside an element Parameters ch - the character start - starting position in the character array length - number of characters from a character array to be used This material is licensed under the Creative Commons License BY-NC-SA 4.0. 157
  • 158. 6.2. XML is analyzed (SAX) • Sample Code The following sample XML document parsing <?xml version="1.0" encoding="UTF-8"?> <root> <node1>Node Value</node1> </root> ※ The actual document does not break space This material is licensed under the Creative Commons License BY-NC-SA 4.0. 158
  • 159. 6.2. XML is analyzed (SAX) Sample Code / / get the stream to be parsed InputSource is = new InputSource (new StringReader (xml)); / / Create a parser Factory SAXParserFactory saxParaser = SAXParserFactory.newInstance (); try { / * Get the parser * / SAXParser sp = saxParaser.newSAXParser (); / * Create an event handler * / SaxHandler sh = new SaxHandler (); / * pass input data and event handlers to the event handler * / sp.parse (is, sh); } Catch (Exception e) { e.printStackTrace (); } This material is licensed under the Creative Commons License BY-NC-SA 4.0. Create SAX parser Parsing XML 159
  • 160. 6.2. XML is analyzed (SAX) Sample Code class SaxHandler extends DefaultHandler { / / Tag start flag boolean isNode1; @ Override public void startElement (String uri, String localName, String qName, Attributes attributes) throws SAXException { if ("node1". equals (localName)) { / / Node1 start tag isNode1 = true; } } Tag at the start of treatment @ Override public void endElement (String uri, String localName, String qName) throws SAXException { if ("node1". equals (localName)) { / / Node1 start tag isNode1 = false; } } @ Override public void characters (char [] ch, int start, int length) throws SAXException { / / Node1 tag if it is started, log text if (isNode1) { String nodevalue = new String (ch, start, length); Log.v (TAG, nodevalue); } } } Tag at the end of treatment Text Event Processing This material is licensed under the Creative Commons License BY-NC-SA 4.0. 160
  • 161. 6.2. XML is analyzed (SAX) • Creating a Sample Program Completed chart Click This material is licensed under the Creative Commons License BY-NC-SA 4.0. 161
  • 162. 6.2. XML is analyzed (SAX) Creating a Sample Program <Procedure> XmlHelper DefaultHandler class to create a class that inherits the subclass startElement, characters, endElement methods are implemented XmlHelper parseSax class that implements the following processing methods Create a SAX parser object XML parsing Hazime Hiraku Implementing Activity onClickSAXButton class XmlHelper # parseSax shaping method to the data to obtain RowModel ※ XmlHelper instance member variable "xmlHelper" is defined in TextView to display the analysis results This material is licensed under the Creative Commons License BY-NC-SA 4.0. 162
  • 163. 6.2. XML is analyzed (SAX) <XmlHelper.java> • Answer public RowModel parseSax (Context context, String xml) { / / get the stream to be parsed InputSource is = new InputSource (new StringReader (xml)); / / Create a parser Factory SAXParserFactory saxParaser = SAXParserFactory.newInstance (); try { / / Get the parser SAXParser sp = saxParaser.newSAXParser (); / / Create an event handler SaxHandler sh = new SaxHandler (); / / pass the input data and an event handler to the event handler sp.parse (is, sh); return sh.rowModel; } Catch (Exception e) { e.printStackTrace (); } return null; } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 163
  • 164. 6.2. XML is analyzed (SAX) • Answer <XmlHelper.java( More )> class SaxHandler extends DefaultHandler { RowModel rowModel = new RowModel (); / / Tag start flag boolean isEntry; boolean isId = false; boolean isSummary = false; boolean isTitle = false; boolean isThumbnail = false; String id = null; String summary = null; String thumbnail = null; String title = null; This material is licensed under the Creative Commons License BY-NC-SA 4.0. 164
  • 165. 6.2. XML is analyzed (SAX) <XmlHelper.java(More)> • Answer @ Override public void startElement (String uri, String localName, String qName, Attributes attributes) throws SAXException { / / Entry to true if the tag is isEntry if ("description". equals (localName)) { / / Entry tag begins isEntry = true; } / / Entry in the tag determines if if (isEntry) { if ("id". equals (localName)) { isId = true; } if ("description". equals (localName)) { isSummary = true; } if (! isThumbnail & & "thumbnail". equals (localName)) { / / Thumnail to get the url attribute of the tag thumbnail = attributes.getValue ("url"); isThumbnail = true; } if ("title". equals (localName)) { isTitle = true; } } } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 165
  • 166. 6.2. XML is analyzed (SAX) • Answer <XmlHelper.java( More )> @ Override public void endElement (String uri, String localName, String qName) throws SAXException { if ("entry". equals (localName)) { / / RowModel to set the value to rowModel.setId (id); rowModel.setSummary (summary); rowModel.setThumbnailImageURL (thumbnail); rowModel.setTitle (title); / / clear values id = null; summary = null; thumbnail = null; title = null; isThumbnail = false; isEntry = false; } } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 166
  • 167. 6.2. XML is analyzed (SAX) • Answer <XmlHelper.java( More )> @ Override public void characters (char [] ch, int start, int length) throws SAXException { if (isEntry) { if (isId) { / / Id to get id = new String (ch, start, length); isId = false; } if (isSummary) { / / Description to obtain summary = new String (ch, start, length); if (summary! = null & & 0 <summary.length ()) { if (20 <length) { summary = summary.substring (0, 20); } } isSummary = false; } if (isTitle) { / / Title to get title = new String (ch, start, length); isTitle = false; } } } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 167
  • 168. 6.2. XML is analyzed (SAX) • Answer <XmlSample.java> public void onClickSAXButton (View v) { RowModel rowModel = null; / / XmlHelper # parseSax RowModel get a call rowModel = this.xmlHelper.parseDom (this, this.xml); if (rowModel == null) { this.textResult.setText ("Failed to retrieve data. ") } else { / / TextView to display the contents of rowModel this.textResult.setText (rowModel.toString ()); } } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 168
  • 169. 6.2. XMLPullParser (repetition) • XMLPullParser (Pull Type) • SAX JAVA by what shall have the same functionality, so Android will not support the same functionality that is available to XMLPullParser. • SAX as an XML document read from the head, performed by the application of the load control, and can retrieve information from the parser, if necessary. • To make an application from the control, it is possible to stop the parsing early that can significantly reduce the time required to parse. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 169
  • 170. 6.2. XML is analyzed (XMLPullpaser) • Parsing XML with XMLPullpaser <Procedure> • Create an XmlPullParser object • Passing a string parser to parse • XML to retrieve one event analysis This material is licensed under the Creative Commons License BY-NC-SA 4.0. 170
  • 171. 6.2. XML is analyzed (XMLPullpaser) • Sample Code The following sample XML document parsing <?xml version="1.0" encoding="UTF-8"?> <root> <node1>Node Value</node1> </root> ※ The actual document does not break space This material is licensed under the Creative Commons License BY-NC-SA 4.0. 171
  • 172. 6.2. XML is analyzed (XMLPullpaser) Sample Code InputStream in = null; try { / / get the stream to be parsed is = getAssets (). open ("samplea.xml"); / / XmlPullParser XmlPullParser define final XmlPullParser parser = Xml.newPullParser (); / / XmlPullParser pass a stream to parse the string parser.setInput (new InputStreamReader (is)); parser.next (); / / root tag parser.next (); / / node1 tags / / XmlPullParser to obtain the name of the tag String tag = parser.getName (); / / XmlPullParser tag name is "node1", then if ("node1". equals (tag)) { parser.next (); String nodevalue = parser.getText (); Log.v (TAG, nodevalue); } } Catch (Exception e) { Create parser XMLPullParser Passing a string parser to parse XML parsing events to get one at a time This material is licensed under the Creative Commons License BY-NC-SA 4.0. 172
  • 173. 6.2. XML is analyzed (XMLPullpaser) • Creating a Sample Program Completed chart Click This material is licensed under the Creative Commons License BY-NC-SA 4.0. 173
  • 174. 6.2. XML is analyzed (XMLPullpaser) Creating a Sample Program <Procedure> XmlHelper parseXmlPullparser class method to implement the following actions: Define XmlPullParser Passing a stream of string to parse While processing one by one statement. <id> <entry> to get the value in the tag, set the value to RowModel <thumbnail> set the value to RowModel that retrived from the “url” attribute. Implementing Activity onClickXMLPullparserButton class XmlHelper # parseXmlPullparser shaping method to the data to obtain RowModel ※ XmlHelper instance member variable "xmlHelper" is defined in TextView to display the analysis results This material is licensed under the Creative Commons License BY-NC-SA 4.0. 174
  • 175. 6.2. XML is analyzed (XMLPullpaser) • Answer <XmlHelper.java> public RowModel parseXmlPullparser (context, String xml) { RowModel rowModel = null; InputStream is = null; try { / / Get the stream to be parsed is = context.getAssets (). open ("sample.xml"); / / XmlPullParser define final XmlPullParser parser = Xml.newPullParser (); / / Pass the string to parse a stream of parser.setInput (new InputStreamReader (is)); int eventType; / / XmlPullParser get the parsed hierarchy final int depth = parser.getDepth (); / / XmlPullParser Perth exit conditions / / While processing the statements one at a time while (((eventType = parser.next ())! = XmlPullParser.END_DOCUMENT | | parser.getDepth ()> depth)) { / / XmlPullParser eventType determine if a start tag if (eventType == XmlPullParser.START_TAG) { / / XmlPullParser to obtain the name of the tag String tag = parser.getName (); / / XmlPullParser tag name is "entry" if, parseToRowModel call if ("entry". equals (tag)) { rowModel = parseToRowModel (parser); break; } } } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 175
  • 176. 6.2. XML is analyzed (XMLPullpaser) • Answer <XmlHelper.java> ( More ) } catch (Exception e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } return rowModel; } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 176
  • 177. 6.2. XML is analyzed (XMLPullpaser) • Answer <XmlHelper.java> (More) private RowModel parseToRowModel (XmlPullParser parser) throws XmlPullParserException, IOException { RowModel rowModel = new RowModel (); int eventType; String tag = null; / / Get the hierarchy to Perth final int depth = parser.getDepth (); / / End condition Perth while (((eventType = parser.next ())! = XmlPullParser.END_DOCUMENT | | parser.getDepth ()> depth)) { / / EventType determine if a start tag if (eventType == XmlPullParser.START_TAG) { tag = parser.getName (); / / <entry> <id> To get the value in the tag, RowModel set the value to if ("id". equals (tag)) { / / Move next. parser.next (); / / Parser to get information from the text, rowModel set to the URL. rowModel.setId (parser.getText ()); } Else if ("description". Equals (tag)) { / / Move next. parser.next (); / / Parser to get information from the text. String summary = parser.getText (); / / 20 characters, so cut fit. if (summary! = null & & 0 <summary.length ()) { if (20 <summary.length ()) { summary = summary.substring (0, 20); } } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 177