Sie sind auf Seite 1von 94

Anroid Application Development (Series II)

3-5hb November 2014

Android Application
Development
Series II

Review

ASMATT (suki1207@uum.edu.my)

Anroid Application Development (Series II)

3-5hb November 2014

Create Android Project


Project File >> New >> Project >> Android App
Project
Enter Application Name, Project Name & Package
Name;

ASMATT (suki1207@uum.edu.my)

Anroid Application Development (Series II)

3-5hb November 2014

Android App Development Steps

Creating Your Emulator


Create your emulator
Eclipse: Window =>
Android Virtual Device
Manager, Choose New

ASMATT (suki1207@uum.edu.my)

Anroid Application Development (Series II)

3-5hb November 2014

Before Execute Your App


1) Select target API
(Choose Android API 19)
2) Select Device or Screen
size (choose 5.1).

3) Give a name for this


target. No space allowed.

4) Choose No skin
5) Click ok. Accept other
defaults. Click this button to
create the emulator.

Run your app


1) Expand your
project (src)
3) Click run
button

2) Click
here

4) Choose
this

Emulator will take some


time to be loaded

ASMATT (suki1207@uum.edu.my)

Anroid Application Development (Series II)

3-5hb November 2014

ANDROID CODING

Button & onClick Handler


Open activity_main.xml (your layout)

ASMATT (suki1207@uum.edu.my)

Anroid Application Development (Series II)

3-5hb November 2014

Add an EditText, a Button & a TextView

Run your app

ASMATT (suki1207@uum.edu.my)

Anroid Application Development (Series II)

3-5hb November 2014

Add onClick handler


Open main.xml
Add a new line (as in Line 21):
17. <Button
18.
19.
20.

android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

21.

android:onClick="handleClick"

22.

android:text="Button" />
You can give
any name

Add handleClick method


Open myFirstButtonHandlerActivity.java
Add method handleClick()

Between the
last (two) }
A new method (beside
onCreate) to handle
onClick event

ASMATT (suki1207@uum.edu.my)

Anroid Application Development (Series II)

3-5hb November 2014

myFirstButtonHandlerActivity.java
1.

package com.Suki.ButtonHandler;

2.
3.
4.
5.
6.

import
import
import
import
import

android.app.Activity;
android.os.Bundle;
android.view.View;
android.widget.EditText;
android.widget.TextView;

7. public class MyFirstButtonHandlerActivity extends Activity {


/** Called when the activity is first created. */
8.
9.
@Override
10.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
11.
12.
setContentView(R.layout.main);
13.
}
14.

Should be similar
with your onClick
button in the
activity_main.xml

15.
16.
17.
18.
19.

public void handleClick(View v) {


// get a reference to editText1 from main.xml
EditText widget_editText1 = (EditText) findViewById(R.id.editText1);
// get the text (input)
String inputText = widget_editText1.getText().toString();

20.
21.
22.
23.
24.

// get a reference to textView1 from main.xml


TextView widget_textView1 = (TextView) findViewById(R.id.textView1);
// put a message (from input) to the widget
widget_textView1.setText("Your Name: " + inputText);
}

25. }

Manipulate Numbers
(Create a new project HandleNumber)

ASMATT (suki1207@uum.edu.my)

Anroid Application Development (Series II)

3-5hb November 2014

Button onClick Handler for


HandleNumberActivity.java
1.
2.
3.

public void handleNom(View v) {


EditText inputTeks = (EditText) findViewById(R.id.editText1);
String teks = inputTeks.getText().toString();
float celsius = Float.parseFloat(teks);
float faren = ((celsius * 9) / 5) + 32;

4.
5.
6.
7.
8.
9.
10.

TextView label1 = (TextView) findViewById(R.id.textView1);


label1.setText(celsius + " Celsius is equal to " +
faren + " Farenheit.");
}

We want to produce/output something like this,


38.0 Celsius is equal to 100.4 Farenheit.

Exercise:
Power 3 Calculator

ASMATT (suki1207@uum.edu.my)

Anroid Application Development (Series II)

3-5hb November 2014

Try This:
Multiplication Calculator

Exercise: Multiplication Calculator


1. public void Calc(View v) {
2.
EditText et1 = (EditText)
findViewById(R.id.editText1);
3.
String nomStr1 = et1.getText().toString();
4.
int nomInt1 = Integer.parseInt(nomStr1);

6.
7.

EditText et2 = (EditText)


findViewById(R.id.editText2);
String nomStr2 = et2.getText().toString();
int nomInt2 = Integer.parseInt(nomStr2);

8.

int hasil = nomInt1*nomInt2;

9.

TextView tv = (TextView)
findViewById(R.id.textView2);
tv.setText("Result is: " + hasil);

5.

10.
11. }

ASMATT (suki1207@uum.edu.my)

10

Anroid Application Development (Series II)

3-5hb November 2014

Exercise:
Basic Calculator

DUPLICATING & IMPORTING


AN ANDROID PROJECT

ASMATT (suki1207@uum.edu.my)

11

Anroid Application Development (Series II)

3-5hb November 2014

Duplicate an Android Project


Simply Copy &
Paste (in Eclipse)
Highlight the
project
Ctrl-C (Copy)
Ctrl-V (Paste)
Enter a new
project name

Copy a project from Another Source


Eclipse: File -> Import
Choose Android ->
Existing Android
Code Into Workspace
Next -> Browse ->
locate the project
OK -> tick Copy
project into
workspace -> Finish

ASMATT (suki1207@uum.edu.my)

12

Anroid Application Development (Series II)

3-5hb November 2014

Using Basic Selection

The if Statement Syntax

The

if statement has the following syntax:


The condition must be a
boolean expression. It must
evaluate to either true or false.

if is a Java
reserved word

if ( condition ) {
statement(s);
}

If the condition is true, the statement(s) is executed.


If it is false, the statement(s) is skipped.

26

ASMATT (suki1207@uum.edu.my)

13

Anroid Application Development (Series II)

3-5hb November 2014

Relational Operators

A condition often uses one of Java's equality operators or


relational operators, which all return boolean results:
==
!=
<
>
<=
>=

equal to
not equal to
less than
greater than
less than or equal to
greater than or equal to

27

Try This: Odd or Even Number

ASMATT (suki1207@uum.edu.my)

14

Anroid Application Development (Series II)

3-5hb November 2014

Try This: Odd or Even Number


1. EditText et = (EditText) findViewById(R.id.editText1);
2. String nomStr = et.getText().toString();
3. int nom = Integer.parseInt(nomStr);

4.
5.
6.
7.
8.
9.

String hasil = "Not known yet";


if (nom%2 == 0) { //or (nom/2*2 == nom)
hasil = "EVEN";
} else {
hasil = "ODD";
}

10. TextView tv = (TextView) findViewById(R.id.textView2);


11. tv.setText("The number is " + hasil);

Exercise: Pass or Fail?


Request a mark value from user
Determine either the mark is pass or fail.
50 & above is considered pass.

ASMATT (suki1207@uum.edu.my)

15

Anroid Application Development (Series II)

3-5hb November 2014

Tips: Background Color & Images

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/dcoped"
android:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
 <Button
android:textColor="#FF0000"

android:id="@+id/button1"
android:background="#FFCC00"

android:layout_width="wrap_content"
android:text="Enter your Name:" />

<EditText

android:id="@+id/editText1"

android:layout_width="match_parent"

android:layout_height="wrap_content"
android:ems="10" >

<requestFocus />
</EditText>


android:layout_height="wrap_content"
android:background="#FFCC00"
android:onClick="handleClick"
android:text="

Button

" />

Http://html-color-codes.info

Local & Remote

VIDEO

ASMATT (suki1207@uum.edu.my)

16

Anroid Application Development (Series II)

3-5hb November 2014

