+ All Categories
Home > Documents > Modul Android 1

Modul Android 1

Date post: 05-Jul-2018
Category:
Upload: ganjar
View: 221 times
Download: 0 times
Share this document with a friend

of 77

Transcript
  • 8/15/2019 Modul Android 1

    1/77

    DAFTAR ISI 

    Halaman Judul .......................................................................................i 

    Halaman Penulis ...................................................................................ii Kata Pengantar  .....................................................................................iii 

    Daftar Isi  ..............................................................................................v 

    Pertemuan 1 Pengenalan Android ..........................................................1 

    Pertemuan 2 Membuat Toast, List Dialog, Alert Dialog ..........................9 

    Pertemuan 3 Membuat Intent  ..............................................................14 

    Pertemuan 4 Membuat Aplikasi Kalkulator  ..........................................25 

    Pertemuan 5 SQL Lite ........................................................................36 Pertemuan 6 Pembuatan Projet ............................................................47 

    Pertemuan 7 Membuat Aplikasi Dengan Php Mysql (Relasi Tabel) 

    Part I ............................................................................. 76 

    Pertemuan 8 Membuat Aplikasi Dengan Php Mysql (Relasi Tabel) 

    Part II ............................................................................76 

  • 8/15/2019 Modul Android 1

    2/77

    Modul praktikum Pemrograman Mobile 

    PERTEMUAN 1 Bagian ini akan menjelaskan tentang : 

      Konsep umum android

      Proses instalasi Eclipse

     

    Membuat Program Pertama..........................................................................................................................................................

    PENGENALAN ANDROID Android adalah sistem operasi untuk telepon seluler yang berbasis

    Linux.Android menyediakan platform yang bersifat open source bagi para pengembang

    untuk menciptakan sebuah aplikasi.Awalnya, Google Inc. mengakuisi Android Inc. yang

    mengembangkan software untuk ponsel yang berada di Palo Alto, California Amerika

    Serikat. Kemudian untuk mengembangkan Android, dibentuklah Open Handset Alliance,

    yaitu konsorsium dari 34 perusahaan hardware, software, dan telekomunikasi, termasuk

    Google, HTC, Intel, Motorola, Qualcomm, T-Mobile, dan Nvidia. Sebuah Activity biasanya ditampilkan dalam satu screen sebagai bagian

    komponen dari View (yang terdiri dari komponen UI, widget atau control), yang bertugas

    melakukan interaksi dengan user untuk melakukan sebuah task tunggal (misalnya, melihat

    informasi, mengedit data, atau memasukkan data). Sebuah aplikasi Android biasanya memiliki satu atau lebih Activity. Salah satu

    Activity ditandai sebagai startup activity, yang pada gilirannya memulai activity

     berikutnya, melalui sebuah intent. Untuk membuat suatu activity, kita melakukan extend

    terhadap class android.app.Activity, dan melakukan override beberapa method, khususnya

    method OnCreate(). Kita bisa mengatur konten view dari activity secara bahasa pemrograman java atau juga

     bisa melalui kode layout file XML Daur hidup sebuah activity diatur melalui method call-back, yang di definisikan pada class

    dasar Activity pada gambar 1.1. tentang siklus hidup android. 

    INSTALASI ECLIPSE, JDK, ANDROID DEVELOPMENT TOOLS Sebelum membangun aplikasi android, diperlukan tiga buah file yang harus diinstal.

    Ketiga buah file tersebut dapat diunduh di  http://developer.android.com/sdk/index.html 

    1. 

    Eclipse2.  ADT Plugin

    3.  SDK Manager

    Ketiga file tersebut sudah include didalam satu folder. Saat mendownload silahkan

    sesuaikan dengan tipe sistem operasi komputer. Kemudian install JDK (Java Development

    Kit) minimal versi 7 dan install di komputer. Berikut ini adalah langkah-langkah instalasi : 

    http://developer.android.com/sdk/index.htmlhttp://developer.android.com/sdk/index.htmlhttp://developer.android.com/sdk/index.html

  • 8/15/2019 Modul Android 1

    3/77

    Modul praktikum Pemrograman Mobile 

    Gambar 1.1 : Siklus Hidup Android 

    1.  Instal JDK, Awal Instalasi pada gambar 1.2. Silahkan Klik Next hingga proses

    instalasi selesai.

    Gambar 1.2 : instalasi Java Development Kit 2.  Selanjutnya kita akan membuat Android Virtual Device pada gambar 1.3. Masuk

    ke folder adt-bundle, kemudian klik SDK manager.exe. jika terdapat

     pemberitahuan error, abaikan saja.

  • 8/15/2019 Modul Android 1

    4/77

    Modul praktikum Pemrograman Mobile 

    Gambar 1.3 : Tampilan SDK Manager  3.  Pilih Tools lalu Manage AVDs pada gambar 1.4

    Gambar 1.4 : Proses Manajemen AVD 

  • 8/15/2019 Modul Android 1

    5/77

    Modul praktikum Pemrograman Mobile 

    4.  Selanjutnya adalah proses konfigurasi emulator android pada gambar 1.5, klik

     New

    Gambar 1.5 : membuat Android Virtual Device 5.  Isi sesuai dengan gambar 1.6. Untuk Internal Storage ubah nilainya menjadi

    500MiB. Kemudian Klik OK

    Gambar 1.6 : konfigurasi AVD 

  • 8/15/2019 Modul Android 1

    6/77

    Modul praktikum Pemrograman Mobile 

    6.  Setelah itu, klik start untuk menjalankan emulator yang telah dibuat. Android

    Device Virtual gambar 1.7 telah selesai dibuat.

    Gambar 1.7 : menjalankan AVD PROGRAM PERTAMA Pada pertemuan pertama. Kita akan membuat program awal sebagai pemanasan. Berikut

    ini langkah-langkah pembuatan aplikasi android pertama. 1.  Jalankan Eclipse pada gambar 1.7, Kemudian Pilih File > New > Android

    Application Project

    Gambar 1.7 : membuat project pertama 

  • 8/15/2019 Modul Android 1

    7/77

    Modul praktikum Pemrograman Mobile 

    2.  Kemudian isi seperti gambar 1.2.

    Gambar 1.8 : memberi nama project 3.

     

    Buka file main.xml didalam package res > layout. Gambar 1.9

    Gambar 1.9 : hierarki package 

  • 8/15/2019 Modul Android 1

    8/77

    Modul praktikum Pemrograman Mobile 

    4.  Ganti kode di main.xml seperti dibawah ini.    

    Tampilan pada Graphical Layout pada gambar 1.10 

    Gambar 1.10 : tampilan graphical layout 

  • 8/15/2019 Modul Android 1

    9/77

    Modul praktikum Pemrograman Mobile 

    5.  Kemudian ubah kode di activity main.java seperti dibawahini. package com.example.projectpertama;import android.os.Bundle;

    import android.app.Activity;

     public class Main extends Activity implements OnClickListener{ TextView txt1;Button btn1;

    @Override protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);setContentView(R.layout.main);txt1 = (TextView) findViewById(R.id.txt1); btn1 = (Button) findViewById(R.id.btn1); btn1.setOnClickListener(this);

    }@Override public void onClick(View arg0) {

    // TODO Auto-generated methodstub txt1.setText("Mantep kan");

    } } 

    6.  Jalankan aplikasi dengan cara klik kanan package > pilih Run As > Android

    Application Project, atau dengan shortcut CTRL + F11.

    7. 

    Aplikasi dapat didownload langsung ke perangkat android. File

    ProjectPertama.apk terletak di folder ProjectPertama/bin.

  • 8/15/2019 Modul Android 1

    10/77

    Modul praktikum Pemrograman Mobile 

    PERTEMUAN 2 Bagian ini akan menjelaskan tentang : 

      Menampilkan gambar

      Membuat dialog interaktif dengan toast, list, dan alert

    ..........................................................................................................................................................MEMBUAT TOAST, LIST DIALOG, ALERT DIALOG Pada pertemuan kedua kita akan membuat kotak dialog sebagai sarana interaktif antara

    aplikasi dengan pengguna. Pada aplikasi ini kita akan mengimplementasikan 3 macam

    dialog, antara lain : •  Toast

    •  List dialog

    •  Alert dialog

    Untuk membuat aplikasi ini. Silahkan membuat project baru seperti pada gambar dibawah

    ini. 1.  Membuat project dengan nama alertlist pada gambar 2.1

    Gambar 2.1 : membuat project alertlist 

  • 8/15/2019 Modul Android 1

    11/77

    Modul praktikum Pemrograman Mobile 

    2.  Modifikasi layout di activitymain.xml menjadi seperti dibawah ini

     

     

     

     

     

     

    10 

  • 8/15/2019 Modul Android 1

    12/77

    Modul praktikum Pemrograman Mobile 

    3.  Modifikasi file AlertListActivity.java seperti dibawah inipackage com.example.alertlist;

    import android.os.Bundle;

    import android.app.Activity;

    public class AlertListActivity extends Activity implements OnClickListener {Button pesantoast;

    Button keluar;

    Button tampillist;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_alert_list);

    pesantoast = (Button)findViewById(R.id.pesantoast);

    pesantoast.setOnClickListener(this);

    tampillist = (Button)findViewById(R.id.tampillist);

    tampillist.setOnClickListener(this);

    keluar = (Button)findViewById(R.id.keluar);

    keluar.setOnClickListener(this);

    }

    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.

    getMenuInflater().inflate(R.menu.activity_alert_list,

    menu); return true; } @Override public void onClick(View arg0)

    { if(arg0 == pesantoast){ Toast.makeText(getBaseContext(), "Anda Memilih Toast",

    Toast.LENGTH_SHORT).show();  } else if (arg0 == keluar){ 

    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setMessage("Apakah Anda ingin keluar ?").setCancelable(false) .setPositiveButton("Ya", new DialogInterface.OnClickListener() {

    @Override public void onClick(DialogInterface arg0, int arg1)

    { AlertListActivity.this.finish(); // TODO Auto-generated method stub } 

    } ).setNegativeButton("Tidak", new DialogInterface.OnClickListener() { 

    11 

  • 8/15/2019 Modul Android 1

    13/77

    Modul praktikum Pemrograman Mobile 

    @Override public void onClick(DialogInterface arg0, int arg1)

    { arg0.cancel(); // TODO Auto-generated method stub 

    } } ).show(); 

    } else if (arg0 == tampillist){ 

    final CharSequence[] item = {"Jeruk", "Jambu", "Nangka",

    "Nanas"}; AlertDialog.Builder builder = new

    AlertDialog.Builder(this); builder.setTitle("Pilih Minuman"); builder.setItems(item, new DialogInterface.OnClickListener()

    { @Override 

    public void onClick(DialogInterface arg0, int arg1) {Toast.makeText(getBaseContext(), item[arg1], Toast.LENGTH_SHORT).show(); // TODO Auto-generated method stub 

    } }).show(); 

    } // TODO Auto-generated method stub } } 

    4. 

    Jalankan aplikasi dan lihat hasilnya.

    Gambar 2.2 : list dialog 

    12 

  • 8/15/2019 Modul Android 1

    14/77

    Modul praktikum Pemrograman Mobile 

    Gambar 2.3 : alert dialog 

    13 

  • 8/15/2019 Modul Android 1

    15/77

    Modul praktikum Pemrograman Mobile 

    PERTEMUAN 3 Pada bagian ini, kita akan mempelajari : 

      Intent untuk memanggil activity

      Penerapan intent pada aplikasi konversi berat badan

    ..........................................................................................................................................................MEMBUAT INTENT Pada pertemuan ketiga kita akan belajar membuat intent sederhana. Inti dari sebuahaplikasi ada 3, yaitu activity, service dan broadcast. Intent digunakan untuk memanggil

    activity, memanggil service, atau melakukan broadcast. Pada bagian ini, kita akan memahami intent paling sederhana yaitu memanggil activitylain. 

    1.  Buat project dengan nama IntentPertama

    Gambar 3.1 : membuat project intentpertama 2.  Modifikasi activity_pertama.xml seperti dibawah ini

  • 8/15/2019 Modul Android 1

    16/77

    Modul praktikum Pemrograman Mobile 

    android:layout_height="match _parent"  

    android:orientation="vertical"  

    tools:context=".ActivityPertama"  > 

       

    3.  Modifikasi ActivityPertama.java seperti dibawah ini

    package com.example.intentpertama;

    import android.os.Bundle;

    import android.app.Activity;

    public class ActivityPertama extends Activity {

    @Override

    protected void onCreate(Bundle savedInstanceState)

    { super.onCreate(savedInstanceState);setContentView(R.layout.activity_pertama);

    final Button button1 = (Button) findViewById(R.id.button1);

    button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { 

    Intent myintent = new Intent(button1.getContext(),

    ActivityKedua.class); 

    startActivityForResult(myintent, 0); //TODO Auto-generated method stub } 

    }); } 

    15 

  • 8/15/2019 Modul Android 1

    17/77

    Modul praktikum Pemrograman Mobile 

    4.  Buat activity kedua seperti gambar 3.2.

    Gambar 3.2 : membuat activity kedua 5.  Modifikasi activity_kedua.xml seperti dibawah ini

     

     

     

    6.  Modifikasi ActivityKedua.java seperti dibawah

    ini package com.example.intentpertama;

    import android.os.Bundle;

    import android.app.Activity;

    import android.content.Intent;

    import android.view.Menu;

    import android.view.View;

    16 

  • 8/15/2019 Modul Android 1

    18/77

    Modul praktikum Pemrograman Mobile 

    import android.widget.Button; public class ActivityKedua extends Activity {

    @Override 

    protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_kedua); Button back = (Button)findViewById(R.id.back);

    back.setOnClickListener(new View.OnClickListener()

    { @Override public void onClick(View arg0) {

    Intent intent = new Intent();

    setResult(RESULT_OK,

    intent); finish(); // TODO Auto-generated method stub 

    } }); 

    } }

    7.  Jalankan aplikasi seperti gambar 3.3

    Gambar 3.3 : hasil aplikasi intent sederhana 

    LATIHAN 1 MEMBUAT KONVERSI BERAT BADAN Aplikasi konversi berat badan ini menggunakan dua buah activity. Activity pertama berisi

    inputan nama, username, dan button. Activity kedua berisi textfield dan button. 1.  Buat project baru dengan nama BeratBadan

    17 

  • 8/15/2019 Modul Android 1

    19/77

    Modul praktikum Pemrograman Mobile 

    Gambar 3.4 : membuat project beratbadan 2.  Modifikasi activity_main.xml berikut 

     

  • 8/15/2019 Modul Android 1

    20/77

    Modul praktikum Pemrograman Mobile 

    android:layout_height="wrap_content"  

    android:ems="10"  > 

      

      

    3. 

    Modifikasi mainactivity.java seperti dibawahini package com.example.latihan1;

    import android.os.Bundle;

    import android.app.Activity;

    public class MainActivity extends Activity implements

    android.view.View.OnClickListener {

    EditText username, password;

    Button login;

    String user = "yuni", pass = "12345";

    @Override

    protected void onCreate(Bundle savedInstanceState)

    { super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    username = (EditText)findViewById(R.id.username);

    password = (EditText)findViewById(R.id.password);

    login = (Button)findViewById(R.id.login); 

    19 

  • 8/15/2019 Modul Android 1

    21/77

    Modul praktikum Pemrograman Mobile 

    login.setOnClickListener(this); } @Override 

    public boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.activity_main,

    menu); return true; } 

    @Override public void onClick(View arg0) {

    try{ if(arg0.getId() == R.id.login){ 

    Intent i = new Intent(getBaseContext(),

    Main2Activity.class); startActivityForResult(i, 0); } 

    } catch (Exception e){ Toast.makeText(getBaseContext(), "Anda Tidak Berhak Masuk",

    Toast.LENGTH_LONG).show(); } 

    } } 

    4.  Modifikasi activity_main2.xml seperti dibawah ini

     

     

  • 8/15/2019 Modul Android 1

    22/77

    Modul praktikum Pemrograman Mobile 

    android:ems="10"  

    android:inputType="number"  > 

     

      

         

    5.  Modifikasi Main2Activity.java seperti dibawah

    ini package com.example.latihan1;

    import android.os.Bundle;

    21 

  • 8/15/2019 Modul Android 1

    23/77

    Modul praktikum Pemrograman Mobile 

    import android.app.Activity; public class Main2Activity extends Activity implements OnClickListener {

    Button hasil, back, exit; 

    EditText berat, tinggi;TextView output;

    @Override protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main2); berat

    = (EditText)findViewById(R.id.berat); tinggi =

    (EditText)findViewById(R.id.tinggi); output =

    (TextView)findViewById(R.id.output); hasil =

    (Button)findViewById(R.id.hasil); back = (Button)findViewById(R.id.back);

    exit = (Button)findViewById(R.id.exit);

    hasil.setOnClickListener(this);

    back.setOnClickListener(this);

    exit.setOnClickListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.activity_main2,

    menu); return true; } @Override public void onClick(View v) { 

    int angka = 110; //angka ideal int angka1 = Integer.parseInt(berat.getText().toString());

    //merubah dari string edittext ke integer 

    int angka2 = Integer.parseInt(tinggi.getText().toString());int ideal = angka2 - angka1; //berat badan ideal int ideal2 = angka2 - angka; //berat badan yang disarankan

    try{ if(v.getId() == R.id.hasil){ //button

    hasil if(ideal == 110){ output.setText("Berat Badan Anda

    Ideal"); }else if (ideal > 110){ output.setText("Anda Kurus"); 

    22 

  • 8/15/2019 Modul Android 1

    24/77

    Modul praktikum Pemrograman Mobile 

    }else{ output.setText("Anda Gemuk, berat Anda "+angka1+" Tinggi

    Anda "+angka2+" Seharusnya Berat badan anda "+ideal2); } }else if (v.getId() == R.id.exit){ 

    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setMessage("Apakah Anda Ingin Keluar ?") .setCancelable(false).setPositiveButton("OK",

    new DialogInterface.OnClickListener() { @Override 

    public void onClick(DialogInterface arg0, int arg1) {

    Main2Activity.this.finish(); 

    } }) .setNegativeButton("NO", new DialogInterface.OnClickListener() {

    @Override public void onClick(DialogInterface dialog, int which)

    { dialog.cancel(); } 

    }).setNeutralButton("Cancel", new DialogInterface.OnClickListener() {

    @Override public void onClick(DialogInterface dialog, int which) {

    dialog.dismiss(); } 

    }).show(); }else if (v.getId() == R.id.back){ Intent i = new Intent(getBaseContext(), MainActivity.class);

    startActivityForResult(i, 0); }else{ 

    Toast.makeText(getBaseContext(), "Masukkan Berat danTinggi Badan Anda", Toast.LENGTH_SHORT).show(); 

    output.setText("Masukkan Angka Dulu"); } 

    }catch(Exception e){ Toast.makeText(getBaseContext(), "Hahaha", Toast.LENGTH_SHORT).show(); 

    } } } 

    23 

  • 8/15/2019 Modul Android 1

    25/77

    Modul praktikum Pemrograman Mobile 

    6.  Jalankan aplikasi seperti gambar 3.6

    Gambar 3.6 : hasil aplikasi konversi berat badan 

    24 

  • 8/15/2019 Modul Android 1

    26/77

    Modul praktikum Pemrograman Mobile 

    PERTEMUAN 4 Pada bagian ini, kita akan mempelajari : 

      Membuat aplikasi kalkulator sederhana

      Pengenalan Autocomplete

    ..........................................................................................................................................................MEMBUAT APLIKASI KALKULATOR  

    1.  Buat project dengan nama kalkulator

    Gambar 4.1 : membuat aplikasi kalkulator  2.  Modifikasi main.xml seperti pada gambar 4.2.

    Gambar 4.2 : tampilan main.xml pada activity 1 

    25 

  • 8/15/2019 Modul Android 1

    27/77

    Modul praktikum Pemrograman Mobile 

    3.  Modifikasi mainactivity.java seperti dibawah

    ini package com.example.hitung_sederhana;

    import android.os.Bundle;

    import android.app.Activity;

    import android.content.Intent;

    public class MainActivity extends Activity implements OnClickListener {

    EditText a, b, c;

    Button tambah, kurang, kali, bagi, next;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    a = (EditText) findViewById(R.id.a); b= (EditText) findViewById(R.id.b); c =

    (EditText) findViewById(R.id.c);

    tambah = (Button) findViewById(R.id.tambah);

    kurang = (Button) findViewById(R.id.kurang); kali

    = (Button) findViewById(R.id.kali);

    bagi = (Button) findViewById(R.id.bagi);

    next = (Button)findViewById(R.id.next);

    tambah.setOnClickListener(this); kurang.setOnClickListener(this); kali.setOnClickListener(this); bagi.setOnClickListener(this); next.setOnClickListener(this); 

    } @Override public void onClick(View v) { 

    int angka1 = Integer.parseInt(a.getText().toString());int angka2 = Integer.parseInt(b.getText().toString());

    int hasil = angka1 + angka2; int hasil2 = angka1 - angka2;

    int hasil3 = angka1 * angka2;

    float hasil4 = angka1 / angka2;

    try { if (v.getId() == R.id.tambah) { 

    26 

  • 8/15/2019 Modul Android 1

    28/77

    Modul praktikum Pemrograman Mobile 

    c.setText(Integer.toString(hasil)); } else if (v.getId() == R.id.kurang) {

    c.setText(Integer.toString(hasil2));

    } else if (v.getId() == R.id.kali) {

    c.setText(Integer.toString(hasil3));

    } else if (v.getId() == R.id.bagi){

    c.setText(Float.toString(hasil4));

    } else {

    Intent i = new Intent(getBaseContext(), MainActivity2.class);

    startActivityForResult(i, 0); } 

    } catch (Exception e) {

    Toast.makeText(getBaseContext(), "Salah", Toast.LENGTH_LONG).show();

    c.setText("Tak Terhingga ~"); } // ketiga.settext(string.valueof(hasil)).tostring()); 

    } } 

    4.  Modifikasi main2.xml

     

     

  • 8/15/2019 Modul Android 1

    29/77

    Modul praktikum Pemrograman Mobile 

    android:layout_marginTop="40dp"  

    android:text="Back"  />  

    5. 

    Modifikasi mainactivity2.xml seperti dibawah

    ini package com.example.hitung_sederhana;

    import android.os.Bundle;

    import android.app.Activity;

    import android.content.Intent;

    public class MainActivity2 extends Activity implements OnClickListener {

    Button back;

    @Override

    protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main_activity2);

    back = (Button)findViewById(R.id.back);

    back.setOnClickListener(this);

    }

    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.activity_main_activity2,

    menu); return true;}

    @Override

    public void onClick(View v) {

    if (v.getId() == R.id.back){

    Intent i = new Intent(getBaseContext(), MainActivity.class);

    startActivityForResult(i, 0);

    }else{

    Toast.makeText(getBaseContext(), "Salah",Toast.LENGTH_LONG).show();

    back.setText("Salah Le... ~");

    }

    }

    }

    28 

  • 8/15/2019 Modul Android 1

    30/77

    Modul praktikum Pemrograman Mobile 

    MEMBUAT APLIKASI DENGAN AUTOCOMPLETE 1.  Buat project dengan nama latihan2

    Gambar 4.3 : membuat project latihan2 2.  Modifikasi main.xml seperti dibawah ini

     

     

     

    29 

  • 8/15/2019 Modul Android 1

    31/77

    Modul praktikum Pemrograman Mobile 

     

          

     

  • 8/15/2019 Modul Android 1

    32/77

    Modul praktikum Pemrograman Mobile 

    android:layout_width="wrap_content"  

    android:layout_height="wrap_content"  

    android:text="Wanita"  /> 

      

      

    3. 

    Modifikasi activity.java seperti dibawahini package com.example.latihan2;

    import android.R.string;

    import android.os.Bundle;

    import android.app.Activity;

    public class MainActivity extends Activity implements OnClickListener,

    TextWatcher, RadioGroup.OnCheckedChangeListener{

    EditText nama, nim;

    TextView seleksi;

    AutoCompleteTextView provinsi;

    RadioGroup jk;

    CheckBox ya;

    String item[] = {"Jawa Tengah", "Jawa Timur", "Jawa Barat", "Sumatera

    Selatan", "Sumatera Utara"};

    ImageButton create;

    String user="yuni", pass="12345";

    @Override

    31 

  • 8/15/2019 Modul Android 1

    33/77

    Modul praktikum Pemrograman Mobile 

    protected void onCreate(Bundle savedInstanceState)

    { super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main); seleksi = (TextView)findViewById(R.id.seleksi);

     provinsi = (AutoCompleteTextView)findViewById(R.id.provinsi);provinsi.addTextChangedListener(this); provinsi.setAdapter(new ArrayAdapter(this,

    android.R.layout.simple_dropdown_item_1line, item)); nama = (EditText)findViewById(R.id.nama);

    nim = (EditText)findViewById(R.id.nim); create = (ImageButton)findViewById(R.id.create);

    create.setOnClickListener(this); 

    ya = (CheckBox)findViewById(R.id.ya); jk= (RadioGroup)findViewById(R.id.jk);

     jk.setOnCheckedChangeListener(this); } @Override public void onClick(View arg0)

    { try{ if(arg0.getId() == R.id.create){ 

    Intent i = new Intent(getBaseContext(),

    MainActivity2.class); startActivityForResult(i, 0); } 

    } catch (Exception e){ 

    Toast.makeText(getBaseContext(), "Anda Tidak Berhak

    Masuk", Toast.LENGTH_LONG).show(); } } 

    @Override public void afterTextChanged(Editable s) { } @Override public void beforeTextChanged(CharSequence s, int start, int count,int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count)

    { seleksi.setText(provinsi.getText()); 

    32 

  • 8/15/2019 Modul Android 1

    34/77

    Modul praktikum Pemrograman Mobile 

    } @Override public void onCheckedChanged(RadioGroup group, int checkedId) { } } 

    4.  Modifikasi main2.xml seperti gambar dibawah ini

    Gambar 4.4 : tampilan activity kedua 5.  Modifikasi activity2.java seperti gambar dibawah ini

    package com.example.latihan2;

    import android.os.Bundle;

    import android.app.Activity;

    public class MainActivity2 extends Activity implements OnClickListener

    { Button exit, back;

    @Override

    protected void onCreate(Bundle savedInstanceState)

    { super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main2);

    back = (Button)findViewById(R.id.back);

    exit = (Button)findViewById(R.id.exit);

    back.setOnClickListener(this);

    exit.setOnClickListener(this);

    }

    @Override

    33 

  • 8/15/2019 Modul Android 1

    35/77

    Modul praktikum Pemrograman Mobile 

    public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.activity_main2,

    menu); return true; } @Override 

    public void onClick(View v)

    { try{ if(v.getId() == R.id.exit){ 

    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setMessage("Apakah Anda Ingin Keluar ?") .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener()

    { @Override public void onClick(DialogInterface arg0, int arg1) {

    MainActivity2.this.finish(); } 

    }) .setNegativeButton("NO", new DialogInterface.OnClickListener() {

    @Override public void onClick(DialogInterface dialog, int which)

    { dialog.cancel(); } 

    }).setNeutralButton("Cancel", new DialogInterface.OnClickListener() {

    @Override public void onClick(DialogInterface dialog, int which)

    { dialog.dismiss(); } }).show(); }else if (v.getId() == R.id.back){ 

    Intent i = new Intent(getBaseContext(),MainActivity.class); startActivityForResult(i, 0); 

    } }catch(Exception e){

    Toast.makeText(getBaseContext(), "Hahaha", Toast.LENGTH_SHORT).show(); 

    } } 

    34 

  • 8/15/2019 Modul Android 1

    36/77

    Modul praktikum Pemrograman Mobile 

    6.  Jalankan aplikasi

    Gambar 4.5 : hasil tampilan aplikasi 

    35 

  • 8/15/2019 Modul Android 1

    37/77

    Modul praktikum Pemrograman Mobile 

    PERTEMUAN 5

    Pada bagian ini, kita akan mempelajari : Membuat aplikasi database sederhana dengan SQLite 

    ................................................................................................................................................ .......... PENGENALAN SQLite SQLite adalah database yang dibangun di Android. Hampir sama dengan SQL pada

    dekstop, SQLite memiliki fiture relasional database namun membutuhkan sedikit memori. 

    SQLite terdapat pada semua perangkat Android. Anda culup mendefinisikan perintah SQL

    untuk meng-create atau meng-update database, selanjutnya sistem ada Android akan

    menangani hal-hal yang berhubungan dengn database. SQLite database otomatis akan

    tersimpan didalam path data/data/nama_package/database/nama_database. 

    PEMBUATAN APLIKASI 1. Buat project baru dengan nama AndroidCrudExample. Lalu setelah itu modifikasi

    layout activity_main.xml sesuai dengan gambar 5.1; 

    Gambar 5.1 layout activity_main.xml 

    2.  Kemudian buat activity baru dengan nama

    student_input_form.xml. Setelah selesai

    membuat activity baru jangan lupa untuk

    menginisialisasikannya pada file

    AndroidManifest.xml agar activity dapat

    kenal/dijalankan. Pada Gambar 5.2

    student_input_form.

    Gambar 5.2. Studen_input_form 

    36 

  • 8/15/2019 Modul Android 1

    38/77

    Modul praktikum Pemrograman Mobile 

    3.  Setelah itu buat file DatabaseHandler.java

    import android.content.Context; import android.database.sqlite.SQLiteDatabase;

    import android.database.sqlite.SQLiteOpenHelper; public class DatabaseHandler extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1; protected static final String DATABASE_NAME = "StudentDatabase";

    public DatabaseHandler(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); 

    } @Override 

    public void onCreate(SQLiteDatabase db) {

    String sql = "CREATE TABLE students " + "( id INTEGER PRIMARY KEY AUTOINCREMENT, "

    + "firstname TEXT, " + "email TEXT ) "; 

    db.execSQL(sql); } 

    @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)

    { String sql = "DROP TABLE IF EXISTS students"; db.execSQL(sql); onCreate(db); 

    } } 

    4. 

    Kemudian itu buat lagi file ObjectStudent.java

    public class ObjectStudent { 

    int id; String firstname;

    String email; public ObjectStudent(){ } 

    37 

  • 8/15/2019 Modul Android 1

    39/77

    Modul praktikum Pemrograman Mobile 

    5.  Setelah itu modifikasi file MainActivity.java (bagi yang tidak memiliki atau

     belum membuat file MainActivity.java buat terlebih dahulu)

    import java.util.List; 

    import android.os.Bundle;

    import android.app.Activity;

    import android.view.Menu;

    import android.widget.Button; import android.widget.LinearLayout;

    import android.widget.TextView; public class MainActivity extends Activity {

    @Override protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    Button buttonCreateLocation = (Button) findViewById(R.id.buttonCreateStudent); 

    buttonCreateLocation.setOnClickListener(new 

    OnClickListenerCreateStudent()); countRecords(); readRecords(); 

    } public void countRecords() { 

    int recordCount = new TableControllerStudent(this).count();

    TextView textViewRecordCount = (TextView) findViewById(R.id.textViewRecordCount);

    textViewRecordCount.setText(recordCount + " records found."); } public void readRecords() { 

    LinearLayout linearLayoutRecords = (LinearLayout)

    findViewById(R.id.linearLayoutRecords); linearLayoutRecords.removeAllViews();

    List students = new TableControllerStudent(this).read(); 

    38 

  • 8/15/2019 Modul Android 1

    40/77

    Modul praktikum Pemrograman Mobile 

    if (students.size() > 0) { for (ObjectStudent obj : students)

    { int id = obj.id; 

    String studentFirstname = obj.firstname;String studentEmail = obj.email; String textViewContents = studentFirstname + " - " +

    studentEmail; TextView textViewLocationItem = new

    TextView(this); textViewLocationItem.setPadding(0, 10, 0, 10);

    textViewLocationItem.setText(textViewContents);

    textViewLocationItem.setTag(Integer.toString(id));

    textViewLocationItem.setOnLongClickListener(new OnLongClickListenerStudentRecord()); 

    linearLayoutRecords.addView(textViewLocationItem); } 

    } else { 

    TextView locationItem = new TextView(this);

    locationItem.setPadding(8, 8, 8, 8);

    locationItem.setText("No records yet.");

    linearLayoutRecords.addView(locationItem); } 

    } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present.

    getMenuInflater().inflate(R.menu.main, menu); return true; 

    } } 

    6.  Lalu kemudian buat file TableControllerStudent.java

    import java.util.ArrayList;

    import java.util.List; 

    import android.content.ContentValues;

    import android.content.Context; 

    39 

  • 8/15/2019 Modul Android 1

    41/77

    Modul praktikum Pemrograman Mobile 

    import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class TableControllerStudent extends DatabaseHandler {

    public TableControllerStudent(Context context) { super(context); 

    public boolean create(ObjectStudent objectStudent) {

    ContentValues values = new ContentValues();

    values.put("firstname", objectStudent.firstname);

    values.put("email", objectStudent.email);

    SQLiteDatabase db = this.getWritableDatabase(); 

    boolean createSuccessful = db.insert("students", null, values) > 0;db.close(); return createSuccessful; 

    } public List read() { 

    List recordsList = new ArrayList();

    String sql = "SELECT * FROM students ORDER BY id DESC";

    SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(sql, null);

    if (cursor.moveToFirst()) { do { 

    int id = Integer.parseInt(cursor.getString(cursor.getColumnIndex("id")));

    String studentFirstname =cursor.getString(cursor.getColumnIndex("firstname"));

    String studentEmail = cursor.getString(cursor.getColumnIndex("email"));

    ObjectStudent objectStudent = new ObjectStudent(); objectStudent.id = id; objectStudent.firstname

    = studentFirstname; objectStudent.email =

    studentEmail; recordsList.add(objectStudent); 

    } while (cursor.moveToNext()); } 

    cursor.close(); db.close(); return recordsList; 

    40 

  • 8/15/2019 Modul Android 1

    42/77

    Modul praktikum Pemrograman Mobile 

    public ObjectStudent readSingleRecord(int studentId)

    { ObjectStudent objectStudent = null; String sql = "SELECT * FROM students WHERE id = " +

    studentId; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(sql,

    null); if (cursor.moveToFirst()) { int id = Integer.parseInt(cursor.getString(cursor.getColumnIndex("id")));

    String firstname = cursor.getString(cursor.getColumnIndex("firstname"));

    String email = cursor.getString(cursor.getColumnIndex("email")); objectStudent = new ObjectStudent();

    objectStudent.id = id;

    objectStudent.firstname = firstname;

    objectStudent.email = email; } cursor.close(); db.close(); return objectStudent; } 

    public boolean update(ObjectStudent objectStudent) {

    ContentValues values = new ContentValues();

    values.put("firstname", objectStudent.firstname);

    values.put("email", objectStudent.email); String where = "id = ?"; String[] whereArgs = { Integer.toString(objectStudent.id) };

    SQLiteDatabase db = this.getWritableDatabase(); boolean updateSuccessful = db.update("students", values, where, whereArgs) > 0;

    db.close(); return updateSuccessful; 

    } public boolean delete(String id) { 

    SQLiteDatabase db = this.getWritableDatabase(); boolean deleteSuccessful = db.delete("students", "id = " + id, null) > 0;

    db.close(); return deleteSuccessful; 

    } public int count() { 

    SQLiteDatabase db = this.getWritableDatabase(); 

    41 

  • 8/15/2019 Modul Android 1

    43/77

    Modul praktikum Pemrograman Mobile 

    String sql = "SELECT * FROM students"; int recordCount = db.rawQuery(sql, null).getCount();

    db.close(); return recordCount;

     } } 

    7.  Buat file java dengan nama OnClickListenerCreateStudent.java

    import android.app.AlertDialog;

    import android.content.Context; import android.content.DialogInterface;

    import android.view.LayoutInflater;

    import android.view.View; import android.view.View.OnClickListener;

    import android.widget.EditText; import android.widget.Toast; 

    public class OnClickListenerCreateStudent implements OnClickListener { 

    @Override public void onClick(View view) { 

    final Context context = view.getContext();

    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  

    View formElementsView = inflater.inflate(R.layout.student_input_form, null, false); 

    final EditText editTextStudentFirstname = (EditText)

    formElementsView.findViewById(R.id.editTextStudentFirstname); final EditText editTextStudentEmail = (EditText)

    formElementsView.findViewById(R.id.editTextStudentEmail); new AlertDialog.Builder(context) .setView(formElementsView) .setTitle("Create Student") .setPositiveButton("Add", new DialogInterface.OnClickListener() {

    public void onClick(DialogInterface dialog, int id) { 

    42 

  • 8/15/2019 Modul Android 1

    44/77

    Modul praktikum Pemrograman Mobile 

    String studentFirstname =

    editTextStudentFirstname.getText().toString(); String studentEmail =

    editTextStudentEmail.getText().toString(); ObjectStudent objectStudent

    = new ObjectStudent(); objectStudent.firstname = studentFirstname; objectStudent.email = studentEmail;

    boolean createSuccessful = new TableControllerStudent(context).create(objectStudent);

    if(createSuccessful){ Toast.makeText(context, "Student information was saved.",

    Toast.LENGTH_SHORT).show(); }else{ 

    Toast.makeText(context, "Unable to save studentinformation.", Toast.LENGTH_SHORT).show(); 

    ((MainActivity) context).countRecords();

    ((MainActivity) context).readRecords();

    dialog.cancel(); } }).show(); } } 

    8.  Buat file java lainnya denga nama OnLongClickListenerStudentRecord.java

    import android.app.AlertDialog;

    import android.content.Context; import android.content.DialogInterface;

    import android.view.LayoutInflater;

    import android.view.View; import android.view.View.OnLongClickListener;

    import android.widget.EditText; import android.widget.Toast; 

    public class OnLongClickListenerStudentRecord implements OnLongClickListener { 

    43 

  • 8/15/2019 Modul Android 1

    45/77

    Modul praktikum Pemrograman Mobile 

    Context context; String id; 

    @Override public boolean onLongClick(View view) {

    context = view.getContext(); id = view.getTag().toString(); final CharSequence[] items = { "Edit", "Delete" }; new AlertDialog.Builder(context).setTitle("Student Record") .setItems(items, new DialogInterface.OnClickListener() {

    public void onClick(DialogInterface dialog, int item) { if (item == 0) {

    editRecord(Integer.parseInt(id)); } else if (item == 1) { 

    boolean deleteSuccessful = new

    TableControllerStudent(context).delete(id); if (deleteSuccessful){ 

    Toast.makeText(context, "Student record was deleted.",

    Toast.LENGTH_SHORT).show(); }else{ 

    Toast.makeText(context, "Unable to delete student record.",

    Toast.LENGTH_SHORT).show(); } 

    ((MainActivity) context).countRecords();

    ((MainActivity) context).readRecords(); } dialog.dismiss(); } 

    }).show();return false; } public void editRecord(final int studentId) { 

    final TableControllerStudent tableControllerStudent =

    new TableControllerStudent(context); ObjectStudent objectStudent =

    tableControllerStudent.readSingleRecord(studentId); 

    44 

  • 8/15/2019 Modul Android 1

    46/77

    Modul praktikum Pemrograman Mobile 

    LayoutInflater inflater = (LayoutInflater)

    context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  final View formElementsView = inflater.inflate(R.layout.student_input_form,

    null, false); final EditText editTextStudentFirstname = (EditText)

    formElementsView.findViewById(R.id.editTextStudentFirstname); final EditText editTextStudentEmail = (EditText)

    formElementsView.findViewById(R.id.editTextStudentEmail); 

    editTextStudentFirstname.setText(objectStudent.firstname);  editTextStudentEmail.setText(objectStudent.email);

    new AlertDialog.Builder(context) 

    .setView(formElementsView) 

    .setTitle("Edit Record") 

    .setPositiveButton("Save Changes",

    new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) {

    ObjectStudent objectStudent = new ObjectStudent(); objectStudent.id = studentId;

    objectStudent.firstname = editTextStudentFirstname.getText().toString(); objectStudent.email = editTextStudentEmail.getText().toString(); boolean updateSuccessful = tableControllerStudent.update(objectStudent);

    if(updateSuccessful){ Toast.makeText(context, "Student record was updated.",

    Toast.LENGTH_SHORT).show(); }else{ 

    Toast.makeText(context, "Unable to update student record.",

    Toast.LENGTH_SHORT).show(); } 

    ((MainActivity) context).countRecords();((MainActivity) context).readRecords();

    dialog.cancel(); } }).show(); } } 

    45 

  • 8/15/2019 Modul Android 1

    47/77

    Modul praktikum Pemrograman Mobile 

    9.  Setelah semua selesai dibuat, coba jalankan. apakah sesuai dengan gambar

    dibawah ?

    Gambar 3. Tampilan awal aplikasi dan Gambar 4. Tampilan input data 

    Gambar 5. Data berhasil diinsert Gambar 6. Pilihan Edit atau Delete data 

    Gambar 7. Saat berhasiil mengupdate/edit data Gambar 8 . Saat berhasil mendelete data 

    46 

  • 8/15/2019 Modul Android 1

    48/77

  • 8/15/2019 Modul Android 1

    49/77

    Modul praktikum Pemrograman Mobile 

    return $con; } function close() {

     // closing db connectionmysql_close(); 

    ?> 

    3.  Kemudian buat file db_config.php

     

    4.  Kemudian buat file create_product.php

  • 8/15/2019 Modul Android 1

    50/77

  • 8/15/2019 Modul Android 1

    51/77

  • 8/15/2019 Modul Android 1

    52/77

    Modul praktikum Pemrograman Mobile 

    echo json_encode($response);

    } else { $response["success"] = 0;

    $response["message"] = "No product found"; 

    echo json_encode($response); } 

    } else {

    $response["success"] = 0; $response["message"] = "Required field(s) is missing"; 

    echo json_encode($response); } ?> 

    7.  Selanjutnya buat file get_all_products.php

  • 8/15/2019 Modul Android 1

    53/77

  • 8/15/2019 Modul Android 1

    54/77

    Modul praktikum Pemrograman Mobile 

    echo

     json_encode($response); } else { $response["success"] = 0;

    $response["message"] = "No product

    found"; echo json_encode($response); } 

    } else { $response["success"]

    = 0; $response["message"] = "No product

    found"; echo json_encode($response); } 

    } else {

    $response["success"] = 0; $response["message"] = "Required field(s) is missing";

    echo json_encode($response); } ?> 

    9.  setelah selesai coba akses  http://localhost/android_connect/db_connect.php 

    untuk melihat apakah koneksi berjalan dengan baik. jika koneksi berjalan dengan

     baik kembali keproject android lalu buat main layout dengan namamain_screen.xml dengan tampilan seperti pada gambar berikut;

    Gambar 6.2 Layout main_screen.xml 

    53 

    http://localhost/android_connect/db_connect.phphttp://localhost/android_connect/db_connect.phphttp://localhost/android_connect/db_connect.phphttp://localhost/android_connect/db_connect.php

  • 8/15/2019 Modul Android 1

    55/77

    Modul praktikum Pemrograman Mobile 

    10.  kemudian buat juga layout untuk tampilan add_product, all_products, edit-

     product, dan list_item

    Gambar 6.3 Layout add_product.xml  Gambar 6.4 Layout all_products.xml 

    Gambar 6.5 Layout edit_product.xml  Gambar 6.6 Layout item_list.xml 

    54 

  • 8/15/2019 Modul Android 1

    56/77

    Modul praktikum Pemrograman Mobile 

    11. Setelah layout selesai dibuat, kemudian lanjut buat file JSONParser.java 

    import java.io.BufferedReader;

    import java.io.IOException; import

     java.io.InputStream; import

     java.io.InputStreamReader; import java.io.UnsupportedEncodingException;

    import java.util.List; 

    import org.apache.http.HttpEntity;

    import org.apache.http.HttpResponse;

    import org.apache.http.NameValuePair; 

    import org.apache.http.client.ClientProtocolException;import org.apache.http.client.entity.UrlEncodedFormEntity;

    import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost;

    import org.apache.http.client.utils.URLEncodedUtils;

    import org.apache.http.impl.client.DefaultHttpClient;

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

    import android.util.Log; 

    public class JSONParser { 

    static InputStream is = null;

    static JSONObject jObj =

    null; static String json = ""; 

    // constructor public

    JSONParser() { 

    // function get json from url

    // by making HTTP POST or GET mehtod

    public JSONObject makeHttpRequest(String url, String method,

    List params) { 

    55 

  • 8/15/2019 Modul Android 1

    57/77

    Modul praktikum Pemrograman Mobile 

    // Making HTTP request

    try { 

    // check for request method

    if(method == "POST"){ // request method is POST

    // defaultHttpClient

    DefaultHttpClient httpClient = new

    DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new 

    UrlEncodedFormEntity(params)); 

    HttpResponse httpResponse = httpClient.execute(httpPost); 

    HttpEntity httpEntity = httpResponse.getEntity();

    is = httpEntity.getContent(); 

    }else if(method == "GET"){ // request method is GET

    DefaultHttpClient httpClient = new DefaultHttpClient(); 

    String paramString

    = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; HttpGet httpGet = new HttpGet(url); 

    HttpResponse httpResponse = 

    httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is

    = httpEntity.getContent(); } 

    } catch (UnsupportedEncodingException e) {

    e.printStackTrace();

    } catch (ClientProtocolException e) {

    56 

  • 8/15/2019 Modul Android 1

    58/77

  • 8/15/2019 Modul Android 1

    59/77

    Modul praktikum Pemrograman Mobile 

    import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair;

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

    import com.example.androidhive.R; 

    import android.app.Activity; import

    android.app.ProgressDialog; import

    android.content.Intent; import

    android.os.AsyncTask; import

    android.os.Bundle; import android.util.Log;

    import android.view.View;

    import android.widget.Button; import android.widget.EditText; 

    public class NewProductActivity extends Activity { 

    // Progress Dialog private ProgressDialog pDialog; 

    JSONParser jsonParser = new JSONParser(); EditText inputName; EditText inputPrice; EditText inputDesc; 

    // url to create new product 

    private static String url_create_product ="http://10.0.2.2/android_connect/create_product.php"; 

    // JSON Node names private static final String TAG_SUCCESS = "success"; 

    @Override public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);  

    58 

  • 8/15/2019 Modul Android 1

    60/77

    Modul praktikum Pemrograman Mobile 

    setContentView(R.layout.add_product); 

    // Edit Text 

    inputName = (EditText) findViewById(R.id.inputName);inputPrice = (EditText) findViewById(R.id.inputPrice);

    inputDesc = (EditText) findViewById(R.id.inputDesc); 

    // Create button Button btnCreateProduct = (Button)

    findViewById(R.id.btnCreateProduct); 

    // button click event 

    btnCreateProduct.setOnClickListener(new View.OnClickListener() { 

    @Override public void onClick(View view) { 

    // creating new product in background thread

    new CreateNewProduct().execute(); } 

    }); } 

    /** * Background Async Task to Create new product

    * */

    class CreateNewProduct extends AsyncTask { 

    /** * Before starting background thread Show Progress Dialog

    */@Override protected void onPreExecute() {

    super.onPreExecute(); pDialog = new ProgressDialog(NewProductActivity.this);

    pDialog.setMessage("Creating Product..");

    pDialog.setIndeterminate(false);

    pDialog.setCancelable(true); pDialog.show(); 

    59 

  • 8/15/2019 Modul Android 1

    61/77

    Modul praktikum Pemrograman Mobile 

    /** * Creating product

    * */

    protected String doInBackground(String... args) { String

    name = inputName.getText().toString(); String

    price = inputPrice.getText().toString(); String description = inputDesc.getText().toString(); 

    // Building Parameters

    List params = new 

    ArrayList(); params.add(new BasicNameValuePair("name", name));

    params.add(new BasicNameValuePair("price", price));

    params.add(new BasicNameValuePair("description", description)); 

    // getting JSON Object

    // Note that create product url accepts POST method

    JSONObject json =

     jsonParser.makeHttpRequest(url_create_product, "POST", params); 

    // check log cat fro response Log.d("Create

    Response", json.toString());

    // check for success tag

    try { 

    int success = json.getInt(TAG_SUCCESS); 

    if (success == 1) { // successfully created

    product Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);

    startActivity(i); 

    // closing this screen 

    60 

  • 8/15/2019 Modul Android 1

    62/77

    Modul praktikum Pemrograman Mobile 

    finish(); } else { 

    // failed to create product } } catch (JSONException e) {

    e.printStackTrace(); } 

    return null; } 

    /** 

    After completing background task Dismiss the progress dialog* **/

    protected void onPostExecute(String file_url)

    { // dismiss the dialog once done

    pDialog.dismiss(); } 

    } } 

    13. Kemudian buat file java EditProductActivity.java 

    import java.util.ArrayList;

    import java.util.List; 

    import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair;

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

    import com.example.androidhive.R; 

    import android.app.Activity; import

    android.app.ProgressDialog; import

    android.content.Intent; 

    61 

  • 8/15/2019 Modul Android 1

    63/77

  • 8/15/2019 Modul Android 1

    64/77

    Modul praktikum Pemrograman Mobile 

    private static final String TAG_PRODUCT = "product";

    private static final String TAG_PID = "pid"; private static final String TAG_NAME = "name";

    private static final String TAG_PRICE = "price"; private static final String TAG_DESCRIPTION = "description"; 

    @Override public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.edit_product); 

    // save button 

    btnSave = (Button) findViewById(R.id.btnSave);btnDelete = (Button) findViewById(R.id.btnDelete); 

    // getting product details from intent

    Intent i = getIntent();

    // getting product id (pid) from intent

    pid = i.getStringExtra(TAG_PID);

    // 

    Getting complete product details in background thread

    new GetProductDetails().execute();

    // save button click event btnSave.setOnClickListener(new

    View.OnClickListener() {

    @Override public void onClick(View arg0) { 

    // starting background task to update productnew SaveProductDetails().execute(); 

    } }); 

    // Delete button click event

    btnDelete.setOnClickListener(new View.OnClickListener() { 

    @Override 

    63 

  • 8/15/2019 Modul Android 1

    65/77

    Modul praktikum Pemrograman Mobile 

    public void onClick(View arg0) { // deleting product in background thread

    new DeleteProduct().execute(); } }); 

    /** * Background Async Task to Get complete product details

    * */

    class GetProductDetails extends AsyncTask { 

    /** * Before starting background thread Show Progress Dialog

    * */

    @Override protected void onPreExecute() {

    super.onPreExecute(); pDialog = new ProgressDialog(EditProductActivity.this);

    pDialog.setMessage("Loading product details. Please wait...");

    pDialog.setIndeterminate(false); pDialog.setCancelable(true); 

    pDialog.show(); } 

    /** * Getting product details in background thread

    * */

    protected String doInBackground(String... params) { 

    // updating UI from Background Thread

    runOnUiThread(new Runnable() { public void run() { 

    // Check for success

    tag int success; try { 

    // Building Parameters 

    64 

  • 8/15/2019 Modul Android 1

    66/77

    Modul praktikum Pemrograman Mobile 

    List params = new ArrayList();

    params.add(new BasicNameValuePair("pid", pid)); // getting product details by making HTTP request

    // Note that product details url will use GET request

    JSONObject json = jsonParser.makeHttpRequest(url_product_detials, "GET", params); 

    // check your log for json response

    Log.d("Single Product Details", json.toString());

    //  json success tag

    success = json.getInt(TAG_SUCCESS);

    if (success == 1) { // successfully received product details

    JSONArray productObj = json .getJSONArray(TAG_PRODUCT); // JSON Array // get first product object from JSON Array

    JSONObject product = productObj.getJSONObject(0);

    // product with this pid found

    // Edit Text

    txtName = (EditText) findViewById(R.id.inputName);

    txtPrice = (EditText) findViewById(R.id.inputPrice);

    txtDesc = (EditText) findViewById(R.id.inputDesc); //

    display product data in EditText txtName.setText(product.getString(TAG_NAME));

    txtPrice.setText(product.getString(TAG_PRICE));

    txtDesc.setText(product.getString(TAG_DESCRIPTION));

    }else{ // product with pid not found } 

    } catch (JSONException e) {

    e.printStackTrace(); } } }); return null; } 

    /** * After completing background task Dismiss the progress dialog  

    65 

  • 8/15/2019 Modul Android 1

    67/77

    Modul praktikum Pemrograman Mobile 

    * **/ protected void onPostExecute(String file_url) {

    // dismiss the dialog once got all details

    pDialog.dismiss(); } 

    } /** * Background Async Task to Save product Details

    * */

    class SaveProductDetails extends AsyncTask {

    /** * Before starting background thread Show Progress Dialog 

    */@Override

    protected void onPreExecute() {

    super.onPreExecute();

    pDialog = new ProgressDialog(EditProductActivity.this);

    pDialog.setMessage("Saving product ...");

    pDialog.setIndeterminate(false);

    pDialog.setCancelable(true);

    pDialog.show();

    }

    /**

    * Saving product

    * */

    protected String doInBackground(String... args) {

    // getting updated data from EditTexts String name = txtName.getText().toString(); String

    price = txtPrice.getText().toString(); String

    description = txtDesc.getText().toString(); //Building Parameters List params = new ArrayList();

    params.add(new BasicNameValuePair(TAG_PID, pid));

    params.add(new BasicNameValuePair(TAG_NAME, name));

    params.add(new BasicNameValuePair(TAG_PRICE, price)); params.add(new BasicNameValuePair(TAG_DESCRIPTION, description)); // sending modified data through http request

    // Notice that update product url accepts POST method

    66 

  • 8/15/2019 Modul Android 1

    68/77

    Modul praktikum Pemrograman Mobile 

    JSONObject json = jsonParser.makeHttpRequest(url_update_product,

    "POST", params); // check json success

    tag try {  int success = json.getInt(TAG_SUCCESS); if(success == 1) { // successfully updated Intent i

    = getIntent();

    // send result code 100 to notify about product update

    setResult(100, i);

    finish();

    } else {

    // 

    failed to update product} } catch (JSONException e) {

    e.printStackTrace(); } 

    return null; } 

    /** * 

    After completing background task Dismiss the progress dialog

    * **/

    protected void onPostExecute(String file_url) { // dismiss the dialog once product uupdated

    pDialog.dismiss(); } 

    /*****************************************************************  * Background Async Task to Delete Product

    * */

    class DeleteProduct extends AsyncTask {

    /** * Before starting background thread Show Progress Dialog

    * */

    @Override protected void onPreExecute() { 

    67 

  • 8/15/2019 Modul Android 1

    69/77

    Modul praktikum Pemrograman Mobile 

    super.onPreExecute(); pDialog = new ProgressDialog(EditProductActivity.this);

    pDialog.setMessage("Deleting Product...");

    pDialog.setIndeterminate(false);

    pDialog.setCancelable(true); pDialog.show(); 

    } /** * Deleting product

    * */

    protected String doInBackground(String... args) {

    // Check for success tag 

    int success;try { 

    // Building Parameters List params = new ArrayList();

    params.add(new BasicNameValuePair("pid", pid)); //

     

    getting product details by making HTTP request JSONObject

     json = jsonParser.makeHttpRequest( url_delete_product, "POST",

    params);

    // check your log for json response

    Log.d("Delete Product",

     json.toString()); // json success tag success = json.getInt(TAG_SUCCESS);

    if (success == 1) { // product successfully deleted

    // notify previous activity by sending code 100

    Intent i = getIntent();

    // send result code 100 to notify about product deletion

    setResult(100, i);finish();

    } } catch (JSONException e) {

    e.printStackTrace(); } return null; } 

    68 

  • 8/15/2019 Modul Android 1

    70/77

    Modul praktikum Pemrograman Mobile 

    /** * After completing background task Dismiss the progress dialog

    * **/

    protected void onPostExecute(String file_url) { // dismiss the dialog once product deleted

    pDialog.dismiss(); } } } 

    14. Selanjutnya buat AllProductActivity.java 

    import java.util.ArrayList;import java.util.HashMap;

    import java.util.List; 

    import org.apache.http.NameValuePair;

    import org.json.JSONArray; import org.json.JSONException;

    import org.json.JSONObject; 

    import com.example.androidhive.R; 

    import android.app.ListActivity;

    import android.app.ProgressDialog;

    import android.content.Intent;

    import android.os.AsyncTask;

    import android.os.Bundle; import android.util.Log;

    import android.view.View; import android.view.View.OnClickListener;

    import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener;

    import android.widget.Button; import android.widget.ListAdapter;

    import android.widget.ListView;

    import android.widget.SimpleAdapter;

    import android.widget.TextView; 

    69 

  • 8/15/2019 Modul Android 1

    71/77

    Modul praktikum Pemrograman Mobile 

    public class AllProductsActivity extends ListActivity { 

    // Progress Dialog private ProgressDialog pDialog; 

    // Creating JSON Parser object

    JSONParser jParser = new JSONParser(); 

    ArrayList productsList; 

    // url to get all products list 

    private static String url_all_products ="http://10.0.2.2/android_connect/get_all_products.php";  

    // JSON Node names private static final String TAG_SUCCESS = "success";

    private static final String TAG_PRODUCTS = "products";

    private static final String TAG_PID = "pid"; private static final String TAG_NAME = "name"; 

    // products JSONArray

    JSONArray products = null;

    Button btnBack; 

    @Override public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.all_products); 

    // Hashmap for ListView productsList = new ArrayList(); 

    // Loading products in Background

    Thread new LoadAllProducts().execute();

    // Get listview

    ListView lv = getListView(); 

    70 

  • 8/15/2019 Modul Android 1

    72/77

    Modul praktikum Pemrograman Mobile 

    // on seleting single product

    // launching Edit Product Screen

    lv.setOnItemClickListener(new OnItemClickListener() {

    @Override public void onItemClick(AdapterView parent, View

    view, int position, long id) { // getting values from selected ListItem String pid = ((TextView) view.findViewById(R.id.pid)).getText() 

    .toString(); 

    // Starting new intent Intent in = new Intent(getApplicationContext(),

    EditProductActivity.class); // sending pid to next activity

    in.putExtra(TAG_PID, pid);

    // starting new activity and expecting some response back

    startActivityForResult(in, 100);

    }

    }); btnBack = (Button) findViewById(R.id.backButton);

    // view products click event btnBack.setOnClickListener(new View.OnClickListener()

    { @Override public void onClick(View view) { 

    // Launching All products Activity Intent i = new Intent(getApplicationContext(),

    MainScreenActivity.class); startActivity(i); 

    } }); } 

    // Response from Edit Product Activity

    @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data); // if result code 100 

    71 

  • 8/15/2019 Modul Android 1

    73/77

    Modul praktikum Pemrograman Mobile 

    if (resultCode == 100) { // if result code 100 is received

    // means user edited/deleted product

    // reload this screen again

    Intent intent = getIntent();

    finish();

    startActivity(intent); } 

    } /** * Background Async Task to Load all product by making HTTP Request

    * */

    class LoadAllProducts extends AsyncTask {/** * Before starting background thread Show Progress Dialog

    * */

    @Override protected void onPreExecute() {

    super.onPreExecute(); pDialog = new ProgressDialog(AllProductsActivity.this);

    pDialog.setMessage("Loading products. Please wait...");

    pDialog.setIndeterminate(false);

    pDialog.setCancelable(false); pDialog.show(); 

    } /** * getting All products from url

    * */

    protected String doInBackground(String... args) {

    // Building Parameters List params = new ArrayList();

    // getting JSON string from URL JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params); // Check your log cat for JSON reponse

    Log.d("All Products: ", json.toString());

    try {

    // Checking for SUCCESS TAG

    int success = json.getInt(TAG_SUCCESS); 

    72 

  • 8/15/2019 Modul Android 1

    74/77

  • 8/15/2019 Modul Android 1

    75/77

    Modul praktikum Pemrograman Mobile 

    // dismiss the dialog after getting all products

    pDialog.dismiss();

    // updating UI from Background Thread

    runOnUiThread(new Runnable() {

    public void run() {

    /**

    * Updating parsed JSON data into

    ListView * */

    ListAdapter adapter = new SimpleAdapter( AllProductsActivity.this, productsList,

    R.layout.list_item, new String[] { TAG_PID,TAG_NAME},

    new int[] { R.id.pid, R.id.name });

    // updating listview

    setListAdapter(adapter); } 

    }); } } } 

    15. Terakhir buat file MainScreenActivity.java 

    import com.example.androidhive.R;import android.app.Activity; import

    android.content.Intent; import

    android.os.Bundle; import android.view.View;

    import android.widget.Button; 

    public class MainScreenActivity extends

    Activity{ Button btnViewProducts; Button btnNewProduct;@Override public void onCreate(Bundle savedInstanceState)

    { super.onCreate(savedInstanceState);

    setContentView(R.layout.main_screen); // Buttons btnViewProducts = (Button) findViewById(R.id.btnViewProducts);

    btnNewProduct = (Button) findViewById(R.id.btnCreateProduct); 

    74 

  • 8/15/2019 Modul Android 1

    76/77

  • 8/15/2019 Modul Android 1

    77/77

    Modul praktikum Pemrograman Mobile 

    Gambar 6.9 Tampilan data  Gambar 6.10 Tampilan edit/delete 

    PERTEMUAN 7 MEMBUAT APLIKASI DENGAN PHP MYSQL (RELASI TABEL) PART I 

    PERTEMUAN 8 MEMBUAT APLIKASI DENGAN PHP MYSQL (RELASI TABEL) PART II 


Recommended