Cara cara Membuat Android

download Cara cara Membuat Android

of 95

Transcript of Cara cara Membuat Android

  • 7/26/2019 Cara cara Membuat Android

    1/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 1

    Android Application

    Development

    Series II

    Review

  • 7/26/2019 Cara cara Membuat Android

    2/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 2

    Create Android Project

    Project File >> New >> Project >> Android App

    Project

    Enter Application Name, Project Name & Package

    Name;

  • 7/26/2019 Cara cara Membuat Android

    3/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 3

    Android App Development Steps

    Creating Your Emulator

    Create your emulator

    Eclipse: Window =>

    Android Virtual Device

    Manager, Choose New

  • 7/26/2019 Cara cara Membuat Android

    4/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 4

    Before Execute Your App1) Select target API

    (Choose Android API 19)

    2) Select Device or Screensize (choose 5.1).

    5) Click ok. Accept otherdefaults. Click this button to

    create the emulator.

    3) Give a name for thistarget. No space allowed.

    4) Choose No skin

    Run your app

    Emulator will take some

    time to be loaded

    1) Expand your

    project (src)

    2) Click

    here

    3) Click run

    button

    4) Choose

    this

  • 7/26/2019 Cara cara Membuat Android

    5/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 5

    ANDROID CODING

    Button & onClick Handler

    Open activity_main.xml (your layout)

  • 7/26/2019 Cara cara Membuat Android

    6/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 6

    Add an EditText, a Button & a TextView

    Run your app

  • 7/26/2019 Cara cara Membuat Android

    7/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 7

    Add onClick handler

    Open main.xml

    Add a new line (as in Line 21):17.

    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

  • 7/26/2019 Cara cara Membuat Android

    8/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 8

    myFirstButtonHandlerActivity.java1. packagecom.Suki.ButtonHandler;

    2. importandroid.app.Activity;

    3. importandroid.os.Bundle;

    4. importandroid.view.View;

    5. importandroid.widget.EditText;

    6. importandroid.widget.TextView;

    7. publicclassMyFirstButtonHandlerActivity extendsActivity {

    8. /** Called when the activity is first created. */

    9. @Override

    10. publicvoidonCreate(Bundle savedInstanceState) {

    11. super.onCreate(savedInstanceState);

    12. setContentView(R.layout.main);

    13. }

    14.

    15. publicvoidhandleClick(View v) {

    16. // get a reference to editText1 from main.xml

    17. EditText widget_editText1= (EditText) findViewById(R.id.editText1);

    18. // get the text (input)

    19. String inputText= widget_editText1.getText().toString();

    20. // get a reference to textView1 from main.xml

    21. TextView widget_textView1= (TextView) findViewById(R.id.textView1);

    22. // put a message (from input) to the widget

    23. widget_textView1.setText("Your Name: "+ inputText);

    24. }25. }

    Should be similar

    with your onClick

    button in the

    activity_main.xml

    Manipulate Numbers(Create a new project HandleNumber)

  • 7/26/2019 Cara cara Membuat Android

    9/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 9

    Button onClick Handler for

    HandleNumberActivity.java

    1. publicvoidhandleNom(View v) {

    2. EditText inputTeks= (EditText) findViewById(R.id.editText1);

    3. String teks= inputTeks.getText().toString();

    4. floatcelsius = Float.parseFloat(teks);

    5. floatfaren = ((celsius * 9) / 5) + 32;

    6.

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

    8. label1.setText(celsius+ " Celsius is equal to "+

    9. faren+ " Farenheit.");

    10. }

    We want to produce/output something like this,

    38.0Celsius is equal to 100.4 Farenheit.

    Exercise:

    Power 3 Calculator

  • 7/26/2019 Cara cara Membuat Android

    10/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 10

    Try This:

    Multiplication Calculator

    Exercise: Multiplication Calculator

    1. publicvoidCalc(View v) {

    2. EditText et1= (EditText)findViewById(R.id.editText1);

    3. String nomStr1= et1.getText().toString();

    4. intnomInt1= Integer.parseInt(nomStr1);

    5. EditText et2= (EditText)findViewById(R.id.editText2);

    6. String nomStr2= et2.getText().toString();

    7. intnomInt2= Integer.parseInt(nomStr2);

    8. inthasil= nomInt1*nomInt2;

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

    10. tv.setText("Result is: "+ hasil);

    11.}

  • 7/26/2019 Cara cara Membuat Android

    11/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 11

    Exercise:

    Basic Calculator

    DUPLICATING & IMPORTING

    AN ANDROID PROJECT

  • 7/26/2019 Cara cara Membuat Android

    12/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 12

    Duplicate an Android Project

    Simply Copy &

    Paste (in Eclipse)

    Highlight the

    project

    Ctrl-C (Copy)

    Ctrl-V (Paste)

    Enter a newproject name

    Copy a project from Another Source

    Eclipse: File -> Import

    Choose Android ->

    Existing AndroidCode Into Workspace

    Next -> Browse ->locate the project

    OK -> tick Copyproject intoworkspace-> Finish

  • 7/26/2019 Cara cara Membuat Android

    13/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 13

    Using Basic Selection

    26

    The if Statement Syntax

    The ifstatement has the following syntax:

    if ( condition) {

    statement(s);}

    ifis a Java

    reserved word

    The conditionmust be a

    boolean expression. It must

    evaluate to either true or false.

    If the conditionis true the statement(s)is executed.

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

  • 7/26/2019 Cara cara Membuat Android

    14/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 14

    27

    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

    greater than

    = greater than or equal to

    Try This: Odd or Even Number

  • 7/26/2019 Cara cara Membuat Android

    15/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 15

    Try This: Odd or Even Number

    1. EditText et = (EditText) findViewById(R.id.editText1);

    2. String nomStr = et.getText().toString();

    3. intnom = Integer.parseInt(nomStr);

    4. String hasil = "Not known yet";

    5. if(nom%2 == 0) { //or (nom/2*2 == nom)

    6. hasil = "EVEN";

    7. } else{

    8. hasil = "ODD";

    9. }

    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.

  • 7/26/2019 Cara cara Membuat Android

    16/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 16

    Tips: Background Color & Images

    Http://html-color-codes.info

    VIDEO

    Local & Remote

  • 7/26/2019 Cara cara Membuat Android

    17/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 17

    VIDEO

    Supported File: 3gp, mp4, ts.

    Supported network protocols:

    HTTP/HTTPS progressive streaming.

    Ex:http://fr3.ah.fm:9000

    HTTP/HTTPS live streaming (HLS).

    Ex: http://www.playon.tv/online/iphone5/main.m3u8

    Real Time Streaming Protocol (RTSP).

    Ex:rtsp://208.77.20.52:1935/dmm1/ten RTMP Protocol is not supported

    Ex:rtmp://109.201.157.183/ren/ren3

    http://fr3.ah.fm:9000/http://www.playon.tv/online/iphone5/main.m3u8http://www.playon.tv/online/iphone5/main.m3u8http://www.playon.tv/online/iphone5/main.m3u8http://www.playon.tv/online/iphone5/main.m3u8http://www.playon.tv/online/iphone5/main.m3u8http://www.playon.tv/online/iphone5/main.m3u8http://www.playon.tv/online/iphone5/main.m3u8http://fr3.ah.fm:9000/http://fr3.ah.fm:9000/http://fr3.ah.fm:9000/http://fr3.ah.fm:9000/http://fr3.ah.fm:9000/http://fr3.ah.fm:9000/
  • 7/26/2019 Cara cara Membuat Android

    18/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 18

    Remote Video

    1. protectedvoidonCreate(Bundle savedInstanceState) {

    2. super.onCreate(savedInstanceState);

    3. setContentView(R.layout.activity_main);

    4.

    5. String url = "http://download.wavetlan.com/SVV/Media/HTTP/H264/ Talkinghead_Media/H264_test2_Talkinghead_mp4_480x320.mp4";

    6. Uri uri = Uri.parse(url);

    7. VideoView video = (VideoView) findViewById(R.id.videoView1);

    8.

    9. final MediaController ctlr = newMediaController(this);

    10. video.setMediaController(ctlr);

    11. video.setVideoURI(uri);

    12. video.requestFocus();

    13. video.setOnPreparedListener(newOnPreparedListener() {

    14. ProgressBar pb=(ProgressBar) findViewById(R.id.progressBar1);

    15.

    16. publicvoidonPrepared(MediaPlayer mp) {17. pb. setVisibility(View.GONE);// Close the progress bar and play the video

    18. ctlr.setAnchorView(video);

    19. video.start();

    20. }

    21. });

    22. }

    Remote Video

    1. protectedvoidonCreate(Bundle savedInstanceState) {

    2. super.onCreate(savedInstanceState);

    3. setContentView(R.layout.activity_main);

    4.

    5. String url = " https://www.dropbox.com/s/xj3y0ofg7a3dqln/frozen_playice.mp4";

    6. Uri uri = Uri.parse(url);

    7. VideoView video = (VideoView) findViewById(R.id.videoView1);

    8.

    9. final MediaController ctlr = newMediaController(this);

    10. video.setMediaController(ctlr);

    11. video.setVideoURI(uri);

    12. video.requestFocus();

    13. video.setOnPreparedListener(newOnPreparedListener() {

    14. ProgressBar pb=(ProgressBar) findViewById(R.id.progressBar1);

    15.

    16. publicvoidonPrepared(MediaPlayer mp) {

    17. pb. setVisibility(View.GONE);// Close the progress bar and play the video

    18. ctlr.setAnchorView(video);

    19. video.start();

    20. }

    21. });

    22. }

  • 7/26/2019 Cara cara Membuat Android

    19/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 19

    Live TV

    1. protectedvoidonCreate(Bundle savedInstanceState) {

    2. super.onCreate(savedInstanceState);

    3. setContentView(R.layout.activity_main);

    4.

    5. String url = "http://dl.dropboxusercontent.com/u/59242226/play/smarttv/channel/tvtiga.m3u8" ;

    6. Uri uri = Uri.parse(url);

    7. VideoView video = (VideoView) findViewById(R.id.videoView1);

    8.

    9. final MediaController ctlr = newMediaController(this);

    10. video.setMediaController(ctlr);

    11. video.setVideoURI(uri);

    12. video.requestFocus();

    13. video.setOnPreparedListener(newOnPreparedListener() {

    14. ProgressBar pb=(ProgressBar) findViewById(R.id.progressBar1);

    15.

    16. publicvoidonPrepared(MediaPlayer mp) {17. pb. setVisibility(View.GONE);// Close the progress bar and play the video

    18. ctlr.setAnchorView(video);

    19. video.start();

    20. }

    21. });

    22. }

    Local Video

    1. protectedvoidonCreate(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. MediaController ctlr = newMediaController(this);

    7. video.setMediaController(ctlr);

    8. video.setVideoURI(uri);

    9. video.start();

    10. }

  • 7/26/2019 Cara cara Membuat Android

    20/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 20

    PLAY AN AUDIO

    1. public class MainActivity extends Activity {

    2. private MediaPlayer mp;

    3. @Override

    4. public void onCreate(Bundle savedInstanceState) {

    5. super.onCreate(savedInstanceState);

    6. setContentView(R.layout.activity_main);

    7. mp = new MediaPlayer();

    8. }

    9.

    10. public void playSound(View v){11. mp = MediaPlayer.create(MainActivity.this,

    R.raw.lagu);

    12. mp.start();

    13. }

    14.}

    Media Player source.

    TALKING ANDROID

    Android is Interesting!

  • 7/26/2019 Cara cara Membuat Android

    21/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 21

    Try This: Text-to-Speech

    1. publicclassMainActivity extendsActivityimplementsOnInitListener {

    2. TextToSpeech talker;

    3.

    4. @Override

    5. protectedvoidonCreate(BundlesavedInstanceState) {

    6. super.onCreate(savedInstanceState);

    7. setContentView(R.layout.activity_main);8. talker = new TextToSpeech(this, this);

    9. }

    Try This: Text-to-Speech

    10. @Override

    11. publicvoidonInit(intarg0) {

    12. // TODOAuto-generated method stub

    13. talker.setLanguage(Locale.UK);

    14. talker.setSpeechRate((float)kadar);

    15. talker.speak(teks,TextToSpeech.QUEUE_FLUSH, null);

    16.

    17. }

  • 7/26/2019 Cara cara Membuat Android

    22/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 22

    TOUCH HANDLING

    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

  • 7/26/2019 Cara cara Membuat Android

    23/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 23

    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;

    Introducing TOAST WIDGET

    Try This: Touch, Move & Lift Event

  • 7/26/2019 Cara cara Membuat Android

    24/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 24

    Try This: Touch Event

    1. @Override

    2. publicbooleanonTouchEvent(MotionEvent event) {

    3. intdetectTouch = event.getAction();

    4. if(detectTouch==MotionEvent.ACTION_DOWN) {

    5. Toast.makeText(getApplicationContext(),

    "...is moving", Toast.LENGTH_SHORT).show();

    6. }

    7. returntrue;

    8. }

    Try This: Detecting Swipe Event

    1. publicclassGestureActivity extendsActivity {

    2. floatx1, x2;

    3. floaty1, y2;

    4. @Override

    5. protectedvoidonCreate(BundlesavedInstanceState) {

    6. super.onCreate(savedInstanceState);

    7. setContentView(R.layout.gesture);

    8. }

  • 7/26/2019 Cara cara Membuat Android

    25/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 25

    Try This: Detecting Swipe Event

    9. @Override

    10. publicbooleanonTouchEvent(MotionEvent event) {

    11. intaction = event.getAction();

    12. switch(action) {

    13. caseMotionEvent.ACTION_DOWN:

    14. x1= event.getX();

    15. y1= event.getY();

    16. break;

    17. caseMotionEvent.ACTION_UP:

    18. x2= event.getX();

    19. y2= event.getY();

    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. }

  • 7/26/2019 Cara cara Membuat Android

    26/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 26

    Try This: Detecting Swipe Event

    32. // if Down to UP sweep event on screen

    33. if(y1> y2) {

    34. Toast.makeText(this,"Down to UP Swap Performed",Toast.LENGTH_LONG).show();

    35. }

    36. break; // for MOVE_UP event

    37. }

    38. returntrue;

    39.}

    Exercise

    When a user performs this swipe, play a

    song.

    When a user performs this swipe, stop thesong.

  • 7/26/2019 Cara cara Membuat Android

    27/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 27

    OPEN ANOTHER LAYOUT

    Open Another Layout

    The easier way to move from one layout to

    another layout is to use setContentView().

  • 7/26/2019 Cara cara Membuat Android

    28/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 28

    Try This: Open Another Layout

    Try This: Open Another Layout

    1. publicclassMainActivity extendsActivity {

    2. @Override

    3. protectedvoidonCreate(Bundle savedInstanceState) {4. super.onCreate(savedInstanceState);

    5. setContentView(R.layout.activity_main);

    6. }

    7. publicvoidOpen_Layout2(View v) {

    8. setContentView(R.layout.second_layout);

    9. }

    10.}

  • 7/26/2019 Cara cara Membuat Android

    29/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 29

    Exercise: Open Another Layout

    Try implements BACK

    button (to return to the

    main page).

    Exercise: Open Another Layout

    Sample Solution

    1. publicvoidOpen_Layout2(View v) {

    2. setContentView(R.layout.second_layout);

    3. }

    4. publicvoidHandleBACK(View v) {

    5. setContentView(R.layout.activity_main);

    6. }

  • 7/26/2019 Cara cara Membuat Android

    30/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 30

    Exercise: Open Another Layout

    Exercise: Open Another Layout

    Sample Solution (for touch screen)

    1. @Override

    2. publicbooleanonTouchEvent(MotionEvent event) {

    3. // TODOAuto-generated method stub

    4. intdetectTouch = event.getAction();

    5. if(detectTouch==MotionEvent.ACTION_DOWN) {

    6. setContentView(R.layout.second_layout);

    7. }

    8. returntrue;

    9. }

  • 7/26/2019 Cara cara Membuat Android

    31/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 31

    ACTION BAR MENU

    Try This: Create an Action Bar Menu

  • 7/26/2019 Cara cara Membuat Android

    32/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 32

    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

    Try This: Create an Action Bar Menu

  • 7/26/2019 Cara cara Membuat Android

    33/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 33

    Try This: Create an Action Bar Menu

    menu.xml: (copy & modify tag)

    1.

    5.

    10.

    Try This: Create an Action Bar Menu

    15. 21.

    27.

    33.

  • 7/26/2019 Cara cara Membuat Android

    34/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 34

    Try This: Create an Action Bar Menu

    .java: (copy & modify if statement in method onOptionsItemSelected)

    1. @Override

    2. publicbooleanonOptionsItemSelected(MenuItem item) {

    3. // Handle action bar item clicks here. The action barwill

    4. // automatically handle clicks on the Home/Up button,so long

    5. // as you specify a parent activity inAndroidManifest.xml.

    6. intid = 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. }

    Try This: Create an Action Bar Menu

    .java: (copy & modify if statement in method onOptionsItemSelected)

    13. if(id == R.id.play_music) {

    14. mp= MediaPlayer.create(getApplicationContext(),R.raw.uum_song);

    15. mp.start();

    16. }

    17. if(id == R.id.stop_music) {

    18. mp.stop();

    19. }

    20. if(id == R.id.bantuan) {

    21. setContentView(R.layout.screen_bantuan);

    22. }

    23. returnsuper.onOptionsItemSelected(item);

    24.}

  • 7/26/2019 Cara cara Membuat Android

    35/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 35

    DUPLICATING & IMPORTINGAN ANDROID PROJECT

    Duplicate an Android Project

    Simply Copy &

    Paste (in Eclipse)

    Highlight the

    project

    Ctrl-C (Copy)

    Ctrl-V (Paste)

    Enter a new

    project name

  • 7/26/2019 Cara cara Membuat Android

    36/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 36

    Copy a project from Another Source

    Eclipse: File -> Import

    Choose Android ->Existing AndroidCode Into Workspace

    Next -> Browse ->locate the project

    OK -> tick Copyproject intoworkspace-> Finish

    Download Internet Resource

  • 7/26/2019 Cara cara Membuat Android

    37/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 37

    Try This:

    Download am Image

    Start with Android 2.3.3

  • 7/26/2019 Cara cara Membuat Android

    38/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 38

    The layout

    The coding

    1. publicvoidHandleDownload(View v) {

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

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

    4. try{

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

    Toast.LENGTH_LONG).show();

    6. Bitmap imgResult = BitmapFactory.decodeStream((InputStream)

    7. newURL(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

  • 7/26/2019 Cara cara Membuat Android

    39/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 39

    The Result

    Now run it on

    Emulator API19

  • 7/26/2019 Cara cara Membuat Android

    40/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 40

    Try this: Download in

    the Android Thread

    Try this: Download in the Android Thread

    1. publicclassMainActivity extendsActionBarActivity {

    2. finalString url="http://crackberry.com/sites/crackberry.com/" +"files/styles/large/public/topic_images/2013/ANDROID.png";

    3. @Override4. protectedvoidonCreate(Bundle savedInstanceState) {

    5. super.onCreate(savedInstanceState);

    6. setContentView(R.layout.activity_main);

    7. }

    8. publicvoidHandleDownload(View v) {

    9. newmyDownloadThread().execute();10. Toast.makeText(getApplicationContext(), "is downloading...",

    Toast.LENGTH_LONG).show();

    11. }

  • 7/26/2019 Cara cara Membuat Android

    41/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 41

    Try this: Download in the Android Thread

    12.privateclassmyDownloadThread extendsAsyncTask {

    13. @Override

    14. protectedBitmap doInBackground(Void... arg0) {

    15. Bitmap imgResult = null;

    16. try{

    17. imgResult =BitmapFactory.decodeStream((InputStream) new

    URL(url).getContent());

    18. } catch(Exception e) {}19. returnimgResult;

    20. }

    Try this: Download in the Android Thread

    21. protectedvoidonPostExecute(Bitmapresult) {

    22. Toast.makeText(getApplicationContext(),

    "is displaying...",Toast.LENGTH_SHORT).show();

    23. ImageView imgView = (ImageView)findViewById(R.id.imageView1);

    24. imgView.setImageBitmap(result);

    25. }

    26. }

    27.}

  • 7/26/2019 Cara cara Membuat Android

    42/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 42

    (2014)

    Thread/AsynTask

    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.

  • 7/26/2019 Cara cara Membuat Android

    43/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 43

    Why use thread in Android?

    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

    NOTE!

    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.

  • 7/26/2019 Cara cara Membuat Android

    44/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 44

    Introduction

    AsyncTask is a generic class, it uses 3 types:

    AsyncTask.

    Paramsthe input. What you pass to the

    AsyncTask

    Progressif you have any updates, passed to

    onProgressUpdate()

    Resultthe output. What returns doInBackground()

    Example:private class MyTask extends AsyncTask { }

    OR

    private class MyTask2 extends AsyncTask { }

    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(Params)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.

  • 7/26/2019 Cara cara Membuat Android

    45/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 45

    Example

    Hello World! Become

    Downloading

    Then progressing

    values will appear

    Final msg, All Done!

    Example

    1. publicclassMainActivity extendsActivity {

    2. TextView tv;

    3. @Override

    4. publicvoidonCreate(Bundle savedInstanceState) {

    5. Super.onCreate(savedInstanceState);

    6. setContentView(R.layout.activity_main);

    7. tv= (TextView) findViewById(R.id.textView1);

    8. }

    9. publicvoidhandleAsynTask(View v) {

    10. // Starting the task. Pass an url as the parameter.

    11. newMyTask().execute("http://ahmadsuki.blogspot.com");

    12. }

    AsynTask

    class

    1stparam input for

    AsynTask class. Leave it

    blank if first param Void

  • 7/26/2019 Cara cara Membuat Android

    46/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 46

    Example

    13. privateclassMyTask extendsAsyncTask {14. @Override

    15. protectedvoidonPreExecute() {

    16. super.onPreExecute();

    17. tv.setText("Downloading...");

    18. }

    19. @Override

    20. protectedString doInBackground(String... params) {

    21. String url = params[0];

    22. // Dummy code

    23. for(inti = 0; i

  • 7/26/2019 Cara cara Membuat Android

    47/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 47

    Summary

    1. publicvoidhandleAsynTask(View v) {

    2. newMyTask().execute("http://ahmadsuki.blogspot.com");

    3. }

    4. privateclassMyTask extendsAsyncTask {

    5. protectedvoidonPreExecute() {

    6. }

    7. protectedString doInBackground(String... params) {

    8. publishProgress(i);

    9. return"All Done!";

    10. }

    11. protectedvoidonProgressUpdate(Integer... values) {

    12. }

    13. protectedvoidonPostExecute(String result) {

    14. }

    15. }

    Summary

    1. publicvoidhandleAsynTask(View v) {

    2. newMyTask().execute();

    3. }

    4. privateclassMyTask extendsAsyncTask {

    5. protectedvoidonPreExecute() {

    6. }

    7. protectedVoid doInBackground(Void... voids) {

    8. publishProgress(i);

    9. returnnull;

    10. }

    11. protectedvoidonProgressUpdate(Integer... values) {

    12. }

    13. //protectedvoidonPostExecute(String result) {

    14. //} NOT IMPLEMENTED

    15. }

  • 7/26/2019 Cara cara Membuat Android

    48/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 48

    Return to Downloading Case:

    Observe the Structure1. public class MainActivity extends ActionBarActivity {

    2. final String url = "http://crackberry.com/sites/crackberry.com/"

    3.

    4. @Override

    5. protected void onCreate(Bundle savedInstanceState) {

    6. }

    7. public void HandleDownload(View v) {

    8. new myDownloadThread().execute();

    9. }

    10. private class myDownloadThread extends AsyncTask {

    11. @Override12. protected BitmapdoInBackground(Void... arg0) {

    13. return imgResult;

    14. }

    15. protected void onPostExecute(Bitmapresult) {

    16. }

    17. }

    1

    2

    3

    Return to Downloading Case:

    Analysis Issues1. public class MainActivity extends ActionBarActivity {

    2. final String url = "http://crackberry.com/sites/crackberry.com/"

    3.

    4. @Override

    5. protected void onCreate(Bundle savedInstanceState) {

    6. }

    7. public void HandleDownload(View v) {

    8. new myDownloadThread().execute();

    9. }

    10. private class myDownloadThread extends AsyncTask {

    11. @Override

    12. protected BitmapdoInBackground(Void... arg0) {

    13. return imgResult;

    14. }

    15. protected void onPostExecute(Bitmapresult) {

    16. }

    17. }

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

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

    Toast.LENGTH_SHORT).show();

    ImageView imgView = (ImageView)

    findViewById(R.id. imageView1);

    imgView.setImageBitmap(result);

  • 7/26/2019 Cara cara Membuat Android

    49/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 49

    Return to Downloading Case:

    Analysis Issues1. public class MainActivity extends ActionBarActivity {

    2. final String url = "http://crackberry.com/sites/crackberry.com/"

    3.

    4. @Override

    5. protected void onCreate(Bundle savedInstanceState) {

    6. }

    7. public void HandleDownload(View v) {

    8. new myDownloadThread().execute();

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

    10. Toast.LENGTH_LONG).show();

    11. }

    12. private class myDownloadThread extends AsyncTask {

    13. @Override

    14. protected BitmapdoInBackground(Void... arg0) {

    15. return imgResult;

    16. }

    17. }

    Can we code this toast message in the AsyncTask

    class?

    Toast.makeText(getApplicationContext(), "is

    downloading...",

    Toast.LENGTH_LONG).show();

    Return to Downloading Case:

    Analysis Issues (Try This)

    Put the cursor inside

    AsyncTask class, choose

    menu source, then select

    Override/Implement

    Methods

  • 7/26/2019 Cara cara Membuat Android

    50/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 50

    Return to Downloading Case:

    Analysis Issues (passing data through 1stparam)

    1. publicvoidHandleDownload(View v) {

    2. String url = http://crackberry.com/sites/crackberry.com/+"files/styles/large/public/topic_images/2013/ANDROID.png";

    3. newmyDownloadThread().execute(url);4. }

    5. privateclassmyDownloadThread extendsAsyncTask {

    6. @Override

    7. protectedBitmap doInBackground(String... arg0) {8. Bitmap imgResult = null;

    9. try{

    10. imgResult = BitmapFactory.decodeStream((InputStream) new

    URL(arg0[0]).getContent());

    Return to Downloading Case:

    Analysis Issues (passing data through 1stparam)

    1. privateclassmyDownloadThread extendsAsyncTask {

    2. @Override

    3. protectedBitmap doInBackground(String... arg0) {

    4. try{

    5. int sizeFile= new URL(arg0[0]).openConnection().getContentLength();

    6. publishProgress(sizeFile);

    7. imgResult = BitmapFactory.decodeStream((InputStream) new

    URL(arg0[0]).getContent());

    8. } catch(Exception e) {}

    9. @Override

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

    11. super.onProgressUpdate(values);

    12. Toast.makeText(getApplicationContext(), "The file size is =

    "+values[0], Toast.LENGTH_LONG).show();

    13. }

    http://crackberry.com/sites/crackberry.com/http://crackberry.com/sites/crackberry.com/http://crackberry.com/sites/crackberry.com/http://crackberry.com/sites/crackberry.com/
  • 7/26/2019 Cara cara Membuat Android

    51/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 51

    (2014)

    EXTRA: DOWNLOAD IMAGE FROMTHE INTERNET

    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:

  • 7/26/2019 Cara cara Membuat Android

    52/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 52

    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

    Downloading Image: Example

    Try to do this application:

    (Use AsyncTask for the downloading task)

  • 7/26/2019 Cara cara Membuat Android

    53/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 53

    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.

    Downloading Image: Example

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

    1. Create the main layout (xml) for your

    Activity. It should have:

    A TextView for the titleA 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

  • 7/26/2019 Cara cara Membuat Android

    54/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 54

    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);

    }

    *ImageDownloaderis the name of

    our AsyncTask

    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 {

    }

    Downloading Image: Example

  • 7/26/2019 Cara cara Membuat Android

    55/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 55

    4. Override all the fourmethods in your AsyncTask , starting with the

    onPreExecute() method.

    - This is for initialising purpose

    @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();}

    onPreExecute() method:

    Downloading Image: Example

    5. Override the doInBackground () method.

    - This is for the background task done by the background thread

    @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;

    }

    doInBackground() method:

    Downloading Image: Example

  • 7/26/2019 Cara cara Membuat Android

    56/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 56

    6. Override the onProgressUpdate () method.

    - This is to show download progress in the ProgressBar and

    TextView on main UI thread

    @Override

    protected void onProgressUpdate(Integer... values) {

    pb.setProgress(values[0]);

    percent.setText(values[0] + "%");

    }

    onProgressUpdate() method:

    Downloading Image: Example

    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)

    @Override

    protected void onPostExecute(Bitmap result) {

    img.setImageBitmap(result);

    Toast.makeText(LoadImageAsyncTaskActivity.this,

    "download complete", Toast.LENGTH_SHORT).show();

    }

    onPostExecute() method:

  • 7/26/2019 Cara cara Membuat Android

    57/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 57

    8. Define the loadImageFromNetwork () method.

    - This method do the actual work of loading the image from the

    given url address

    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;

    }

    }

    loadImageFromNetwork() method:

    Downloading Image: Example

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

  • 7/26/2019 Cara cara Membuat Android

    58/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 58

    (2014)

    DOWNLOAD TEXT FILE FROM THEINTERNET

    (2014)

    Try This: Download a Text File

  • 7/26/2019 Cara cara Membuat Android

    59/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 59

    (2014)

    Try This: Download a Text File

    1. publicvoiddownloadTextFile(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)

    Try This: Download a Text File

    7. try{

    8. //get the TextFile as an inputstream

    9. inputStream = newDefaultHttpClient().execute(new

    HttpGet(url)).getEntity().getContent();

    10. // convert inputstream to BufferedReader

    11. BufferedReader reader = newBufferedReader(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);

  • 7/26/2019 Cara cara Membuat Android

    60/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 60

    (2014)

    (2014)

    Try This: Download a Text File

    (alternative codingwithout thread yet)

    1. publicclassMainActivity extendsActionBarActivity {

    2. InputStream inputStream= null;

    3. String theString= "";

    4. finalString url= "http://textfiles.com/100";

    5. @Override

    6. protectedvoidonCreate(Bundle savedInstanceState) {

    7. super.onCreate(savedInstanceState);

    8. setContentView(R.layout.activity_main);

    9. }

  • 7/26/2019 Cara cara Membuat Android

    61/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 61

    (2014)

    Try This: Download a Text File

    (alternative codingwithout thread yet)

    10. publicvoiddownloadTextFile(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)

    Try This: Download a Text File

    (alternative codingwithout thread yet)

    17.publicString readFile (String url){

    18.try{

    19. inputStream= newDefaultHttpClient().execute(new

    HttpGet(url)).getEntity().getContent();

    20. BufferedReader reader = newBufferedReader(newInputStreamReader(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.returntheString;

    28.}

  • 7/26/2019 Cara cara Membuat Android

    62/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 62

    (2014)

    Hide & UnHide the EditView

    (2014)

    Hide & UnHide the EditView

    1.

  • 7/26/2019 Cara cara Membuat Android

    63/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 63

    (2014)

    Hide & UnHide the EditView

    1. publicvoiddownloadTextFile(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)

    Try This:

    Download a Text File in AsyncTask

  • 7/26/2019 Cara cara Membuat Android

    64/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 64

    (2014)

    Try This:

    Download a Text File in AsyncTask

    1. publicvoiddownloadTextFile(View v) {

    2. TextView tv = (TextView) findViewById(R.id.textView1);

    3. tv.setText("URL: "+ url);

    4. newMyDownTF().execute();5. }

    6. privateclassMyDownTF extendsAsyncTask{

    7. @Override

    8. protectedString doInBackground(Void... params) {

    9. // TODOAuto-generated method stub10. String result = readFile(url);

    11. returnresult;

    12. }

    (2014)

    Try This:

    Download a Text File in AsyncTask

    13. @Override

    14. protectedvoidonPostExecute(String strResult) {

    15. // TODOAuto-generated method stub

    16. super.onPostExecute(strResult);17. EditText et = (EditText) findViewById(R.id.editText1);

    18. et.setVisibility(et.VISIBLE);

    19. et.setText(strResult);

    20. }

  • 7/26/2019 Cara cara Membuat Android

    65/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 65

    (2014)

    Try This: Download a Text File with

    ProgressUpdate (line by line progress display)

    (2014)

    Try This: Download a Text File with

    ProgressUpdate (line by line progress display)

    1. publicvoiddownloadTextFile(View v) {

    2. tv= (TextView) findViewById(R.id.textView1);

    3. newMyDownTF().execute();

    4. }

    5. privateclassMyDownTF extendsAsyncTask{

  • 7/26/2019 Cara cara Membuat Android

    66/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 66

    (2014)

    Try This: Download a Text File with

    ProgressUpdate (line by line progress display)

    6. @Override

    7. protectedString doInBackground(Void... params) {8. String theString = "";

    9. try{

    10. //get the TextFile as an inputstream

    11. inputStream= newDefaultHttpClient().execute(newHttpGet(url)).getEntity().getContent();

    12. // convert inputstream to BufferedReader

    13. BufferedReader reader = newBufferedReader(newInputStreamReader(inputStream));

    14. //Read from bufferedReader to String

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

    16. theString += line;

    17. publishProgress(line);18. }19. inputStream.close();

    20. } catch(Exception e) {

    21. Log.d("InputStream", e.getLocalizedMessage());

    22. }

    23. returntheString;

    24. }

    (2014)

    Try This: Download a Text File with

    ProgressUpdate (line by line progress display)

    25.@Override

    26.protectedvoidonProgressUpdate(String... values) {

    27.// TODOAuto-generated method stub

    28. super.onProgressUpdate(values);

    29. tv.setText("Reading the file line by line:\n "+

    values[0]);

    30.}

  • 7/26/2019 Cara cara Membuat Android

    67/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 67

    (2014)

    Try This:

    Download a WebPage File

    (2014)

    Try This:

    Download a WebPage File

    Start by changing the

    previous layout screen by

    embedding a WebViewobject (remove the

    EditText).

  • 7/26/2019 Cara cara Membuat Android

    68/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 68

    (2014)

    Try This:

    Download a WebPage File

    1. @Override

    2. protectedvoidonPostExecute(String

    strResult) {

    3. // TODOAuto-generated method stub

    4. super.onPostExecute(strResult);

    5. WebView wv = (WebView)

    findViewById(R.id.webView1);

    6. wv.loadData(strResult, "text/html", null);7. }

    (2014)

    Try This: Download a WebPage File

    with a Dynamic URL

  • 7/26/2019 Cara cara Membuat Android

    69/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 69

    (2014)

    Try This: Download a WebPage File

    with a Dynamic URL

    1. publicvoiddownloadTextFile(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. newMyDownTF().execute(strURL);

    7. }

    8. privateclassMyDownTF extendsAsyncTask{

    (2014)

    Try This: Download a WebPage File

    with a Dynamic URL

    9. @Override

    10. protectedString doInBackground(String... params) {11. // TODOAuto-generated method stub

    12. String theString = "";

    13. String theURL = params[0];14. try{

    15. //get the TextFile as an inputstream

    16. inputStream= newDefaultHttpClient().execute(new

    HttpGet(theURL)).getEntity().getContent();17. // convert inputstream to BufferedReader

    18. BufferedReader reader = newBufferedReader(newInputStreamReader(inputStream));

    19. //Read from bufferedReader to String

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

    21. theString+= line;22. //publishProgress(line);

    23. }

    24. inputStream.close();

    25. } catch(Exception e) {

    26. Log.d("InputStream", e.getLocalizedMessage());

    27. }

    28. returntheString;29. }

  • 7/26/2019 Cara cara Membuat Android

    70/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 70

    (2014)

    Accessing Web Service

    (2014)

    Access Database Server:

    Old ArchitectureCentralized System

  • 7/26/2019 Cara cara Membuat Android

    71/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 71

    (2014)

    Access Database Server:

    Old ArchitectureClient/Server System

    (2014)

    Access Database Server:

    Web ArchitectureWeb Server

  • 7/26/2019 Cara cara Membuat Android

    72/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 72

    (2014)

    Access Database Server:

    Web ArchitectureWeb Service

    (2014)

    Access Database Server:

    Web Service ArchitectureAndroid

  • 7/26/2019 Cara cara Membuat Android

    73/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 73

    (2014)

    JSON (JavaScript Object Notation)

    very light weight

    structured

    easy to parse

    human readable

    the best alternative

    to XML

    (2014)

    JSON (JavaScript Object

    Notation)

    square bracket ([) representsa JSON array

    curly bracket ({) represents a

    JSON object A JSON object contains a keythat is just a string. Pairs ofkey/value make up a JSONobject

    Each key has a value thatcould be string , integer ordouble etc.

  • 7/26/2019 Cara cara Membuat Android

    74/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 74

    (2014)

    JSON Web Service Programming

    3 main steps:

    Download JSON file

    Parsing

    Display (formatting)

    (2014)

    JSON Web Service Programming

    Step 1: Download a JSON File

    From our previous

    download text file app,

    just change it to the newJSON URL, e.g.

    final String url =

    "http://kis.kedah.gov.my/

    majlis/majlis.json";

  • 7/26/2019 Cara cara Membuat Android

    75/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 75

    (2014)

    JSON Web Service Programming Exercise

    Step 1: Download this JSON File

    (2014)

    JSON Web Service Programming

    Step 2: Parsing the JSON File

  • 7/26/2019 Cara cara Membuat Android

    76/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 76

    (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)

    JSON Web Service Programming

    Step 2: Parsing the JSON File

    1. publicvoidparsingJSON(String strJSON) {

    2. // TODOAuto-generated method stub

    3. JSONObject jsonObj;

    4. String strDate, strTime;

    5. try{

    6. jsonObj = newJSONObject(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.}

  • 7/26/2019 Cara cara Membuat Android

    77/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 77

    (2014)

    JSON Web Service Programming

    Step 3: Display the Output/Data

    (2014)

    JSON Web Service Programming

    Step 3: Display the Output/Data

    1. JSONObject jsonObj;

    2. String strDate="", strTime="";

    3. try{

    4. jsonObj = newJSONObject(strJSON);

    5. strDate = jsonObj.getString("date");

    6. strTime = jsonObj.getString("time");

    7. } catch(JSONException e) {}

    8. 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);

  • 7/26/2019 Cara cara Membuat Android

    78/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 78

    (2014)

    JSON Web Service Programming

    Parsing the JSON File with Array Object []

    (2014)

    JSON Web Service Programming

    Parsing the JSON File with Array Object []

    1. publicvoidparsingJSON(String strJSON) {

    2. // TODOAuto-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 = newJSONObject(strJSON);

  • 7/26/2019 Cara cara Membuat Android

    79/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 79

    (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(inti = 0; i 0) {

    byte[] b = new byte[4096];

    n = in.read(b);

    if (n > 0)

    out.append(new String(b, 0, n));

    }return out.toString();

    }

    getResultFromEntity() method:

    Example : A Simple Contact Rest-based Application

  • 7/26/2019 Cara cara Membuat Android

    89/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 89

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

  • 7/26/2019 Cara cara Membuat Android

    90/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 90

    Intro - II

    One of the most common functionalities requiredin mobile applications is to call a web service toretrieve data.

    This process involves requesting the web servicewith parameters, receiving the response andparsing it to obtain data.

    Today the most common web services types areSOAPand REST.

    Android does not provide a built in SOAP client,there are many third party libraries that can beused

    Intro (REST)

    REST (or RESTful) Services are an increasinglycommon paradigm for creating web servicesbecause 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 simpleto consume client-server architecture over HTTP.

    Among the most popular formats are JSON(JavaScript Object Notation) and XML.

  • 7/26/2019 Cara cara Membuat Android

    91/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 91

    Web Service with JSON

    Simple JSON data:{

    "data" : {

    "id": "1234",

    "category" : "my_category",

    "name" : "my_name"

    }

    }

    In order to parse the JSON data:

    {

    "data" : {

    "id": "1234",

    "category" : "my_category",

    "name" : "my_name"

    }

    }

    import org.json.JSONException;

    import org.json.JSONObject;

    Web Service with JSON - II1. String id;

    2. String name;

    3. String category;

    4. String jsonString = "{\"data\" : {\"id\": "1234","category" :

    Android","name" : Ahmad Suki"}}";

    5. try{6. JSONObject jsonObj= new JSONObject(jsonString);

    7. JSONObject dataObj = jsonObj.getJSONObject("data");

    8. id = dataObj.getString("id");

    9. category = dataObj.getString("category");

    10. name = dataObj.getString("name");

    11. }

    12. catch(JSONException e) {

    13. }

  • 7/26/2019 Cara cara Membuat Android

    92/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 92

    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 ite.g. how to obtain only the names and phone numbers from the message

    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

  • 7/26/2019 Cara cara Membuat Android

    93/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 93

    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();

    }

    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");

  • 7/26/2019 Cara cara Membuat Android

    94/95

    Anroid Application Development (Series II) 3-5hb November 2014

    ASMATT ([email protected]) 94

    Parsing JSON message

    5. After fetching the contact array, add a for loop to iterate through the

    contacts:

    for (int t=0; t

  • 7/26/2019 Cara cara Membuat Android

    95/95

    Anroid Application Development (Series II) 3-5hb November 2014

    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!");