Remote Video
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String url = "http://download.wavetlan.com/SVV/Media/HTTP/H264/ Talkinghead_Media/H264_test2_Talkinghead_mp4_480x320.mp4";
Uri uri = Uri.parse(url);
VideoView video = (VideoView) findViewById(R.id.videoView1);
final MediaController ctlr = new MediaController(this);
video.setMediaController(ctlr);
video.setVideoURI(uri);
video.requestFocus();
video.setOnPreparedListener(new OnPreparedListener() {
ProgressBar pb=(ProgressBar) findViewById(R.id.progressBar1);
public void onPrepared(MediaPlayer mp) {
pb. setVisibility(View.GONE); // Close the progress bar and play the video
ctlr.setAnchorView(video);
video.start();
}
});
}

<uses-permission android:name="android.permission.INTERNET"/>

ASMATT (suki1207@uum.edu.my)

17

Anroid Application Development (Series II)

3-5hb November 2014

Remote Video
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String url = " https://www.dropbox.com/s/xj3y0ofg7a3dqln/frozen_playice.mp4";
Uri uri = Uri.parse(url);
VideoView video = (VideoView) findViewById(R.id.videoView1);
final MediaController ctlr = new MediaController(this);
video.setMediaController(ctlr);
video.setVideoURI(uri);
video.requestFocus();
video.setOnPreparedListener(new OnPreparedListener() {
ProgressBar pb=(ProgressBar) findViewById(R.id.progressBar1);
public void onPrepared(MediaPlayer mp) {
pb. setVisibility(View.GONE); // Close the progress bar and play the video
ctlr.setAnchorView(video);
video.start();
}
});
}

<uses-permission android:name="android.permission.INTERNET"/>

Live TV
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String url = "http://dl.dropboxusercontent.com/u/59242226/play/smarttv/channel/tvtiga.m3u8";
Uri uri = Uri.parse(url);
VideoView video = (VideoView) findViewById(R.id.videoView1);
final MediaController ctlr = new MediaController(this);
video.setMediaController(ctlr);
video.setVideoURI(uri);
video.requestFocus();
video.setOnPreparedListener(new OnPreparedListener() {
ProgressBar pb=(ProgressBar) findViewById(R.id.progressBar1);
public void onPrepared(MediaPlayer mp) {
pb. setVisibility(View.GONE); // Close the progress bar and play the video
ctlr.setAnchorView(video);
video.start();
}
});
}

<uses-permission android:name="android.permission.INTERNET"/>

ASMATT (suki1207@uum.edu.my)

18

Anroid Application Development (Series II)

3-5hb November 2014

Local Video
1. protected void onCreate(Bundle savedInstanceState) {
2.
super.onCreate(savedInstanceState);
3.
setContentView(R.layout.activity_main);
4.

Uri uri = Uri.parse("android.resource://"+


getApplication().getPackageName()
+"/"+R.raw.frozen_playice);

5.

VideoView video = (VideoView)


findViewById(R.id.videoView1);

6.
7.
8.
9.
10. }

MediaController ctlr = new MediaController(this);


video.setMediaController(ctlr);
video.setVideoURI(uri);
video.start();

PLAY AN AUDIO
1. public class MainActivity extends Activity {
2.
private MediaPlayer mp;
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = new MediaPlayer();
}
Media Player source.
public void playSound(View v){
mp = MediaPlayer.create(MainActivity.this,
R.raw.lagu);
mp.start();
}

ASMATT (suki1207@uum.edu.my)

19

Anroid Application Development (Series II)

3-5hb November 2014

Android is Interesting!

TALKING ANDROID

Try This: Text-to-Speech


1. public class MainActivity extends Activity
implements OnInitListener {
2.
TextToSpeech talker;
3.
@Override
4.
5.
protected void onCreate(Bundle
savedInstanceState) {
6.
super.onCreate(savedInstanceState);
7.
setContentView(R.layout.activity_main);
8.
talker = new TextToSpeech(this, this);
9.
}

ASMATT (suki1207@uum.edu.my)

20

Anroid Application Development (Series II)

3-5hb November 2014

Try This: Text-to-Speech


10. @Override
11. public void onInit(int arg0) {
12.
// TODO Auto-generated method stub
13.
talker.setLanguage(Locale.UK);
14.
talker.setSpeechRate((float)kadar);
15.
talker.speak(teks,
TextToSpeech.QUEUE_FLUSH, null);
16.
17. }

TOUCH HANDLING

ASMATT (suki1207@uum.edu.my)

21

Anroid Application Development (Series II)

3-5hb November 2014

Try This: Android Life-Cycle App


We can implement/overrides all built-in
methods using the Eclipse.
Eclipse: Source -> Override/Implement
methods
Tick all related methods

Introducing TOAST WIDGET

Allows us to send brief messages to our end users.


Toast.makeText(this, Our Text", Toast.LENGTH_SHORT).show();

Three parameters:
The activity that is running this Toast alert
What the message should be
How long to show the Toast pop-up

import android.widget.Toast;

ASMATT (suki1207@uum.edu.my)

22

Anroid Application Development (Series II)

3-5hb November 2014

Try This: Touch, Move & Lift Event

Try This: Touch Event


1. @Override
2. public boolean onTouchEvent(MotionEvent event) {
3.
int detectTouch = event.getAction();
4.
if (detectTouch==MotionEvent.ACTION_DOWN) {
5.
Toast.makeText(getApplicationContext(),
"...is moving", Toast.LENGTH_SHORT).show();
6.
}
7.
return true;
8. }

ASMATT (suki1207@uum.edu.my)

23

Anroid Application Development (Series II)

3-5hb November 2014

Try This: Detecting Swipe Event


1. public class GestureActivity extends Activity {
2.
float x1, x2;
3.
float y1, y2;
4.
5.
6.
7.
8.

@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gesture);
}

Try This: Detecting Swipe Event


9. @Override
10. public boolean onTouchEvent(MotionEvent event) {
11.
int action = event.getAction();
12.
switch (action) {
13.
case MotionEvent.ACTION_DOWN:
14.
x1 = event.getX();
15.
y1 = event.getY();
16.
break;
17.
18.
19.

case MotionEvent.ACTION_UP:
x2 = event.getX();
y2 = event.getY();

ASMATT (suki1207@uum.edu.my)

24

Anroid Application Development (Series II)

3-5hb November 2014

Try This: Detecting Swipe Event


20. // if left to right sweep event on screen
21. if (x1 < x2) { //or better (x2-x1>50)
22.
Toast.makeText(this, "Left to Right Swap Performed",
Toast.LENGTH_LONG).show();
23. }
24. // if right to left sweep event on screen
25. if (x1 > x2) { //or (x1-x2 > 50)
26.
Toast.makeText(this, "Right to Left Swap Performed",
Toast.LENGTH_LONG).show();
27. }
28. // if UP to Down sweep event on screen
29. if (y1 < y2) {
30.
Toast.makeText(this, "UP to Down Swap Performed",
Toast.LENGTH_LONG).show();
31. }

Try This: Detecting Swipe Event


32.
33.
34.

// if Down to UP sweep event on screen


if (y1 > y2) {
Toast.makeText(this,
"Down to UP Swap Performed",
Toast.LENGTH_LONG).show();
}

35.
36.
37.

break; // for MOVE_UP event


}

38. return true;


39.}

ASMATT (suki1207@uum.edu.my)

25

Anroid Application Development (Series II)

3-5hb November 2014

Exercise
When a user performs this swipe , play a
song.
When a user performs this swipe , stop the
song.

OPEN ANOTHER LAYOUT

ASMATT (suki1207@uum.edu.my)

26

Anroid Application Development (Series II)

3-5hb November 2014

Open Another Layout


The easier way to move from one layout to
another layout is to use setContentView().

Try This: Open Another Layout

ASMATT (suki1207@uum.edu.my)

27

Anroid Application Development (Series II)

3-5hb November 2014

Try This: Open Another Layout


1. public class MainActivity extends Activity {
2.
3.
4.
5.
6.

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

7.
public void Open_Layout2(View v) {
8.
setContentView(R.layout.second_layout);
9.
}
10.}

Exercise: Open Another Layout


Try implements BACK
button (to return to the
main page).

ASMATT (suki1207@uum.edu.my)

28

Anroid Application Development (Series II)

3-5hb November 2014

Exercise: Open Another Layout


Sample Solution
1. public void Open_Layout2(View v) {
2. setContentView(R.layout.second_layout);
3. }
4. public void HandleBACK(View v) {
5. setContentView(R.layout.activity_main);
6. }

Exercise: Open Another Layout

ASMATT (suki1207@uum.edu.my)

29

Anroid Application Development (Series II)

3-5hb November 2014

Exercise: Open Another Layout


Sample Solution (for touch screen)
1. @Override
2. public boolean onTouchEvent(MotionEvent event) {
3.
// TODO Auto-generated method stub
4.
int detectTouch = event.getAction();
5.
if (detectTouch==MotionEvent.ACTION_DOWN) {
6.
setContentView(R.layout.second_layout);
7.
}
8.
return true;
9. }

ACTION BAR MENU

ASMATT (suki1207@uum.edu.my)

30

Anroid Application Development (Series II)

3-5hb November 2014

Try This: Create an Action Bar Menu

Try This: Create an Action Bar Menu


2 easy steps:
List of menu options can be prepared by
modifying main.xml (res -> menu).
Override the public boolean
onOptionsItemSelected(MenuItem item) {}

Start the project by choosing theme Holo


Light with Dark Action Bar

ASMATT (suki1207@uum.edu.my)

31

Anroid Application Development (Series II)

3-5hb November 2014

Try This: Create an Action Bar Menu

Try This: Create an Action Bar Menu


menu.xml: (copy & modify <item /> tag)
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.

<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.suki.mytaskbar.MainActivity" >
<item
android:id="@+id/main_acreen"
android:orderInCategory="100"
android:title="Paparan Utama"
app:showAsAction="never"/>
<item
android:id="@+id/layout2"
android:orderInCategory="100"
android:title="Buka Layout 2"
app:showAsAction="never"/>

ASMATT (suki1207@uum.edu.my)

32

Anroid Application Development (Series II)

3-5hb November 2014

Try This: Create an Action Bar Menu


15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.

<item

33.

</menu>

android:id="@+id/play_music"
android:icon="@drawable/ic_launcher"
android:orderInCategory="100"
android:title="Play Music"
app:showAsAction="never"/>
<item
android:id="@+id/stop_music"
android:icon="@drawable/ic_launcher"
android:orderInCategory="100"
android:title="Stop Music"
app:showAsAction="never"/>
<item
android:id="@+id/bantuan"
android:icon="@drawable/ic_launcher"
android:orderInCategory="100"
android:title="Bantuan"
app:showAsAction="never"/>

Try This: Create an Action Bar Menu


.java: (copy & modify if statement in method onOptionsItemSelected)
1. @Override
2. public boolean onOptionsItemSelected(MenuItem item) {
3. // Handle action bar item clicks here. The action bar
will
4. // automatically handle clicks on the Home/Up button,
so long
5. // as you specify a parent activity in
AndroidManifest.xml.
6.
int id = item.getItemId();
7.
if (id == R.id.main_acreen) {
8.
setContentView(R.layout.activity_main);
9.
}
10.
if (id == R.id.layout2) {
11.
setContentView(R.layout.activity_main2);
12.
}

ASMATT (suki1207@uum.edu.my)

33

Anroid Application Development (Series II)

3-5hb November 2014

Try This: Create an Action Bar Menu


.java: (copy & modify if statement in method onOptionsItemSelected)
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24. }

if (id == R.id.play_music) {
mp = MediaPlayer.create(getApplicationContext(),
R.raw.uum_song);
mp.start();
}
if (id == R.id.stop_music) {
mp.stop();
}
if (id == R.id.bantuan) {
setContentView(R.layout.screen_bantuan);
}
return super.onOptionsItemSelected(item);

DUPLICATING & IMPORTING


AN ANDROID PROJECT

ASMATT (suki1207@uum.edu.my)

34

Anroid Application Development (Series II)

3-5hb November 2014

Duplicate an Android Project


Simply Copy &
Paste (in Eclipse)
Highlight the
project
Ctrl-C (Copy)
Ctrl-V (Paste)
Enter a new
project name

Copy a project from Another Source


Eclipse: File -> Import
Choose Android ->
Existing Android
Code Into Workspace
Next -> Browse ->
locate the project
OK -> tick Copy
project into
workspace -> Finish

ASMATT (suki1207@uum.edu.my)

35

Anroid Application Development (Series II)

3-5hb November 2014

Download Internet Resource

Try This:

Download am Image

ASMATT (suki1207@uum.edu.my)

36

Anroid Application Development (Series II)

3-5hb November 2014

Start with Android 2.3.3

The layout

ASMATT (suki1207@uum.edu.my)

37

Anroid Application Development (Series II)

3-5hb November 2014

The coding
1.
2.
3.
4.
5.

public void HandleDownload(View v) {


String url = "http://crackberry.com/sites/crackberry.com/" +
"files/styles/large/public/topic_images/2013/ANDROID.png";
try {
Toast.makeText(getApplicationContext(), "downloading...",
Toast.LENGTH_LONG).show();
6.
Bitmap imgResult = BitmapFactory.decodeStream((InputStream)
7.
new URL(url).getContent());
8.
ImageView imgView = (ImageView) findViewById(R.id.imageView1);
9.
imgView.setImageBitmap(imgResult);
10.
Toast.makeText(getApplicationContext(), "is Displaying...",
Toast.LENGTH_LONG).show();
11.
} catch (Exception e) {}
12. }

*** Dont forget to set the Internet permission

The Result

ASMATT (suki1207@uum.edu.my)

38

Anroid Application Development (Series II)

3-5hb November 2014

Now run it on
Emulator API19

Try this: Download in


the Android Thread

ASMATT (suki1207@uum.edu.my)

39

Anroid Application Development (Series II)

3-5hb November 2014

Try this: Download in the Android Thread


1. public class MainActivity extends ActionBarActivity {
2.
final String url =
"http://crackberry.com/sites/crackberry.com/"+
"files/styles/large/public/topic_images/2013/ANDROID.png";
3.
4.
5.
6.
7.

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

8.

public void HandleDownload(View v) {

9.

new myDownloadThread().execute();

10.

Toast.makeText(getApplicationContext(), "is downloading...",


Toast.LENGTH_LONG).show();

11.

Try this: Download in the Android Thread


12. private class myDownloadThread extends
AsyncTask<Void, Void, Bitmap> {
13.
14.
15.
16.
17.
18.
19.
20.

@Override
protected Bitmap doInBackground(Void... arg0) {
Bitmap imgResult = null;
try {
imgResult =
BitmapFactory.decodeStream((InputStream) new
URL(url).getContent());
} catch (Exception e) {}
return imgResult;
}

ASMATT (suki1207@uum.edu.my)

40

Anroid Application Development (Series II)

3-5hb November 2014

Try this: Download in the Android Thread


21. protected void onPostExecute(Bitmap
result) {
22.

23.
24.

Toast.makeText(getApplicationContext(),
"is displaying...",
Toast.LENGTH_SHORT).show();
ImageView imgView = (ImageView)
findViewById(R.id.imageView1);
imgView.setImageBitmap(result);

25. }
26. }
27.}

Thread/AsynTask

(2014)

ASMATT (suki1207@uum.edu.my)

41

Anroid Application Development (Series II)

3-5hb November 2014

Why use thread in Android?


When an Android application is first started, the runtime system
creates a single thread in which all application components will run
This thread is referred to as the main thread(also known as UI thread,
since it modifies the user interface and handles input events)
All code of an Android application (incl. additional components) runs in the
main thread and every statement is executed after each other
If you perform a long lasting operation(e.g accessing data from the Internet)
the application is blocked until the corresponding operation has finished.

Why use thread in Android?


NOTE!
Android enforces a worst case reaction time of applications.
If an activity does not react within 5 seconds to user input,
the Android system displays an Application not responding (ANR) dialog.
From this dialog the user can choose to stop the application

ASMATT (suki1207@uum.edu.my)

42

Anroid Application Development (Series II)

3-5hb November 2014

LOGO

Android AsynTask
Enables proper and easy use of the UI thread. This
class allows to perform background operations and
publish results on the UI thread without having to
manipulate threads and/or handlers.

Introduction
AsyncTask is a generic class, it uses 3 types:
AsyncTask<Params, Progress, Result>.
 Params the input. What you pass to the
AsyncTask
 Progress if you have any updates, passed to
onProgressUpdate()
 Result the output. What returns doInBackground()

Example:
private class MyTask extends AsyncTask<String, Integer, String> { }
OR
private class MyTask2 extends AsyncTask<Void, Integer, Void> { }

ASMATT (suki1207@uum.edu.my)

43

Anroid Application Development (Series II)

3-5hb November 2014

Introduction
The most common methods you will need to
implement (overrides) are these:
1. onPreExecute() called on the UI thread
before the thread starts running.
2. doInBackground(Params3) put all the code
you want the application to perform in
background.
3. onProgressUpdate() - called when you invoke
publishProgress() in the doInBackground().
4. onPostExecute(Result) called after the
background thread finishes.

Example

Hello World! Become


Downloading5
Then progressing
values will appear
Final msg, All Done!

ASMATT (suki1207@uum.edu.my)

44

Anroid Application Development (Series II)

3-5hb November 2014

Example
1.
2.

public class MainActivity extends Activity {


TextView tv;

3.
4.
5.
6.
7.
8.

@Override
public void onCreate(Bundle savedInstanceState) {
Super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
}

9. public void handleAsynTask(View v) {


10.
// Starting the task. Pass an url as the parameter.
11.
new MyTask().execute("http://ahmadsuki.blogspot.com");
12. }
1st param input for
AsynTask
AsynTask class. Leave it
class
blank if first param Void

Example
13.

private class MyTask extends AsyncTask<String, Integer, String> {

14.

@Override

15.
16.
17.
18.

protected void onPreExecute() {

19.

@Override

20.
21.

protected String doInBackground(String... params) {

super.onPreExecute();
tv.setText("Downloading...");
}

String url = params[0];

22.
23.
24.
25.
26.
27.
28.

// Dummy code
for (int i = 0; i <= 100; i += 5) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
Return

publishProgress(i);

29.
30.
31.
32.

Array
type

Return to 3rd param


of the AsynTask class

to 2nd param of
the AsynTask class

return "All Done!";


}

ASMATT (suki1207@uum.edu.my)

45

Anroid Application Development (Series II)

3-5hb November 2014

Example

Input from 2nd param


of the AsynTask cls

33.
34.
35.
36.
37.

@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
tv.setText("Progress Value: " + values[0]);
}

38.
39.
40.
41.
42.

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tv.setText(result);
Input from 3rd param
}
of the AsynTask cls

43.

44.}

Summary
1. public void handleAsynTask(View v) {
2.
new MyTask().execute("http://ahmadsuki.blogspot.com");
3. }
4. private class MyTask extends AsyncTask<String, Integer, String> {
5.
6.

protected void onPreExecute() {


}

7.

protected String doInBackground(String... params) {


publishProgress(i);
return "All Done!";

8.
9.
10.

11.
12.

protected void onProgressUpdate(Integer... values) {

13.
14.
15.

protected void onPostExecute(String result) {


}

ASMATT (suki1207@uum.edu.my)

46

Anroid Application Development (Series II)

3-5hb November 2014

Summary
1. public void handleAsynTask(View v) {
2.
new MyTask().execute();
3. }
4. private class MyTask extends AsyncTask<Void, Integer, Void> {
5.
6.

protected void onPreExecute() {


}

7.

protected Void doInBackground(Void... voids) {


publishProgress(i);
return null;

8.
9.
10.

11.
12.

protected void onProgressUpdate(Integer... values) {

13.
14.
15.

//protected void onPostExecute(String result) {


//} NOT IMPLEMENTED

Return to Downloading Case:


Observe the Structure
1.
2.
3.
4.
5.
6.

public class MainActivity extends ActionBarActivity {


final String url = "http://crackberry.com/sites/crackberry.com/"
@Override
protected void onCreate(Bundle savedInstanceState) {
}

7.
8.
9.

public void HandleDownload(View v) {


new myDownloadThread().execute();
}

10.

private class myDownloadThread extends AsyncTask<Void, Void, Bitmap> {

2
11.
12.
13.
14.

@Override
protected Bitmap doInBackground(Void... arg0) {
return imgResult;
}

15.
16.
17. }

protected void onPostExecute(Bitmap result) {


}

ASMATT (suki1207@uum.edu.my)

47

Anroid Application Development (Series II)

3-5hb November 2014

Return to Downloading Case:

Analysis Issues
1.
2.
3.
4.
5.
6.

public class MainActivity extends ActionBarActivity {


final String url = "http://crackberry.com/sites/crackberry.com/"
@Override
protected void onCreate(Bundle savedInstanceState) {
}

7.
8.
9.

public void HandleDownload(View v) {


new myDownloadThread().execute();
}

10.

private class myDownloadThread extends AsyncTask<Void, Void, Bitmap> {

Can we display the result here (instead of on onPostExecute?


displaying...",

11.
12.
13.
14.

@Override
Toast.makeText(getApplicationContext(), "is
protected Bitmap doInBackground(Void... arg0) {
Toast.LENGTH_SHORT).show();
return imgResult;
ImageView imgView = (ImageView)
}

findViewById(R.id.imageView1);

imgView.setImageBitmap(result);
protected void onPostExecute(Bitmap
result) {
}

15.
16.
17. }

Return to Downloading Case:

Analysis Issues
1.
2.
3.
4.
5.
6.

public class MainActivity extends ActionBarActivity {


final String url = "http://crackberry.com/sites/crackberry.com/"
@Override
Can we code this toast message in the AsyncTask
protected void onCreate(Bundle
savedInstanceState) {
class?
}
Toast.makeText(getApplicationContext(), "is

downloading...",
7.
8.
9.
10.
11.

public void HandleDownload(View v) {


Toast.LENGTH_LONG).show();
new myDownloadThread().execute();
Toast.makeText(getApplicationContext(), "is downloading...",
Toast.LENGTH_LONG).show();
}

12.

private class myDownloadThread extends AsyncTask<Void, Void, Bitmap> {

13.
14.
15.
16.
17.

@Override
protected Bitmap doInBackground(Void... arg0) {
return imgResult;
}
}

ASMATT (suki1207@uum.edu.my)

48

Anroid Application Development (Series II)

3-5hb November 2014

Return to Downloading Case:

Analysis Issues (Try This)


Put the cursor inside
AsyncTask class, choose
menu source, then select
Override/Implement
Methods

Return to Downloading Case:

Analysis Issues (passing data through 1st param)


1. public void HandleDownload(View v) {
2.

String url = http://crackberry.com/sites/crackberry.com/ +


"files/styles/large/public/topic_images/2013/ANDROID.png";

3.

new myDownloadThread().execute(url);

4. }
5. private class myDownloadThread extends AsyncTask<String, Void,
Bitmap> {
6.
@Override
7.
8.
9.
10.

protected Bitmap doInBackground(String...

arg0)

Bitmap imgResult = null;


try {
imgResult = BitmapFactory.decodeStream((InputStream) new
URL(arg0[0]).getContent());

ASMATT (suki1207@uum.edu.my)

49

Anroid Application Development (Series II)

3-5hb November 2014

Return to Downloading Case:

Analysis Issues (passing data through 1st param)


1. private class myDownloadThread extends AsyncTask<String,

2.
3.
4.
5.
6.
7.

Integer, Bitmap> {

@Override
protected Bitmap doInBackground(String... arg0) {
try {
int sizeFile= new URL(arg0[0]).openConnection().getContentLength();

publishProgress(sizeFile);

8.

imgResult = BitmapFactory.decodeStream((InputStream) new


URL(arg0[0]).getContent());
} catch (Exception e) {}

9.

@Override

10. protected void onProgressUpdate(Integer... values) {


11.
12.
13.

super.onProgressUpdate(values);
Toast.makeText(getApplicationContext(), "The file size is =
"+values[0], Toast.LENGTH_LONG).show();
}

EXTRA: DOWNLOAD IMAGE FROM


THE INTERNET
(2014)

ASMATT (suki1207@uum.edu.my)

50

Anroid Application Development (Series II)

3-5hb November 2014

Internet Access Permission


Before your application can access the Internet, it needs
to be
granted permission for Internet access.
.

Add this in the AndroidManifest.xml:

<uses-permission android:name=android.permission.INTERNET/>

Background Thread

Starting

with Android 3.0 (Honeycomb) you may not

perform
network operations on your main UI thread
This will cause a NetworkOnMainThreadException
In order to solve this, you need to use background
thread:
Handler
or
AsyncTask

ASMATT (suki1207@uum.edu.my)

51

Anroid Application Development (Series II)

3-5hb November 2014

Downloading Image: Example


Try to do this application:

(Use AsyncTask for the downloading task)

Downloading Image: Example

Downloading the image must be performed as


a background task (NEVER in the main UI
thread)
Therefore, in this example, we will use
AsyncTask for the downloading job.

Use this link: https://www.dropbox.com/s/0ghcyv2lmsi0t2j/myBee.bmp

ASMATT (suki1207@uum.edu.my)

52

Anroid Application Development (Series II)

3-5hb November 2014

Downloading Image: Example


1. Create the main layout (xml) for your
Activity. It should have:
A TextView for the title
A ProgressBar (initially invisible) to show
progress
A TextView to display % progress
An ImageView to display the downloaded
image
(set background color to black)
An EditText to enter the image URL
A Button to start the downloading

Downloading Image: Example


2. In your Activity class,
get handles to the all of the views used (call findViewById( ))
inside the onCreate() method
define the button onclick method. In this method:
Get the String from the url address TextView
Create the AsyncTask object & call its execute() method by
passing the url address(String) as its parameter
public void download(View v) {
String url = etUrl.getText().toString().trim();
new ImageDownloader().execute(url);
}

ASMATT (suki1207@uum.edu.my)

*ImageDownloader
is the name of
our AsyncTask

53

Anroid Application Development (Series II)

3-5hb November 2014

Downloading Image: Example

3. Create a subclass of AsyncTask names ImageDownloader, as a


private inner class inside your Activity class
- Use the three generic types as specified:

private class ImageDownloader extends


AsyncTask<String, Integer, Bitmap> {

Downloading Image: Example


4.

Override all the four methods in your AsyncTask , starting with the
onPreExecute() method.
- This is for initialising purpose

onPreExecute() method:
@Override
protected void onPreExecute() {
progress = 0; //declare this int variable as global in your AsyncTask
pb.setVisibility(View.VISIBLE);
Toast.makeText(LoadImageAsyncTaskActivity.this,
"starting download", Toast.LENGTH_SHORT).show();
super.onPreExecute();
}

ASMATT (suki1207@uum.edu.my)

54

Anroid Application Development (Series II)

3-5hb November 2014

Downloading Image: Example


5. Override the doInBackground () method.
- This is for the background task done by the background thread

doInBackground() method:
@Override
protected Bitmap doInBackground(String... urls) {
Bitmap bmp = loadImageFromNetwork(urls[0]); //do the loading task
while (progress < 100) {
progress += 1;
publishProgress(progress); //update progress to UI thread
SystemClock.sleep(100); //to slowdown the system
}
return bmp;
}

Downloading Image: Example


6. Override the onProgressUpdate () method.
- This is to show download progress in the ProgressBar and
TextView on main UI thread

onProgressUpdate() method:
@Override
protected void onProgressUpdate(Integer... values) {
pb.setProgress(values[0]);
percent.setText(values[0] + "%");
}

ASMATT (suki1207@uum.edu.my)

55

Anroid Application Development (Series II)

3-5hb November 2014

Downloading Image Example


7. Override the onPostExecute () method.
- This is to display the result (image) in the ImageView &
a message that download has completed (using Toast)

onPostExecute() method:
@Override
protected void onPostExecute(Bitmap result) {
img.setImageBitmap(result);
Toast.makeText(LoadImageAsyncTaskActivity.this,
"download complete", Toast.LENGTH_SHORT).show();
}

Downloading Image: Example


8. Define the loadImageFromNetwork () method.
- This method do the actual work of loading the image from the
given url address

loadImageFromNetwork() method:
private Bitmap loadImageFromNetwork(String url) {
try {
Bitmap bitmap = BitmapFactory
.decodeStream((InputStream) new URL(url).getContent());
// URL urlObj = new URL(url);
// InputStream in = (InputStream) urlObj.getContent();
//Bitmap bitmap = BitmapFactory.decodeStream(in);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
Log.d("getBmpFromUrl error: ", e.getMessage().toString());
return null;
}
}

ASMATT (suki1207@uum.edu.my)

56

Anroid Application Development (Series II)

3-5hb November 2014

Downloading Image: Example


9. Add permission for Internet access in your manifest file.

AndroidManifest.xml :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.nasran.loadimageasynctask"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<application
:
:
:

DOWNLOAD TEXT FILE FROM THE


INTERNET
(2014)

ASMATT (suki1207@uum.edu.my)

57

Anroid Application Development (Series II)

3-5hb November 2014

Try This: Download a Text File

(2014)

Try This: Download a Text File


1. public void downloadTextFile(View v) {
2.
InputStream inputStream = null;
3.
String theString = "";
4.
String url = "http://textfiles.com/100";
5.
TextView tv = (TextView)
findViewById(R.id.textView1);
6.
tv.setText("URL: " + url);

(2014)

ASMATT (suki1207@uum.edu.my)

58

Anroid Application Development (Series II)

3-5hb November 2014

Try This: Download a Text File


7. try {
8.
//get the TextFile as an inputstream
9.
inputStream = new DefaultHttpClient().execute(new
HttpGet(url)).getEntity().getContent();
10. // convert inputstream to BufferedReader
11. BufferedReader reader = new BufferedReader(new
InputStreamReader(inputStream));
12. //Read from bufferedReader to String
13. for(String line = reader.readLine(); line != null; line =
reader.readLine())
14.
theString += line;
15. inputStream.close();
16. } catch (Exception e) {}
17. EditText et = (EditText) findViewById(R.id.editText1);
18. et.setText(theString);
(2014)

(2014)

ASMATT (suki1207@uum.edu.my)

59

Anroid Application Development (Series II)

3-5hb November 2014

Try This: Download a Text File


(alternative coding without thread yet)
1. public class MainActivity extends ActionBarActivity {
2.
InputStream inputStream = null;
3.
String theString = "";
4.
final String url = "http://textfiles.com/100";
5.
6.
7.
8.
9.

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

(2014)

Try This: Download a Text File


(alternative coding without thread yet)
10. public void downloadTextFile(View v) {
11.
TextView tv = (TextView) findViewById(R.id.textView1);
12.
tv.setText("URL: " + url);
13.
String result = readFile(url);
14.
EditText et = (EditText) findViewById(R.id.editText1);
15.
et.setText(result);
16. }

(2014)

ASMATT (suki1207@uum.edu.my)

60

Anroid Application Development (Series II)

3-5hb November 2014

Try This: Download a Text File


(alternative coding without thread yet)
17.public String readFile (String url){
18.try {
19. inputStream = new DefaultHttpClient().execute(new
HttpGet(url)).getEntity().getContent();
20. BufferedReader reader = new BufferedReader(new
InputStreamReader(inputStream));
21. for(String line = reader.readLine(); line != null; line =
reader.readLine())
22.
theString += line;
23. inputStream.close();
24.} catch (Exception e) {
25.Log.d("InputStream", e.getLocalizedMessage());
26.}
27.return theString;
28.}
(2014)

Hide & UnHide the EditView

(2014)

ASMATT (suki1207@uum.edu.my)

61

Anroid Application Development (Series II)

3-5hb November 2014

Hide & UnHide the EditView


1.
2.
3.
4.
5.
6.
7.
8.
9.

<EditText
android:id="@+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="21dp"

android:visibility="invisible"
android:ems="10" >

(2014)

Hide & UnHide the EditView


1. public void downloadTextFile(View v) {
2.
TextView tv = (TextView) findViewById(R.id.textView1);
3.
tv.setText("URL: " + url);
4.
String result = readFile(url);
5.
EditText et = (EditText) findViewById(R.id.editText1);

6.

et.setVisibility(et.VISIBLE);

7.
et.setText(result);
8. }

(2014)

ASMATT (suki1207@uum.edu.my)

62

Anroid Application Development (Series II)

3-5hb November 2014

Try This:

Download a Text File in AsyncTask

(2014)

Try This:

Download a Text File in AsyncTask


1.
2.
3.

public void downloadTextFile(View v) {


TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText("URL: " + url);

4.

new MyDownTF().execute();

5.

6.

private class MyDownTF extends AsyncTask<Void, Void, String>{

7.

@Override

8.
9.
10.
11.
12.

protected String doInBackground(Void... params) {


// TODO Auto-generated method stub
String result = readFile(url);
return result;
}

(2014)

ASMATT (suki1207@uum.edu.my)

63

Anroid Application Development (Series II)

3-5hb November 2014

Try This:

Download a Text File in AsyncTask


13.
14.
15.
16.
17.
18.
19.
20.

@Override
protected void onPostExecute(String strResult) {
// TODO Auto-generated method stub
super.onPostExecute(strResult);
EditText et = (EditText) findViewById(R.id.editText1);
et.setVisibility(et.VISIBLE);
et.setText(strResult);
}

(2014)

Try This: Download a Text File with

ProgressUpdate (line by line progress display)

(2014)

ASMATT (suki1207@uum.edu.my)

64

Anroid Application Development (Series II)

3-5hb November 2014

Try This: Download a Text File with

ProgressUpdate (line by line progress display)


1. public void downloadTextFile(View v) {
2.
tv = (TextView) findViewById(R.id.textView1);
3.
new MyDownTF().execute();
4. }
5. private class MyDownTF extends AsyncTask<Void,

String,

String>{

(2014)

Try This: Download a Text File with

ProgressUpdate (line by line progress display)


6.

@Override

7.

protected String doInBackground(Void... params) {

8.
9.

String theString = "";


try {

10.
11.
12.
13.
14.

//get the TextFile as an inputstream


inputStream = new DefaultHttpClient().execute(new
HttpGet(url)).getEntity().getContent();
// convert inputstream to BufferedReader
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
//Read from bufferedReader to String

15.
16.

for(String line = reader.readLine(); line != null; line = reader.readLine()) {


theString += line;

17.

publishProgress(line);

18.

19.

inputStream.close();

20.
21.
22.
23.
24.

} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return theString;
}

(2014)

ASMATT (suki1207@uum.edu.my)

65

Anroid Application Development (Series II)

3-5hb November 2014

Try This: Download a Text File with

ProgressUpdate (line by line progress display)


25. @Override
26. protected void onProgressUpdate(String... values) {
27. // TODO Auto-generated method stub
28.
super.onProgressUpdate(values);
29.
tv.setText("Reading the file line by line:\n "+
values[0]);
30. }

(2014)

Try This:
Download a WebPage File

(2014)

ASMATT (suki1207@uum.edu.my)

66

Anroid Application Development (Series II)

3-5hb November 2014

Try This:
Download a WebPage File
Start by changing the
previous layout screen by
embedding a WebView
object (remove the
EditText).

(2014)

Try This:
Download a WebPage File
1. @Override
2. protected void onPostExecute(String
strResult) {
3. // TODO Auto-generated method stub
4.
super.onPostExecute(strResult);
5.
WebView wv = (WebView)
findViewById(R.id.webView1);
6.
wv.loadData(strResult, "text/html", null);
7. }

(2014)

ASMATT (suki1207@uum.edu.my)

67

Anroid Application Development (Series II)

3-5hb November 2014

Try This: Download a WebPage File


with a Dynamic URL

(2014)

Try This: Download a WebPage File


with a Dynamic URL
1. public void downloadTextFile(View v) {
2. EditText ed = (EditText)
findViewById(R.id.editText1);
3. String strURL =
ed.getText().toString().trim();
4. tv = (TextView) findViewById(R.id.textView1);
5. tv.setText("URL: " + strURL);
6. new MyDownTF().execute(strURL);
7. }
8. private class MyDownTF extends
AsyncTask<String, String, String>{
(2014)

ASMATT (suki1207@uum.edu.my)

68

Anroid Application Development (Series II)

3-5hb November 2014

Try This: Download a WebPage File


with a Dynamic URL
9.

@Override

10. protected String doInBackground(String... params) {


11.
12.

// TODO Auto-generated method stub


String theString = "";

13.

String theURL = params[0];

14.

try {

15.

//get the TextFile as an inputstream

16.

inputStream = new DefaultHttpClient().execute(new


HttpGet(theURL)).getEntity().getContent();

17.
18.
19.
20.

// convert inputstream to BufferedReader


BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
//Read from bufferedReader to String
for(String line = reader.readLine(); line != null; line = reader.readLine()) {

21.
22.
23.
24.

theString += line;
//publishProgress(line);
}
inputStream.close();

25.
26.
27.

} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}

28.
29.

return

theString;

(2014)

Accessing Web Service

(2014)

ASMATT (suki1207@uum.edu.my)

69

Anroid Application Development (Series II)

3-5hb November 2014

Access Database Server:


Old Architecture Centralized System

(2014)

Access Database Server:


Old Architecture Client/Server System

(2014)

ASMATT (suki1207@uum.edu.my)

70

Anroid Application Development (Series II)

3-5hb November 2014

Access Database Server:


Web Architecture Web Server

(2014)

Access Database Server:


Web Architecture Web Service

(2014)

ASMATT (suki1207@uum.edu.my)

71

Anroid Application Development (Series II)

3-5hb November 2014

Access Database Server:


Web Service Architecture Android

(2014)

JSON (JavaScript Object Notation)

very light weight


structured
easy to parse
human readable
the best alternative
to XML

(2014)

ASMATT (suki1207@uum.edu.my)

72

Anroid Application Development (Series II)

3-5hb November 2014

JSON (JavaScript Object


Notation)
square bracket ([) represents
a JSON array
curly bracket ({) represents a
JSON object
A JSON object contains a key
that is just a string. Pairs of
key/value make up a JSON
object
Each key has a value that
could be string , integer or
double etc.
(2014)

JSON Web Service Programming


3 main steps:
Download JSON file
Parsing
Display (formatting)

(2014)

ASMATT (suki1207@uum.edu.my)

73

Anroid Application Development (Series II)

3-5hb November 2014

JSON Web Service Programming


Step 1: Download a JSON File
From our previous
download text file app,
just change it to the new
JSON URL, e.g.
final String url =
"http://kis.kedah.gov.my/
majlis/majlis.json";
(2014)

JSON Web Service Programming Exercise


Step 1: Download this JSON File

(2014)

ASMATT (suki1207@uum.edu.my)

74

Anroid Application Development (Series II)

3-5hb November 2014

JSON Web Service Programming


Step 2: Parsing the JSON File

(2014)

JSON Web Service Programming


Step 2: Parsing the JSON File

For parsing a JSON object, we have to create an object of class


JSONObject and specify a string containing JSON data to it. Its
syntax is:

JSONObject reader = new JSONObject(strJSON);


An JSON file consist of different object with different key/value
pair:

JSONObject sys = reader.getJSONObject("sys");


strCountry = sys.getString("country");
(2014)

ASMATT (suki1207@uum.edu.my)

75

Anroid Application Development (Series II)

3-5hb November 2014

JSON Web Service Programming


Step 2: Parsing the JSON File
1. public void parsingJSON(String strJSON) {
2. // TODO Auto-generated method stub
3.
JSONObject jsonObj;
4.
String strDate, strTime;
5.
try {
6.
jsonObj = new JSONObject(strJSON);
7.
strDate = jsonObj.getString("date");
8.
strTime = jsonObj.getString("time");
9.
Toast.makeText(getApplicationContext(),
"Your Date-Time: "+strDate+" - "+strTime,
Toast.LENGTH_LONG).show();
10.
} catch (JSONException e) {}
11. }

(2014)

JSON Web Service Programming


Step 3: Display the Output/Data

(2014)

ASMATT (suki1207@uum.edu.my)

76

Anroid Application Development (Series II)

3-5hb November 2014

JSON Web Service Programming


Step 3: Display the Output/Data
1.
2.
3.
4.
5.
6.
7.
8.

JSONObject jsonObj;
String strDate="", strTime="";
try {
jsonObj = new JSONObject(strJSON);
strDate = jsonObj.getString("date");
strTime = jsonObj.getString("time");
} catch (JSONException e) {}
TextView tvDate = (TextView)
findViewById(R.id.textView3);
9. TextView tvTime =
(TextView)findViewById(R.id.textView4);
10. tvDate.setText("Today Date: "+strDate);
11. tvTime.setText("US Time now: "+strTime);

(2014)

JSON Web Service Programming


Parsing the JSON File with Array Object []

(2014)

ASMATT (suki1207@uum.edu.my)

77

Anroid Application Development (Series II)

3-5hb November 2014

JSON Web Service Programming


Parsing the JSON File with Array Object []
1. public void parsingJSON(String strJSON) {
2. // TODO Auto-generated method stub
3.
JSONObject jsonObj;
4.
String strMajlis="", strTarikh="",
strTempat="";
5.
String strOutput = "Senarai Majlis
adalah seperti berikut:\n\n";
6.
try {
7.
jsonObj = new JSONObject(strJSON);

(2014)

Parsing the JSON File with


Array Object []
8. // Getting JSON Array node
9. JSONArray jsonArray =
jsonObj.getJSONArray
("majlis");
10. // looping through All array items

11. for (int i = 0; i <


jsonArray.length(); i++) {
12.
JSONObject majlisItem =
jsonArray.getJSONObject(i);

(2014)

ASMATT (suki1207@uum.edu.my)

78

Anroid Application Development (Series II)

3-5hb November 2014

Parsing the JSON File with


Array Object []
13. strMajlis =
majlisItem.getString("majlis");
14. strTarikh =
majlisItem.getString("trkh");
15. strTempat =
majlisItem.getString("tempat");
16. strOutput += (i+1) + ") " + strMajlis
+ "\nTarikh: " + strTarikh +
"\nTempat: " + strTempat +
"\n\n\n";
17.
}
18. } catch (JSONException e) {}
19. TextView tvOutput = (TextView)
findViewById(R.id.textView3);
20. tvOutput.setText(strOutput);

(2014)

Exercise

(2014)

ASMATT (suki1207@uum.edu.my)

79

Anroid Application Development (Series II)

3-5hb November 2014

WEB SERVICE EXTRA

(2014)

Accessing Web Service


Web service is a program that is provided as service which can be
accessed by other program through Internet by using the Web standard
(e.g. http and xml)

Examples such as Google Map, Amazon, Yahoo, weather service,


cloud computing services etc. You can define your own web services
There are 2 main types:
SOAP based web services
Restful web services

ASMATT (suki1207@uum.edu.my)

80

Anroid Application Development (Series II)

3-5hb November 2014

Restful Web Service


Restful (Rest-based) web service is based on web standard architecture
(Rest stands for Representational State Transfer)
Each service is considered as a resource (similar like web page) :
has its own URL
can be accessed using standard Http operations
(GET, POST, PUT & DELETE)
REST is simpler to use than the SOAP (Simple Object Access Protocol)
approach

Restful Web Service


Well look into how to consume Restful web services from Android client
A client can make 4 types of request :
POST - Adds a resource on the server. The resource is contained in the
body of the POST request. POST is analogous to an SQL insert.
GET Retrieves a resource from the server. The resource is specified
with a URL. GET is analogous to an SQL select
PUT - Updates a resource on the server. The resource is contained
in the body of the PUT request. PUT is analogous to an SQL update
DELETE Deletes a resource on the server. The resource is specified
in the URL only. DELETE is analogous to an SQL delete

ASMATT (suki1207@uum.edu.my)

81

Anroid Application Development (Series II)

3-5hb November 2014

Restful Web Service


REST involves the transfer of resources between clients and servers.
The formats are usually one or more simple MIME types
such as:
commonly text/plain,
text/html,
application/json,
application/xml
Calling a REST from an Android application requires making an HTTP
request in a background thread and then parsing the results on the UI thread

Restful Web Service


The Java Classes to make Http request from a client:
(obtained from org.apache.http package)
HttpClient (abstract), DefaultHttpClient (concrete)
For creating the http client object
HttpGet, HttpPost
For creating the request operation object (i.e HttpGet for GET op)
HttpResponse
For creating the response object
HttpEntity
For obtaining the result from the response object

ASMATT (suki1207@uum.edu.my)

82

Anroid Application Development (Series II)

3-5hb November 2014

Example : A Simple Contact Rest-based Application


In this application, we can use Restful services to
List all contacts
Search a contact
Add a new contact
We will use AsyncTask to
connect & make
request to the services

Example : A Simple Contact Rest-based Application

List (GET)

Search (GET)

Create (POST)

Note: Request&Response use JSON Format

ASMATT (suki1207@uum.edu.my)

83

Anroid Application Development (Series II)

3-5hb November 2014

Example : A Simple Contact Rest-based Application

1. Create the main layout (xml) for your Activity. It should have:
A TextView for the title
A Button to List All Contacts
A TextView to display Enter Name
An EditText to enter person name
A TextView to display Enter Name
An EditText to enter person phone number
A Button to find/search a contact
A Button to add a new contact
An EditText to display operation result message

Example : A Simple Contact Rest-based Application

2. In the onCreate() method in your Activity class,


get handles to the all of the Buttons used (call findViewById( )) &
register with the onClick listeners
Specify that your Activity class also implements OnClickListener
public class Main extends Activity implements OnClickListener {
int operation = 0; //identify operation to be performed
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
findViewById(R.id.button1).setOnClickListener(this);
findViewById(R.id.button2).setOnClickListener(this);
}

ASMATT (suki1207@uum.edu.my)

84

Anroid Application Development (Series II)

3-5hb November 2014

Example : A Simple Contact Rest-based Application


3. In the onClick() method in your Activity class,
Identify which button is clicked and assign the correct
operation id.
Execute the background thread(AsyncTask) to perform the
operation
@Override
public void onClick(View v) {
Button b = (Button) v;
switch (b.getId()) {
case R.id.my_button:
operation = 1; //List Op
new LongRunningGetIO().execute();
break;
case R.id.button1:
operation = 2; ; //Search Op
new LongRunningGetIO().execute();
break;
case R.id.button2:
operation = 3; ; //Add Op
new LongRunningGetIO().execute();
break;
}
}

* LongRunningGetIO
is the name of
our AsyncTask

Example : A Simple Contact Rest-based Application

4. Create a subclass of AsyncTask names LongRunningGetIO, as a


private inner class inside your Activity class
- Use the three generic types as specified:

private class LongRunningGetIO extends


AsyncTask<Void, Void, String> {

ASMATT (suki1207@uum.edu.my)

85

Anroid Application Development (Series II)

3-5hb November 2014

Example : A Simple Contact Rest-based Application


5. Override the two methods in your AsyncTask, starting with the
doInBackground () method

doInBackground() method:
@Override
* http://10.11.8.204:8080/
protected String doInBackground(Void... params) {
is the IP Address of the server
HttpClient httpClient = new DefaultHttpClient();
String addr = null;
if (operation == 1)
addr = "http:// 10.1.100.229:8080/GetSomeRest/webresources/service/";
if (operation == 2) {
EditText edt = (EditText) findViewById(R.id.editText1);
String name = edt.getText().toString();
addr = "http:// 10.1.100.229:8080/GetSomeRest/webresources/service/"
+ name;
}
if (operation == 3) {
addr = "http:// 10.1.100.229:8080/GetSomeRest/webresources/service/add";
}

Example : A Simple Contact Rest-based Application


doInBackground() method (contd):
HttpGet httpGet = null;
HttpPost postRequest = null;
if (operation <= 2) { //operation == 1 or 2
httpGet = new HttpGet(addr);
//create GET request
httpGet.addHeader("accept", "application/json"); //indicate result message in JSON
Log.d("nasran",addr);
} else {
//operation == 3
try {
EditText nameEdt = (EditText) findViewById(R.id.editText1);
String name = nameEdt.getText().toString();
EditText telEdt = (EditText) findViewById(R.id.editText2);
String telNo = telEdt.getText().toString();
Log.d("nasran",addr);
postRequest = new HttpPost(addr); //create POST request
StringEntity input = new StringEntity("{\"name\":\""
+ name + "\",\"telNo\":\"" + telNo + "\"}");
//Construct JSON input
input.setContentType("application/json"); //indicate input message in JSON form
postRequest.setEntity(input); //append input in POST request
} catch (Exception e) { }
}

ASMATT (suki1207@uum.edu.my)

86

Anroid Application Development (Series II)

3-5hb November 2014

Example : A Simple Contact Rest-based Application


doInBackground() method (contd):
String text = null;
HttpResponse response = null;
try {
if (operation <= 2) {
response = httpClient.execute(httpGet); //send GET request
} else {
response = httpClient.execute(postRequest); //send POST request
}
HttpEntity entity = response.getEntity(); //get Entity from response
text = getResultFromEntity(entity); //get results (in String) from Entity
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;

Example : A Simple Contact Rest-based Application


6. Override the onPostExecute () method.
- This is to display the result from the background thread in main
thread

onPostExecute() method:
@Override
protected void onPostExecute(String results) {
if (results != null) {
EditText et = (EditText) findViewById(R.id.editText3);
et.setText(results);
}
}

ASMATT (suki1207@uum.edu.my)

87

Anroid Application Development (Series II)

3-5hb November 2014

Example : A Simple Contact Rest-based Application


7. Define the getResultFromEntity () method.
- This method get the JSON result in String type from the Entity

getResultFromEntity() method:
protected String getResultFromEntity(HttpEntity entity)
throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n > 0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n > 0)
out.append(new String(b, 0, n));
}
return out.toString();
}

Example : A Simple Contact Rest-based Application


8. Add permission for Internet access in your manifest file.

AndroidManifest.xml :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package= "com.example.testrestclientasynctask"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<application
:
:
:

ASMATT (suki1207@uum.edu.my)

88

Anroid Application Development (Series II)

3-5hb November 2014

Introduction
Web services provide a standard means of
interoperating between different software
applications, running on a variety of platforms and/or
frameworks.

Intro - II
One of the most common functionalities required
in mobile applications is to call a web service to
retrieve data.
This process involves requesting the web service
with parameters, receiving the response and
parsing it to obtain data.
Today the most common web services types are
SOAP and REST.
Android does not provide a built in SOAP client,
there are many third party libraries that can be
used

ASMATT (suki1207@uum.edu.my)

89

Anroid Application Development (Series II)

3-5hb November 2014

Intro (REST)
REST (or RESTful) Services are an increasingly
common paradigm for creating web services
because of their simplicity and inherent platform
agnostic approach.
Many of the major service providers use REST,
such as Twitter, Flickr, Facebook, etc.
REST allows for stateless, cacheable, and simple
to consume client-server architecture over HTTP.
Among the most popular formats are JSON
(JavaScript Object Notation) and XML.

Web Service with JSON


Simple JSON data:
{
"data" : {
"id": "1234",
"category" : "my_category",
"name" : "my_name"
}
}

 In order to parse the JSON data:


import org.json.JSONException;
import org.json.JSONObject;

ASMATT (suki1207@uum.edu.my)

90

Anroid Application Development (Series II)

3-5hb November 2014

Web Service with JSON - II


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.

String id;
String name;
String category;
String jsonString = "{\"data\" : {\"id\": "1234","category" :
Android","name" : Ahmad Suki"}}";
try{
JSONObject jsonObj= new JSONObject(jsonString);
JSONObject dataObj = jsonObj.getJSONObject("data");
id = dataObj.getString("id");
category = dataObj.getString("category");
name = dataObj.getString("name");
}
catch(JSONException e) {
}

Parsing JSON message


The results from List operation is in JSON format.

We have to parse the JSON formatted massage to extract the data inside it
e.g. how to obtain only the names and phone numbers from the message

ASMATT (suki1207@uum.edu.my)

91

Anroid Application Development (Series II)

3-5hb November 2014

Parsing JSON message

To parse JSON message, youll need these Java classes from


org.json package:
JSONObject
JSONArray
Also need the StringBuilder to append the string, representing
each of the JSON object, extracted from JSON message

Parsing JSON message


1. We need to do the parsing in the AsyncTask onPostExecute method:
(you can modify this method from the last example)
protected void onPostExecute(String result)
Notice that this method receives a string parameter, result, which contain
the JSON message that we are going to process. Also declare the
StringBuilder:
StringBuilder contactResult = new StringBuilder();

2. The JSON processing methods can throw exceptions, so add try and
catch blocks next:
try {
}
catch (Exception e) {
et.setText(Something went wrong!");
e.printStackTrace();
}

ASMATT (suki1207@uum.edu.my)

92

Anroid Application Development (Series II)

3-5hb November 2014

Parsing JSON message


3. Inside the try block, create a JSONObject, passing the JSON result
as the parameter:
JSONObject resultObject = new JSONObject(result ) ;

4. We need to retrieve this contact array, using its name: Contacts. Get
the Contacts array from the JSON Object:

JSONArray contactArray = resultObject.getJSONArray("Contacts");

Parsing JSON message


5. After fetching the contact array, add a for loop to iterate through the
contacts:
for (int t=0; t<contactArray.length(); t++) {
}

6. Inside the loop, get each item as a JSON Object:

JSONObject contactObject = contactArray.getJSONObject(t);

ASMATT (suki1207@uum.edu.my)

93

Anroid Application Development (Series II)

3-5hb November 2014

Parsing JSON message


7. Now retrieve the person name from this object, appending it to the
String Builder :
contactResult.append(contactObject.getString("name")+ ": ");

8. Next, retrieve the phone number from the object, also appending it to
the String Builder and ended with a new line character:

contactResult.append(contactObject.getString("telNo")+ "\n");

Parsing JSON message


9. Now move to after the catch block. If the processing has worked, we
display the result (convert the StringBuilder to String) in the EditText ,
otherwise we display an error message::

if(contactResult.length()>0)
et.setText(contactResult.toString());
else
et.setText("Sorry - no results!");

ASMATT (suki1207@uum.edu.my)

94

Das könnte Ihnen auch gefallen