AND ROI D FAST T RACK
Tentang Penulis Agus Haryanto, MKOM http://agusharyanto.net @agus_inovator agus.superwriter@gmail.com 08551000444 / 089673371119 Juara 2 Indosat M2 Android Application Contest Juara Harapan Kompetisi Android T-Market (Telesindo) Juara 1 BBDEVID Challenge Blackberry Application (Webworks) Juara 1 AngelHack Blackberry Indonesia
ANDROID FAST TRACK A G U S H A R YA N T O
CONTENTS Preface...vii Pengenalan Android...9 Kenalan dengan Android...9 Instalasi Android...10 Project Android pertama...11 Pengenalan User Interface...19 Mengenal Layout...19 Mengenal View...36 Android Database SQLITE...49 SQLITE...49 Kamus Tiga Bahasa (CRUD)...50 Android Google Map...87 Menampilkan Data GPS...87 Menampilkan Map pada Android...95 Menampilkan Direction pada Map...111 Android PHP MySQL...125 CRUD Android PHP Mysql...125 Penutup...151 Semangat...151 Seminar Workshop Android...151 Referensi...152 v Android Fast Track
PREFACE Android begitu fenomenal diusianya masih muda sudah mampu mendominasi pasar smartphone dunia. Bagi pengembang aplikasi itu adalah pasar yang besar untuk aplikasinya. Untuk membuat aplikasi android tidaklah sesulit yang dibayangkan. Syarat utamanya kita harus menguasai dasar java dan konsep object orientedya (OOP). Pada buku Android Fast Track ini akan membahas bagian-bagian penting dalam pembuatan aplikasi Android meliputi Pengenalan dasar pembuatan aplikasi android, pengenalan cara menggunakan database sqlite android, pengenalan cara menggunakan Map API 2 untuk mengembangkan aplikasi android yang menggunakan peta. Pengenalan cara membuat aplikasi android yang datanya tersimpan di server Buku ini tentunya masih jauh dari sempurna. apabila ada masukkan langsung saja Untuk itu email ke agus.superwriter@gmail.com. Untuk melihat tutorial android lainnya dapat berkunjung ke situs http://agusharyanto.net Untuk kampus atau sekolah yang berminat mengadakan seminar atau workshop android atau lainnya bisa hubungi saya di email agus.superwriter@gmail.com atau di 0855-1000-444.,twitter @agus_inovator Khusus untuk luar kota biaya trans- portasi dan akomodasi ditanggung penyelenggara acara. vii
1 PENGENALAN ANDROID KENALAN DENGAN ANDROID Sebelum melangkah lebih jauh, alangkah baiknya jika kita mengenal apa itu android. Android adalah Sistem Operasi yang dikembangkan dan dipopulerkan oleh Google. Andy Rubin dapat kita sebut sebagai otak utama dibalik OS android ini. Pada awalnya perkembangan OS Android ini kurang begitu bagus, Hal ini membuat Google turun tangan dengan turut melahirkan ponsel Google Android pertama yang legendaris yang dikenal dengan nama Nexus One. Di Nexus One ini Google menunjukkan kemampuan android yang sebenarnya dan hasilnya luar biasa, tanggapan pasar begitu bagus. Hal inilah yang mendorong minat perusahaan-perusahaan Smarthone bersemangat untuk membuat Smartphone dengan OS Android. Dan hasilnya dapat dilihat saat ini android menguasai pasar Smartphone Dunia dengan dipimpin oleh Samsung dengan seri Galaxynya. Berikut saya tampilkan data analisis dari Gartner.
Ada Sistem Operasi berarti ada aplikasi yang dapat kita buat di dalamnya. Pada Android Fast Track ini kami mencoba mengenalkan cara membuta aplikasi pada android, disini metode yang diterapkan akan lebih banyak praktek. I N S TA L A S I A N D R O I D Sebelum memulai membuat aplikasi android tentunya kita harus mempersiapkan softwarenya terlebih dahulu. Step Instalaasi : 1. Download Java 1.7 dari oracle.com http://www.oracle.com/technetwork/java/javase/downloads/j dk7-downloads-1880260.html lalu install. 2. Download Ecliplse Bundle (Eclipse + ADT + Android SDK Platform) dari developer.andorid.com http://developer.android.com/sdk/index.html#win-bundle 3. Unzip file yang didownload ke direktori yang kita inginkan misalanya c:\development 4. Instalasi Selesai. Untuk menjalankannnya, masuk ke direktori eclipse dari file yang diunzip lalu jalankan eclipse 5. Untuk mendownload Platform android lainnya, jalankan SDKManager Untuk Spesifikasi Hardwarenya agar terasa nyaman waktu develop aplikasi sebaikanya gunakan komputer dengan processor core i3 keatas dan memori 4GB 10
AGUS HARYANTO PROJECT ANDROID P E R TA M A Dalam hidup selalu ada yang pertama, demikian juga dengan belajar. Kali ini kita akan membuat project Android Pertama kita. 1. Pada eclipse dibagian toolbar klik New 2. Pada jendela yang tanpil, klik folder Android, lalu pilih Android Application Project lalu klik Next 3. Isilah isian pada jendela New Android Application Field Keterangan Application Name Nama Aplikasi. Yang akan terlihat pada Icon Launcher Aplikasi. Project Name Nama Project. Nama Project ini boleh beda dengan nama Aplikasi. Package Name Nama package aplikasi kita, biasanya diawali dengan domain_organisasi lalu nama aplikasi. 11 Pengenalan Android
Misalnya net.agusharyanto.myfirstapp Minimum Required SDK Minimum SDK yang diperbolehkan untuk menjalankan aplikasi. Target SDK Target SDK yang akan menjalakan Aplikasi. Compile With Aplikasi akan di compile dengan SDK versi ini. Theme Theme yang akan dipakai untuk develop aplikasi. Klik Next 4. Mucul Jendela untuk mengkonfigurasi project, biarkan saja dengan nilai default. Klik Next 5. Muncul Jendela untuk mengatur Icon dari Aplikasi disini kita harus menyiapkan Icon dengan ukuran 32x32, 48x48, 72x72, 128x128. Jika belum siap klik Next saja. 6. Pada jendela Activity pilih Empty Activity lalu klik Next. Jika ingin pakai Fragment pilih Blank Activity. Karena baru belajar kita pilih yang tanpa Fragment yaitu Empty Activity 7. Pada jendela Empty Activity, kita bisa menentukan nama Activity dan layoutnya, untuk awal kita gunakan suja nilai yang sudah ada (default) lalu klik Finish Setelah selesai, maka kita sudah berhasil membuat project android dan bisa langsung merun aplikasinya. Tetapi sebelumnya kita harus memperhatikan beberapa file dan direktori yang ada pada project kita. 12
AGUS HARYANTO AndroidManifest.xml Pada file ini konfigurasi projectkita ditentukan, meliputi Default Activity yang akan dijalankan pada saat aplikasi dijalankan 13 Pengenalan Android
Daftar Activity dan Service yang akan digunakan dalam aplikasi. Datftar Permission Minimal SDK yang dapat menjalankan Aplikasi. Icon Aplikasi. src/ Direktori src/ adalah direktori dimana file-file class java aplikasi kita disimpan res/ Direktory res adalah direktori dimana file-file resource yang berkaitan dengan aplikasi disimpan ada beberapa direktori penting dibawah res/ ini layout/ direktori layout adalah tempat untuk menyimpan xml file layout user interface aplikasi. values/ direktori values adalah tempat untuk meyimpan file xml resource yang berkaitan dengan xml layout seperti String Definition dan Color Definition drawable-***/ adalah direktori untuk menyimpna file-file gambar, suara dan lainnya yang digunakan dalam aplikasi. Setelah kita mengerti, mari kita run projectnya, caranya adalah pada dari menu eclipse pilih Run ----> Run As ----> Android Application Jika belum ada Emulator AVDnya kita bisa menambahkan melalui menu Window ---> AVD Manager Terlihat kita sudah berhasil menjalankan project kita. 14
AGUS HARYANTO Dari mana tulisan Hello world! Yang pertama kita lihat adalah file AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/andr oid" package="net.agusharyanto.myfirstapp" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="17" /> 15 Pengenalan Android
<application android:allowbackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/apptheme" > <activity android:name="net.agusharyanto.myfirstapp.mainactivity " android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application> </manifest> Perhatikan disini activity yang dieksekusi pertama kali adalah MainActivity Mari kita buka file MainActivity.java package net.agusharyanto.myfirstapp; android.os.bundle; android.app.activity; android.view.menu; public class MainActivity extends Activity { @Override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); @Override public boolean oncreateoptionsmenu(menu menu) { 16
AGUS HARYANTO // Inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.main, menu); return true; Perhatikan activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/andr oid" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin " android:paddingleft="@dimen/activity_horizontal_margin " android:paddingright="@dimen/activity_horizontal_margi n" android:paddingtop="@dimen/activity_vertical_margin" tools:context=".mainactivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> </RelativeLayout> Disini menggunakan relative layout yang didalamnya ada TextView dari sinilah android:text="@string/hello_world" HelloWorld muncul, buka file string.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">myfirstapp</string> <string name="action_settings">settings</string> 17 Pengenalan Android
<string name="hello_world">hello world!</string> </resources> Tugas Jawablah Pertanyaan-pertanyaan dibwah ini. 1. Apa itu Android? 2. Apayang membuat anda tertarik belajar membuat aplikasi android? 3. Apa keuntungan yang didapat jika kita mempunyai kemampuan untuk membuat aplikasi android? 4. Anda lebih suka bahasa java atau HTML 5? 5. Anda suka dengan programming? 18
2 PENGENALAN USER I N T E R FA C E Sebelumnya kita sudah belajar membuat aplikasi sederhana pada Android. Sekarang kita melangkah ke aplikasi yang lebih menarik, yaitu aplikasi yang sudah menggunakan beberapa object view groups dan view. M E N G E N A L L AY O U T Pada Android layout memegang peranan penting terutama pada user interface. Dalam layout biasany didalamnya terdiri dari satu atau lebih objek view sehingga dapatlah disebut Layout adalah View Group. Ada beberapa layout yang berlaku di android. Linear Layout Linear Layout sesuai dengan namanya digunakan untuk menyusun view sacara linear vertical atau horizontal. Agar Lebih memahaminya mari kita buat satu project yang menggunakan linear layout
1. Buat project baru, isi kan parameter-parameternya seperti dibawah ini 20
AGUS HARYANTO Field Isi Application Name BelajarLinearLayout Project Name BelajarLinearLayout Package Name net.agusharyanto.belajarlayout Minimum SDK Api 8: Android 2.2 (Froyo) Required Target SDK Api 19: Android 4.4 (KitKat) Compile With Holo Light With Dark Action Bar Activity Name BelajarLinearLayoutActivity Layout Name main 2. Buka File activity_main.xml kemudian ketikan kode berikut <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="${packagename.${activityclass"> <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1"> <TextView android:text="merah" android:gravity="center_horizontal" android:background="#aa0000" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1"/> <TextView android:text="hijau" android:gravity="center_horizontal" android:background="#00aa00" android:layout_width="wrap_content" 21 Pengenalan User Interface
android:layout_height="fill_parent" android:layout_weight="1"/> <TextView android:text="biru" android:gravity="center_horizontal" android:background="#0000aa" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1"/> <TextView android:text="kuning" android:gravity="center_horizontal" android:background="#aaaa00" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1"/> </LinearLayout> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1"> <TextView android:text="baris Satu" android:textsize="15pt" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1"/> <EditText android:id="@+id/edittext1" android:text="baris Dua" android:textsize="15pt" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1"/> <Button android:id="@+id/button1" android:text="baris Tiga" android:textsize="15pt" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1"/> <TextView android:text="baris Empat" android:textsize="15pt" 22
AGUS HARYANTO android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1"/> </LinearLayout> </LinearLayout> Coba perhatikan kita ada tiga tag LinearLayout. 1. LinearLayout yang paling luar android:orientation diset vertical, yang berarti setiap view atau layout yang berada didalamnya akan disusn secara vertical. 2. LinearLayout yang kedua berada didalam LinearLayout yang diluar, android:orientation diset horizontal, yang berarti setiap view atau layout yang berada didalamnya akan disusun secara horizontal 3. Linear Layout yang ketiga juga berada didalam LinearLayout yang diluar, android:orientation diset vertical yang berarti setiap view atau layout yang berada didalamnya akan disusun secara vertical LinearLayout yang paling luar bisa disebut parent dari LinearLayout yang kedua dan ketiga. Disini kita juga mulai dikenalkan dengan beberapa tag baru yang masuk kedalam golongan view Tag Fungsi TextView Untuk menampilkan Text dalam bentuk label EditText Untuk Menampilkan Inputan Text Button Digunakan untuk menampilkan button atau tombol. Diatas juga terlihat properti-properti (Kalau kita biasa dengan HTML ini bisa disebut Atribut dan CSSnya) yang melekat pada masing-masing view. Property (Atribut) 23 Pengenalan User Interface fungsi
android:id Menetapkan id dari suatu view android:text Menetapkan isi text yang akan ditampilkan Property (CSS) fungsi android:textsize Menetapkan besar ukuran huruf android:layout_width Menetapkan lebar dari suatu view android:layout_height Menetapkan tinggi dari suatu view android:layout_weight Menunjukkan berapa banyak ruang ekstra dalam LinearLayout akan dialokasikan ke tampilan yang terkait dengan LayoutParams. android:gravity Menentukan tempat object/view pada suatu layout Agar lebih memahami fungsi dari property-property diatas cobalah baca javadoc android pada situs developer.andorid.com dan coba rubah nilainya. 3. Buka File MainActivity.java package net.agusharyanto.belajarandroidlayout; android.app.activity; android.os.bundle; public class MainActivity extends Activity { @Override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); 24
4. AGUS HARYANTO Sekarang Mari kita jalankan projectnya TableLayout Yang namanya table pasti ada baris dan kolom, demikian juga dengan TableLayout ini, view yang ada dalam layout ini akan disusun berdasarkan baris dan kolomnya.dimana ada TableLayout maka didalamnya akan ada TableRow TableRow adalah child dari TableLayout. Setiap Satu TableRow merupakan 1 baris dalam table. Pusing yang dengan teori, yah sudah kita langsung praktek saja. 25 Pengenalan User Interface
Masih dengan project yang tadi buat pada directory res/layout buat layout baru dengan nama tablelayout.xml 26
27 Pengenalan User Interface AGUS HARYANTO
Sacara ototmatis akan membuat file tablelayout.xml difolder layout, Edit file tersebut lalu ketikkan kode berikut <?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/and roid" android:layout_width="fill_parent" android:layout_height="fill_parent" android:stretchcolumns="1"> 28
AGUS HARYANTO <TableRow> <TextView android:text="nama" android:padding="3dip" android:background="#0000aa"/> <TextView android:text="nilai" android:gravity="right" android:padding="3dip" android:background="#0000aa" /> </TableRow> <TableRow> <TextView android:text="agus" android:padding="3dip" /> <TextView android:text="90" android:gravity="right" android:padding="3dip" /> </TableRow> <TableRow> <TextView android:text="zainal" android:padding="3dip" /> <TextView android:text="80" android:gravity="right" android:padding="3dip" /> </TableRow> </TableLayout> Pada file tablelayout.xml diatas terdapat 1 TableLayout yang didalamnya 3 TableRow, disetiap TableRow masing-masing mempunya 2 TextView, dari struktur code diatas maka akan terlihat sebuah table yang mempunyai 3 baris dan 2 kolom. buka file MainActivity.java rubah layout yang digunakan un tuk activity ini menjadi yang semula activity_main menjadi tablelayout package net.agusharyanto.belajarandroidlayout; android.app.activity; android.os.bundle; 29 Pengenalan User Interface
public class MainActivity extends Activity { @Override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.tablelayout); Sekarang mari kita run projectnya Nah Betulkan hasilnya dalam bentuk table dangan 3 baris dan 2 kolom. RelativeLayout 30
AGUS HARYANTO RelativeLayout sesuai dengan namanya, disini kita dapat menentukan posisi dari suatu view berdasarkan sudut pandang parent atau siblingnya. Agar lebih mudah dimengerti mari kita mulai lagi codingnya 1. Masih dengan project yang tadi buat pada directory res/layout buat layout baru dengan nama relativelayout.xml caranya sama seperti buat tablelayout diatas hanya pada jendela New Android XML File pada root elementnya pilih RelativeLayout Pada file relativelayout.xml ketikan kode berikut <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/and roid" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="#005500" android:padding="10px" > 31 Pengenalan User Interface
<TextView android:id="@+id/label" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="isi Pesan:" /> <EditText android:id="@+id/entry" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@android:drawable/editbox_backgro und" android:layout_below="@id/label" /> <Button android:id="@+id/kirim" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/entry" android:layout_alignparentright="true" android:layout_marginleft="10px" android:text="kirim" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toleftof="@id/kirim" android:layout_aligntop="@id/kirim" android:text="cancel" /> </RelativeLayout> 2. Buka file MainActivity.java package net.agusharyanto.belajarandroidlayout; android.app.activity; android.os.bundle; public class MainActivity extends Activity { @Override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.relativelayout); 32
3. AGUS HARYANTO Sekarang mari kita run projectnya AbsoluteLayout Absolute Layout dapat digunakan untuk meletakkan view sesuai dengan posisi yang kita inginkan. Masih dengan project yang tadi buat pada directory res/layout buat layout baru dengan nama absolutelayout.xml <?xml version="1.0" encoding="utf-8"?> <AbsoluteLayout android:layout_width="match_parent" android:layout_height="match_parent" xmlns:android="http://schemas.android.com/apk/res/android" > <Button android:layout_width="188px" android:layout_height="wrap_content" android:text="button" android:layout_x="126px" android:layout_y="361px" /> 33 Pengenalan User Interface
<Button android:layout_width="113px" android:layout_height="wrap_content" android:text="button" android:layout_x="12px" android:layout_y="361px" /> </AbsoluteLayout> Buka file MainActivity.java package net.agusharyanto.belajarandroidlayout; android.app.activity; android.os.bundle; public class MainActivity extends Activity { @Override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.absolutelayout); Sekarang mari kita run projectnya 34
AGUS HARYANTO MENGENAL VIEW Sebelumnya kita telah belajar tentang layout pada android disitu melihat ada TextView, Button dan lain-lain. Nah TextView, Button dan kawan-kawannya itu kalau diandroid disebut sebagai View, View ini adalah komponen-komponen yang membentuk user interface pada aplikasi android. Kita bisa mengelompokkan view ini dalam beberapa group. Basic Views, biasanya ini yang umum atau sering digunakan seperti TextView, EditText dan Button Picker Views, biasanya berupa pilihan untuk menginputkan Date dan Time seperti DatePicker dan TimePicker. List Views, biasanya menampilkan daftar pilihan yang panjang seperti ListView dan Spinner View Display Views view yang digunakan untuk menampilkan gambar seperti Gallery dan ImageSwitcher views. 35 Pengenalan User Interface
Menus views yang menampilkan tambahan menu ataupun context menu Additional Views seperti AnalogClock dan DigitalClock Basic View Pada Seksi ini, kita akan membahas basic view pada android, untuk meudahkan saya akan menjelaskanya dalam bentuk table TextView EditText Button ImageButton CheckBox ToggleButton RadioButton RadioGroup Widget Fungsi TextView sama seperti label pada SWING, yaitu untuk menampilkan tulisan dilayar. EditText sama seperti TextBox pada SWING, yaitu untuk user menginputkan data Button Sama seperti Button pada SWING yaiu sebagai Trigger untuk menjalankan suatu Fungsi ImageButton Sama fungsinya seperti Button, Bedanya Button ini didalamnya ada gambarnya CheckBox Digunakan apabila ada pertanyaan pilihan yang jawabannya bisa lebih dari satu Radio Button Biasanya digunakan untuk pilihan yang jawabannya 1 Radio Group Kumpulan dari Radio Button 36
AGUS HARYANTO Sekarang mari kita coba gunakan view-view diatas kedalam aplikasi. 1. Buat New Android Projectnya 37 Pengenalan User Interface
2. edit file activity_main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/andr oid" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:id="@+id/btnsave" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="save" /> <Button android:id="@+id/btnopen" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="open" /> <ImageButton android:id="@+id/btnimg1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" /> <EditText android:id="@+id/txtname" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <CheckBox android:id="@+id/chkautosave" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="autosave" /> <CheckBox android:id="@+id/star" style="?android:attr/starstyle" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <RadioGroup android:id="@+id/rdbgp1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" 38
AGUS HARYANTO > <RadioButton android:id="@+id/rdb1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="option 1" /> <RadioButton android:id="@+id/rdb2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="option 2" /> </RadioGroup> <ToggleButton android:id="@+id/toggle1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> 39 Pengenalan User Interface
Perhatikan atribut id yang mewakili identitas dari setiap view. Untuk mendeklarasikan id pada sebuah view harus diawali dengan @+id/ diikuti dengan nama yang ingin kita berikan 3. Sekarang mari kita jalankan projectnya Coba kita sentuh beberapa view, hasilnya ada yang seperti ini 40
AGUS HARYANTO Tetapi tentunya kita tidak ingin hanya ditampilan saja yang berubah. Tentunya kita ingin program juga dapat menangkap apa yang terjadi pada user Interface. Untuk itu mari kita buka otak dari project kita, yaitu file MainActivity.java package net.agusharyanto.basicview; android.app.activity; android.os.bundle; android.view.view; 41 Pengenalan User Interface
android.widget.button; android.widget.checkbox; android.widget.radiogroup; android.widget.radiogroup.oncheckedchangelistener; android.widget.toast; android.widget.togglebutton; public class MainActivity extends Activity { @Override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); //---Button view--button btnopen = (Button) findviewbyid(r.id.btnopen); btnopen.setonclicklistener(new View.OnClickListener() { public void onclick(view v) { Toast.makeText(getBaseContext(), "You have clicked the Open button", Toast.LENGTH_SHORT).show(); ); Button btnsave = (Button) findviewbyid(r.id.btnsave); btnsave.setonclicklistener(new View.OnClickListener() { public void onclick(view v) { DisplayToast("You have clicked the Save button"); ); //---CheckBox--CheckBox checkbox = (CheckBox) findviewbyid(r.id.chkautosave); checkbox.setonclicklistener(new View.OnClickListener() { 42
AGUS HARYANTO checked"); public void onclick(view v) { if (((CheckBox)v).isChecked()) DisplayToast("CheckBox is else DisplayToast("CheckBox is unchecked"); ); //---RadioButton--RadioGroup radiogroup = (RadioGroup) findviewbyid(r.id.rdbgp1); radiogroup.setoncheckedchangelistener(new OnCheckedChangeListener() { public void oncheckedchanged(radiogroup group, int checkedid) { //---displays the ID of the RadioButton that is checked--displaytoast(integer.tostring(checkedid)); ); //---ToggleButton--ToggleButton togglebutton = (ToggleButton) findviewbyid(r.id.toggle1); togglebutton.setonclicklistener(new View.OnClickListener() { public void onclick(view v) { if (((ToggleButton)v).isChecked()) DisplayToast("Toggle button is On"); else DisplayToast("Toggle button is Off"); ); private void DisplayToast(String msg) { Toast.makeText(getBaseContext(), msg, 43 Pengenalan User Interface
Toast.LENGTH_SHORT).show(); Oke mari kita perhatikan code by codenya Button btnopen = (Button) findviewbyid(r.id.btnopen); btnopen.setonclicklistener(new View.OnClickListener() { public void onclick(view v) { Toast.makeText(getBaseContext(), "You have clicked the Open button", Toast.LENGTH_SHORT).show(); ); Agar sebuah view bisa kita manipulasi (merubah isi, atau menangkap event) perlu didaftarkan di code activity. Contoh diatas kita mendaftarkan View (Button) dengan id btnopen kedalam sebuah variable btnopen. setelah itu kita bisa menambahkan listener pada button tersebut, kalau pada code diatas yang kita daftarkan adalah setonclicklistener. Efek yang terjadi adalah apabila btnopen diklik maka akan mengeksekusi perintah yang ada pada method onclick. Pada kode diatas akan menampilkan popup informasi dalam bentuk Toast Untuk Button lainnya dan view lainnya silahkan dicoba sendiri. Dan perhatikan pada method setonclick dari masing-masing view. 44
AGUS HARYANTO Tugas Kerjakan tugas-tugas dibawah ini 1. Buatlah aplikasi kalkulator sederhana yang fungsinya menghitung dua bilangan seperti dibawah ini 45 Pengenalan User Interface
46
47 Pengenalan User Interface AGUS HARYANTO
3 A N D R O I D D ATA B A S E SQLITE Sebelumnya kita sudah belajar membuat aplikasi sederhana pada Android, nah sekarang mari kita buat aplikasi yang lebih keren, aplikasi yang menggunakan database SQLite. S QL I T E Seperti telah dijelaskan diatas database pada android menggunakan SQLite. Dengan SQLite untuk insert, update dan query data dapat dilakukan dengan syntak SQL. Untuk itu sebelum melangkah pembuatan aplikasi Android yang memanfatkan firtur SQlite databasenya, kita harus menguasai cara menggunakan SQLite. Sama seperti database lainnya syntak SQLnya terbagi 2 kategori yaitu syntak untuk Data Definition Language (DDL) dan Data Manipulation Language (DML). Bagi yang pernah belajar database pasti tidak asing dengan kedua istilah tersebut. Sekarang ada pertanyaan nih apa beda DDL dan DML?
Biar mudah dipahami, kalau database itu kita ibaratkan sebuah rumah, maka DDL itu adalah syntax untuk membuat rumah, menambah kamar, merubah bangunan rumah, makanya yang termasuk syntak-syantak DDL adalah create table, alter table, drop table. sedangkan DML adalah syntax untuk mengetahui isi rumah, siapa saja penghuninya, berapa jumlahnya, ada berapa yang pria dan yang wanita, adakah anak-anak dirumah itu. Makanya yang termasuk syntak-syntak DML adalah insert, update, delete, select Untuk mengetahui lebih lanjut tentang sqlite bisa kunjungi SQLite Home Page KAMUS TIGA BAHASA (CRUD) Sekarang mari kita buat project yang menggunakan database sqlite di android. Dulu sebelum pakai android dihandphone yang dulu pasati pernah install kamus inggris Indonesia, yang kita gunakan untuk mencari terjemahan suatu kata dalam bahasa indonesia ke bahasa inggris dan jerman. Sebetulnya diandroid juga sudah ada yang buat. Tetapi tentunya akan lebih puas jika kita buat sendiri. Goal dari Aplikasi ini adalah untuk memahami CRUD dbsqlite pada Android. Berikut langkah-langkahnya 1. Buat project baru android dengan nama Kamus 50
AGUS HARYANTO 2. Buat Class baru dengan nama DatabaseHelper.java package net.agusharyanto.kamus; android.content.contentvalues; android.content.context; android.database.sqlite.sqlitedatabase; android.database.sqlite.sqliteopenhelper; public class DatabaseHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "dbkamus"; public static final String INGGRIS= "inggris"; public static final String INDONESIA = "indonesia"; public static final String JERMAN = "JERMAN"; //Constructor DataKamus untuk initiate database 51 Android Database SQLITE
public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, 1); //method createtable untuk membuat table kamus public void createtable(sqlitedatabase db){ db.execsql("drop TABLE IF EXISTS kamus"); db.execsql("create TABLE if not exists kamus (_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "inggris TEXT, indonesia TEXT, jerman TEXT);"); //method generatedata untuk mengisikan data ke kamus. public void generatedata(sqlitedatabase db){ ContentValues cv=new ContentValues(); cv.put(inggris, "run"); cv.put(indonesia, "lari"); cv.put(jerman, "laufen"); db.insert("kamus", INGGRIS, cv); cv.put(inggris, "walk"); cv.put(indonesia, "jalan"); cv.put(jerman, "gehen"); db.insert("kamus", INDONESIA, cv); cv.put(inggris, "read"); cv.put(indonesia, "membaca"); cv.put(jerman, "lesen"); db.insert("kamus", JERMAN, cv); @Override public void onupgrade(sqlitedatabase db, int oldversion, int newversion) { // TODO Auto-generated method stub createtable(db); generatedata(db); @Override public void oncreate(sqlitedatabase db) { // TODO Auto-generated method stub //Toast.makeText(getBaseContext(), "Oncreate", Toast.LENGTH_SHORT).show(); createtable(db); 52
AGUS HARYANTO generatedata(db); Pada class inilah database dibuat dengan nama dbkamus, disini table juga dibuat dengan nama kamus dan diisikan dengan beberapa data. 3. Edit file activity_main.xml pada direktori res/layout lalu ketikan kode berikut <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/andr oid" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="kamus Inggris Indonesia Jerman" /> <TextView android:id="@+id/textview01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="inggris :" > </TextView> <EditText android:id="@+id/txtinggris" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="" > <requestfocus> </requestfocus> </EditText> <Button android:id="@+id/btnterjemah" android:layout_width="fill_parent" 53 Android Database SQLITE
android:layout_height="wrap_content" android:onclick="getterjemahan" android:text="terjemahkan" > </Button> <TextView android:id="@+id/textview03" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="indonesia :" > </TextView> <EditText android:id="@+id/txtindonesia" android:layout_width="fill_parent" android:layout_height="wrap_content" android:editable="false" android:text="" > </EditText> <TextView android:id="@+id/textview1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="jerman" > </TextView> <EditText android:id="@+id/txtjerman" android:layout_width="fill_parent" android:layout_height="wrap_content" > </EditText> </LinearLayout> Disini untuk user interface menggunakan linear layout yang didalamnya ada tiga edit text dan satu button 4. Edit file MainActivity.java yang ada apada direktori src/ lalu ketikan kode berikut package net.agusharyanto.kamus; android.app.activity; android.database.cursor; android.database.sqlite.sqlitedatabase; 54
AGUS HARYANTO android.os.bundle; android.view.view; android.widget.edittext; android.widget.toast; public class MainActivity extends Activity { private SQLiteDatabase db = null; private Cursor kamuscursor = null; private EditText txtinggris; private EditText txtindonesia; private EditText txtjerman; private DatabaseHelper datakamus = null; public static final String INGGRIS = "inggris"; public static final String INDONESIA = "indonesia"; /** Called when the activity is first created. */ @Override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); datakamus = new DatabaseHelper(this); db = datakamus.getwritabledatabase(); setcontentview(r.layout.activity_main); txtinggris = (EditText) findviewbyid(r.id.txtinggris); txtindonesia = (EditText) findviewbyid(r.id.txtindonesia); txtjerman = (EditText) findviewbyid(r.id.txtjerman); public void getterjemahan(view view) { String bhsindonesia = ""; String bhsjerman=""; String englishword = txtinggris.gettext().tostring(); kamuscursor = db.rawquery("select _ID, INGGRIS, INDONESIA, JERMAN " + "FROM kamus where INGGRIS='" + englishword + "' ORDER BY INGGRIS", null); if (kamuscursor.movetofirst()) { 55 Android Database SQLITE
for (;!kamuscursor.isafterlast(); kamuscursor.movetonext()) { bhsindonesia = kamuscursor.getstring(2); bhsjerman = kamuscursor.getstring(3); else{ Toast.makeText(getBaseContext(), "Terjemahan Tidak ditemukan", Toast.LENGTH_SHORT).show(); txtindonesia.settext(bhsindonesia); txtjerman.settext(bhsjerman); @Override public void ondestroy() { super.ondestroy(); try { kamuscursor.close(); db.close(); catch (Exception e){ 5. Sekarang mari kita run projectnya 56
AGUS HARYANTO Pada isian Inggris ketikan run lalu klik button Terjemahkan. Coba isi inggris diisi dengan sepatu lalu klik Terjemahkan Coba inggris tidak diisi lalu klik Terjemahkan 6. Oke kita sudah berhasil membuat kamus, sekarang kita ingin menampilkan kata-kata dalam database kedalam list. 7. Buat Layout baru dengan nama row.xml lalu ketikan kode berikut <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/andr oid" android:layout_width="fill_parent" 57 Android Database SQLITE
android:layout_height="fill_parent" android:orientation="horizontal" android:paddingbottom="5sp" android:paddingtop="5sp" > <TextView android:id="@+id/inggris" android:layout_width="100sp" android:layout_height="wrap_content" android:layout_alignparentleft="true" /> <TextView android:id="@+id/indonesia" android:layout_width="100sp" android:layout_height="wrap_content" android:layout_torightof="@+id/inggris" /> <TextView android:id="@+id/jerman" android:layout_width="100sp" android:layout_height="wrap_content" android:layout_torightof="@+id/indonesia" /> </RelativeLayout> 8. Buat Layout baru dengan nama daftarkata.xml lalu ketikan kode berikut <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/andr oid" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/textview1" android:layout_width="100sp" android:layout_height="wrap_content" android:layout_alignparentleft="true" android:layout_alignparenttop="true" android:text="inggris" android:textsize="20sp" /> <TextView 58
AGUS HARYANTO android:id="@+id/textview2" android:layout_width="100sp" android:layout_height="wrap_content" android:layout_alignparenttop="true" android:layout_torightof="@+id/textview1" android:text="indonesia" android:textsize="20sp" /> <TextView android:id="@+id/textview3" android:layout_width="100sp" android:layout_height="wrap_content" android:layout_alignparenttop="true" android:layout_torightof="@+id/textview2" android:text="jerman" android:textsize="20sp" /> <ListView android:id="@+id/list1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" android:layout_alignparentleft="true" android:layout_below="@+id/textview1"/> </RelativeLayout> 9. Buat Class baru dengan nama Daftarkata.java lalu ketikkan kode berikut. package net.agusharyanto.kamus; android.app.activity; android.content.context; android.database.cursor; android.database.sqlite.sqlitedatabase; android.os.bundle; android.util.log; android.view.layoutinflater; android.view.view; android.view.viewgroup; android.widget.listview; android.widget.simplecursoradapter; 59 Android Database SQLITE
android.widget.textview; public class DaftarKata extends Activity { private DatabaseHelper dbhelper; private SQLiteDatabase db = null; private ListView listcontent = null; private Cursor kamuscursor = null; CustomCursorAdapter adapter; /** Called when the activity is first created. */ @Override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); dbhelper = new DatabaseHelper(this); setcontentview(r.layout.daftarkata); listcontent = (ListView) findviewbyid(r.id.list1); isdatalistview(); private void isdatalistview() { try { db = dbhelper.getwritabledatabase(); kamuscursor = db.query("kamus", new String[] { "_id", "inggris", "indonesia", "jerman", "_id>0", null, null, null, null); // startmanagingcursor( jasacursor); /* * Create an array to specify the fields we want to display in the * list (only the 'inggris,indonesia,jerman' column in this case) */ String[] from = new String[] { "inggris", "indonesia", "jerman" ; /* * and an array of the fields we want to bind those fieiplds to (in 60
AGUS HARYANTO * this case just the textview 'inggris,indonesia,jerman' from our new row.xml * layout above) */ int[] to = new int[] { R.id.inggris, R.id.indonesia, R.id.jerman ; /* Now create a simple cursor adapter.. */ adapter = new CustomCursorAdapter(this, R.layout.row, kamuscursor, from, to); // listview.setadapter(adapter); listcontent.setadapter(adapter); catch (Exception e) { e.printstacktrace(); finally { if (db!= null && db.isopen()) { db.close(); @Override public void ondestroy() { super.ondestroy(); try { kamuscursor.close(); catch (Exception e) { protected class CustomCursorAdapter extends SimpleCursorAdapter { private int layout; private LayoutInflater inflater; private Context context; public CustomCursorAdapter(Context context, 61 Android Database SQLITE
int layout, Cursor c, String[] from, int[] to) { super(context, layout, c, from, to); this.layout = layout; this.context = context; inflater = LayoutInflater.from(context); @Override public View newview(context context, Cursor cursor, ViewGroup parent) { Log.d("NewView", "*****xxx"); View v = inflater.inflate(r.layout.row, parent, false); return v; @Override public void bindview(view v, Context context, Cursor c) { // 1 is the column where you're getting your data from String inggris = c.getstring(1); String jerman = c.getstring(3); String indonesia = c.getstring(2); /** * Next set the name of the entry. */ TextView name_text = (TextView) v.findviewbyid(r.id.inggris); TextView des_text = (TextView) v.findviewbyid(r.id.jerman); TextView id_text = (TextView) v.findviewbyid(r.id.indonesia); des_text.settext(jerman); id_text.settext(indonesia); if (name_text!= null) { name_text.settext(inggris); 62
AGUS HARYANTO 10. Rubah bagian yang bercetak tebal pada AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/andr oid" package="net.agusharyanto.kamus" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="17" /> <application android:allowbackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/apptheme" > <activity android:name="net.agusharyanto.kamus.daftarkata" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application> </manifest> 11. Sekarang mari kita Run projectnya. 63 Android Database SQLITE
12. Kita sudah sukses menampilkan daftar kata, selanjutnya kita akan menyedian form untuk menambahkan kata. 13. Buat layout baru dengan nama tambahkata.xml selanjutnya ketikan kode berikut <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/andr oid" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > 64
/> AGUS HARYANTO <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="kamus Inggris Indonesia Jerman" <TextView android:id="@+id/textview01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="inggris :" > </TextView> <EditText android:id="@+id/txtinggris" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="" > </EditText> <TextView android:id="@+id/textview03" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="indonesia :" > </TextView> <EditText android:id="@+id/txtindonesia" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="" > </EditText> <TextView android:id="@+id/textview1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="jerman" > </TextView> <EditText android:id="@+id/txtjerman" android:layout_width="fill_parent" 65 Android Database SQLITE
android:layout_height="wrap_content" > </EditText> <Button android:id="@+id/btnterjemah" android:layout_width="fill_parent" android:layout_height="wrap_content" android:onclick="savedata" android:text="save Data" > </Button> </LinearLayout> 14. Buat class baru dengan nama TambahKata.java package net.agusharyanto.kamus; android.app.activity; android.content.contentvalues; android.database.sqlite.sqlitedatabase; android.os.bundle; android.view.view; android.widget.edittext; android.widget.toast; public class TambahKata extends Activity{ private SQLiteDatabase db = null; private EditText txtinggris; private EditText txtindonesia; private EditText txtjerman; private DatabaseHelper datakamus = null; public static final String INGGRIS= "inggris"; public static final String INDONESIA = "indonesia"; public static final String JERMAN = "JERMAN"; public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); datakamus = new DatabaseHelper(this); db = datakamus.getwritabledatabase(); setcontentview(r.layout.tambahkata); txtinggris = (EditText) findviewbyid(r.id.txtinggris); 66
AGUS HARYANTO txtindonesia = (EditText) findviewbyid(r.id.txtindonesia); txtjerman = (EditText) findviewbyid(r.id.txtjerman); public void savedata(view view) { String bhsindonesia = txtindonesia.gettext().tostring();; String bhsjerman= txtjerman.gettext().tostring(); String englishword = txtinggris.gettext().tostring(); ContentValues cv=new ContentValues(); cv.put(inggris, englishword); cv.put(indonesia, bhsindonesia); cv.put(jerman, bhsjerman); if (db.insert("kamus", INGGRIS, cv)>0){ Toast.makeText(getBaseContext(), "Save Data Success", Toast.LENGTH_SHORT).show(); else{ Toast.makeText(getBaseContext(), "Save Data Fail", Toast.LENGTH_SHORT).show(); @Override public void ondestroy() { super.ondestroy(); db.close(); 15. Rubah AndroidManifest.xml yang bercetak tebal <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/andr 67 Android Database SQLITE
oid" package="net.agusharyanto.kamus" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="17" /> <application android:allowbackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/apptheme" > <activity android:name="net.agusharyanto.kamus.tambahkata" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application> </manifest> 16. Sekarang mari kita run projectnya. 68
AGUS HARYANTO 17. Bagaimana melihat hasilnya? apa harus rubah AndroidManifest.xml. Cara yang lebih baik adalah dengan membuat menu yang dapat mengakses form Terjemahan, Daftar Kata dan Tambah Kata 18. Buat Class baru dengan nama MenuActivity.java lalu ketikkan kode berikut package net.agusharyanto.kamus; android.app.listactivity; android.content.intent; android.os.bundle; android.view.view; 69 Android Database SQLITE
android.widget.arrayadapter; android.widget.listview; android.widget.toast; public class MenuActivity extends ListActivity { String[] menuutama = new String[] { "Terjemah Kata", "Tambah Kata", "Daftar Kata", "Keluar Aplikasi" ; public void oncreate(bundle icicle) { super.oncreate(icicle); // Menset nilai array ke dalam list adapater sehingga data pada array // akan dimunculkan dalam list this.setlistadapter(new ArrayAdapter<String>(this, android.r.layout.simple_list_item_1, menuutama)); @Override /**method ini akan mengoveride method onlistitemclick yang ada pada class List Activity * method ini akan d1ipanggil apabilai ada salah satu item dari list menu yang dipilih */ protected void onlistitemclick(listview l, View v, int position, long id) { super.onlistitemclick(l, v, position, id); // Menangkap nilai text yang dklik Object o = this.getlistadapter().getitem(position); String pilihan = o.tostring(); // Menampilkan hasil pilihan menu dalam bentuk Toast tampilkanpilihan(pilihan); protected void tampilkanpilihan(string pilihan) { try { //Intent digunakan untuk sebagai pengenal suatu activity Intent i = null; 70
AGUS HARYANTO if (pilihan.equals("terjemah Kata")) { i = new Intent(this,MainActivity.class); else if (pilihan.equals("tambah Kata")) { i = new Intent(this, TambahKata.class); else if (pilihan.equals("daftar Kata")) { i = new Intent(this, DaftarKata.class); else if (pilihan.equals("keluar Aplikasi")) { finish(); else { Toast.makeText(this,"Anda Memilih: " + pilihan + ", Actionnya belum dibuat", Toast.LENGTH_LONG).show(); startactivity(i); catch (Exception e) { e.printstacktrace(); 19. Pada AndroidManifest.xml rubah dan tambahkan yang bercetak tebal <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/andr oid" package="net.agusharyanto.kamus" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="17" /> <application android:allowbackup="true" android:icon="@drawable/ic_launcher" 71 Android Database SQLITE
android:label="@string/app_name" android:theme="@style/apptheme" > <activity android:name="net.agusharyanto.kamus.menuactivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> <activity android:name="mainactivity" android:label="terjemah Kata"> </activity> <activity android:name="daftarkata" android:label="daftar Kata"> </activity> <activity android:name="tambahkata" android:label="tambah Kata"> </activity> </application> </manifest> 20. Sekarang mari kita run projectnya 72
AGUS HARYANTO Klik masing-masing menu. 21. Sekarang kita melangkah kebagian Rubah data dan Hapus data. Pasti kita memikirkan bagaiman cara menempatkan Edit dan Hapus ini. Aha kita letakan saja di DaftarKata. Jadi ketika satu baris kata di klik lama (long click) akan memunculkan menu edit dan hapus. 22. Buka file String.xml pada direktori value ketikan kode berikut <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">kamus</string> <string name="action_settings">settings</string> <string name="hello_world">hello world!</string> 73 Android Database SQLITE
<string name="ok">ok</string> <string name="save">simpan</string> <string name="cancel">cancel</string> <string name="add_title">edit Kamus</string> <string name="delete_title">hapus Kamus, And yakin?</string> </resources> 23. Tambahkan layout untuk edit data beri nama edit.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/andr oid" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/textview01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="inggris :" > </TextView> <EditText android:id="@+id/inggris" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="" > </EditText> <TextView android:id="@+id/textview03" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="indonesia :" > </TextView> <EditText android:id="@+id/indonesia" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="" > 74
AGUS HARYANTO </EditText> <TextView android:id="@+id/textview1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="jerman" > </TextView> <EditText android:id="@+id/jerman" android:layout_width="fill_parent" android:layout_height="wrap_content" > </EditText> </LinearLayout> 24. Buka kembali file DaftarKata.java lalu ketikan kode berikut package net.agusharyanto.kamus; android.app.activity; android.app.alertdialog; android.content.contentvalues; android.content.context; android.content.dialoginterface; android.database.cursor; android.database.sqlite.sqlitedatabase; android.os.bundle; android.view.contextmenu; android.view.layoutinflater; android.view.menu; android.view.menuitem; android.view.view; android.view.viewgroup; android.widget.adapterview; android.widget.edittext; android.widget.listview; android.widget.simplecursoradapter; android.widget.textview; public class DaftarKata extends Activity { private DatabaseHelper dbhelper; private SQLiteDatabase db = null; private ListView listcontent = null; 75 Android Database SQLITE
1; 2; private static final int EDIT_ID = Menu.FIRST + private static final int DELETE_ID = Menu.FIRST + private Cursor kamuscursor = null; CustomCursorAdapter adapter; /** Called when the activity is first created. */ @Override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); dbhelper = new DatabaseHelper(this); setcontentview(r.layout.daftarkata); listcontent = (ListView) findviewbyid(r.id.list1); isdatalistview(); registerforcontextmenu(listcontent); private void isdatalistview() { try { db = dbhelper.getwritabledatabase(); kamuscursor = db.query("kamus", new String[] { "_id", "inggris", "indonesia", "jerman", "_id>0", null, null, null, null); /* * Create an array to specify the fields we want to display in the * list (only the 'inggris,indonesia,jerman' column in this case) */ String[] from = new String[] { "inggris", "indonesia", "jerman" ; /* * and an array of the fields we want to bind those fieiplds to (in * this case just the textview 'inggris,indonesia,jerman' from our * new row.xml layout above) */ 76
AGUS HARYANTO int[] to = new int[] { R.id.inggris, R.id.indonesia, R.id.jerman ; /* Now create a simple cursor adapter.. */ adapter = new CustomCursorAdapter(this, R.layout.row, kamuscursor, from, to); // listview.setadapter(adapter); listcontent.setadapter(adapter); catch (Exception e) { e.printstacktrace(); finally { if (db!= null && db.isopen()) { // db.close(); @Override public void ondestroy() { super.ondestroy(); try { kamuscursor.close(); catch (Exception e) { @Override public void oncreatecontextmenu(contextmenu menu, View v, ContextMenu.ContextMenuInfo menuinfo) { menu.add(menu.none, DELETE_ID, Menu.NONE, "`Hapus").setIcon(R.drawable.ic_launche r).setalphabeticshortcut('e'); menu.add(menu.none, EDIT_ID, Menu.NONE, "Edit") 77 Android Database SQLITE
.seticon(r.drawable.ic_launche r).setalphabeticshortcut('d'); @Override public boolean oncontextitemselected(menuitem item) { switch (item.getitemid()) { case DELETE_ID: AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getmenuinfo(); delete(info.id); return (true); case EDIT_ID: AdapterView.AdapterContextMenuInfo infox = (AdapterView.AdapterContextMenuInfo) item.getmenuinfo(); Cursor ckamuscursor = db.rawquery( "SELECT _ID, inggris, indonesia, jerman " + "FROM kamus where _ID=" + infox.id, null); ckamuscursor.movetofirst(); edit(infox.id, ckamuscursor.getstring(1), ckamuscursor.getstring(2), ckamuscursor.getstring(3)); return (true); return (super.onoptionsitemselected(item)); private void edit(long id, String pinggris, String pindonesia, String pjerman) { LayoutInflater inflater = LayoutInflater.from(this); 78
AGUS HARYANTO View addview = inflater.inflate(r.layout.edit, null); EditText edinggris = (EditText) addview.findviewbyid(r.id.inggris); EditText edindonesia = (EditText) addview.findviewbyid(r.id.indonesia); EditText edjerman = (EditText) addview.findviewbyid(r.id.jerman); edinggris.settext(pinggris); edindonesia.settext(pindonesia); edjerman.settext(pjerman); final DialogWrapper wrapper = new DialogWrapper(addView); final long xid = id; /* * wrapper.inggrisfield.settext(pinggris); * wrapper.indonesiafield.settag(pindonesia) */ new AlertDialog.Builder(this).setTitle(R.string.add_title).setView(addView).setPositiveButton(R.string.sa ve, new DialogInterface.OnClickListener() { public void onclick(dialoginterface dialog, int whichbutton) { processedit(wrapper, xid); ).setnegativebutton(r.string.ca ncel, DialogInterface.OnClickListener() { onclick(dialoginterface dialog, new public void int whichbutton) { // ignore, just dismiss 79 Android Database SQLITE
).show(); private void delete(final long rowid) { if (rowid > 0) { new AlertDialog.Builder(this).setTitle(R.string.delet e_title).setpositivebutton(r.stri ng.ok, new DialogInterface.OnClickListener() { public void onclick(dialoginterface dialog, int whichbutton) { processdelete(rowid); ).setnegativebutton(r.stri ng.cancel, DialogInterface.OnClickListener() { void onclick(dialoginterface dialog, new public int whichbutton) { / / ignore, just dismiss ).show(); private void processedit(dialogwrapper wrapper, long id) { ContentValues values = new ContentValues(2); values.put("inggris", wrapper.getinggris()); values.put("indonesia", wrapper.getindonesia()); values.put("jerman", wrapper.getjerman()); 80
AGUS HARYANTO // db.update(table, values, whereclause, whereargs) null); db.update("kamus", values, "_id=" + id, kamuscursor.requery(); private void processdelete(long rowid) { String[] args = { String.valueOf(rowId) ; db.delete("kamus", "_ID=?", args); kamuscursor.requery(); class DialogWrapper { EditText inggrisfield = null; EditText indonesiafield = null; EditText jermanfield = null; View base = null; DialogWrapper(View base) { this.base = base; indonesiafield = (EditText) base.findviewbyid(r.id.indonesia); String getinggris() { return (getinggrisfield().gettext().tostring()); String getindonesia() { return (getindonesiafield().gettext().tostring()); String getjerman() { return (getjermanfield().gettext().tostring()); private EditText getinggrisfield() { if (inggrisfield == null) { inggrisfield = (EditText) 81 Android Database SQLITE
base.findviewbyid(r.id.inggris); return (inggrisfield); private EditText getindonesiafield() { if (indonesiafield == null) { indonesiafield = (EditText) base.findviewbyid(r.id.indonesia); return (indonesiafield); private EditText getjermanfield() { if (jermanfield == null) { jermanfield = (EditText) base.findviewbyid(r.id.jerman); return (jermanfield); protected class CustomCursorAdapter extends SimpleCursorAdapter { private int layout; private LayoutInflater inflater; private Context context; public CustomCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) { super(context, layout, c, from, to); this.layout = layout; this.context = context; inflater = LayoutInflater.from(context); @Override public View newview(context context, Cursor cursor, ViewGroup parent) { 82
AGUS HARYANTO View v = inflater.inflate(r.layout.row, parent, false); return v; @Override public void bindview(view v, Context context, Cursor c) { // 1 is the column where you're getting your data from String inggris = c.getstring(1); String jerman = c.getstring(3); String indonesia = c.getstring(2); /** * Next set the name of the entry. */ TextView name_text = (TextView) v.findviewbyid(r.id.inggris); TextView des_text = (TextView) v.findviewbyid(r.id.jerman); TextView id_text = (TextView) v.findviewbyid(r.id.indonesia); des_text.settext(jerman); id_text.settext(indonesia); if (name_text!= null) { name_text.settext(inggris); 25. Sekarang mari kita run projectnya 83 Android Database SQLITE
Lakukan skenario seperti ini. Pilih salah satu data lalu tekan yang lama lalu Edit, akan muncul jendela edit. Pilih salah satu data lalu tekan yang lama pada data tersebut akan muncul context menu, pilihlah hapus Hore, kita telah berhasil membuat aplikasi database sqlite pada android yang didalamanya sudah mencakup fungsi Create Read Update Delete (CRUD). Tugas 84
AGUS HARYANTO Buatlah Aplikasi yang ada fungsi CRUD SQLitenya contohnya Aplikasi Menu Makanan. Mempunyai Fitur List Menu makanan yang terdiri dari Nama Makanan dan Harganya, User juga dapat menambah menu baru, update menu dan hapus menu. 85 Android Database SQLITE
4 ANDROID GOOGLE MAP Tak dapat dipungkiri smartphone saat ini tidak saja dimanfaatkan untuk aplikasi data entry dan hiburan tetapi sekarang sudah dimanfaatkan oleh pengembang untuk mendevelop Aplikasi Location Base Service dimana salah satunya adalah membantu pengguna menemukan lokasi Point of Interest (POS) yang terdekat, misalnya ditengah jalan bensinya mau habis, bisa memanfaatkan aplikasi untuk mencari terminal pengisian bahan bakar terdekat. M E N A M P I L K A N D A T A GP S Hampir Semua Handphone ber OS android dilengkapi GPS, sebetulnya apasih GPS itu. GPS adalah singkatan dari Global Positionning System, dengan GPS kita dapat mengetahui lokasi kita berada yaitu data koordinat Latitude dan Longitudenya. Bagia yang pernah membuat aplikasi yang menggunakan MAP pasti sudah mengenal istilah ini. GPS hanyalah hardware, untuk memaksimalkannya kita perlu membuat aplikasi yang memanfaatkan GPS. Ada pertanyaan nih, setelah mengetahui fungsi GPS, kira-kira aplikasi apa yang akan kita bangun?
Ingat Aplikasi Social networking FourSquare, dimana pada foursquare kita dapat mengetahui posisi teman-teman kita yang sedang online, sehingga apabila ada yang jaraknya dekat dengan kita maka kita bisa copy darat. Sekarang kita masuk kemateri utama, mulai lah belajar dengan pertanyaan Bagaimanakah cara mendapatkan Lokasi kita saat ini dengan menggunakan GPS di android? Bagaimanakah cara menampilkannya dalam bentuk MAP? Mari kita buat project untuk menangkap koordinat dari GPS. 1. Buat New Android Project dengan nama LokasiKu 88
2. AGUS HARYANTO Edit layout activity_main.xml lalu ketikan kode berikut <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".mainactivity" > <TextView android:id="@+id/textview1" android:layout_width="80sp" android:layout_height="wrap_content" android:text="latitude : " /> <EditText android:id="@+id/edlatitude" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_aligntop="@+id/textview1" 89 Android Google Map
android:layout_torightof="@+id/textview1" android:editable="false" android:ems="10" > </EditText> <TextView android:id="@+id/textview2" android:layout_width="80sp" android:layout_height="wrap_content" android:layout_alignleft="@+id/textview1" android:layout_below="@+id/edlatitude" android:text="longitude : " /> <EditText android:id="@+id/edlongitude" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignleft="@+id/edlatitude" android:layout_aligntop="@+id/textview2" android:editable="false" android:ems="10" /> </RelativeLayout> 3. Edit class MainActivity.java lalu ketikan kode berikut package net.agusharyanto.lokasiku; android.app.activity; android.content.context; android.location.criteria; android.location.location; android.location.locationlistener; android.location.locationmanager; android.os.bundle; android.widget.edittext; android.widget.toast; public class MainActivity extends Activity implements LocationListener { private EditText latitutefield; private EditText longitudefield; 90
AGUS HARYANTO private LocationManager locationmanager; private String provider; */ /** Called when the activity is first created. @Override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); latitutefield = (EditText) findviewbyid(r.id.edlatitude); longitudefield = (EditText) findviewbyid(r.id.edlongitude); // Get the location manager locationmanager = (LocationManager) getsystemservice(context.location_service); // Define the criteria how to select the locatioin provider -> use // default Criteria criteria = new Criteria(); provider = locationmanager.getbestprovider(criteria, false); Location location = locationmanager.getlastknownlocation(provider); // Initialize the location fields if (location!= null) { System.out.println("Provider " + provider + " has been selected."); onlocationchanged(location); else { latitutefield.settext("lokasi tidak tersedia"); longitudefield.settext("lokasi tidak tersedia"); /* Request updates at startup */ @Override protected void onresume() { 91 Android Google Map
super.onresume(); locationmanager.requestlocationupdates(provider, 400, 1, this); /* Remove the locationlistener updates when Activity is paused */ @Override protected void onpause() { super.onpause(); locationmanager.removeupdates(this); @Override public void onlocationchanged(location location) { double lat = (double) (location.getlatitude()); double lng = (double) (location.getlongitude()); latitutefield.settext(string.valueof(lat)); longitudefield.settext(string.valueof(lng)); @Override public void onstatuschanged(string provider, int status, Bundle extras) { // TODO Auto-generated method stub @Override public void onproviderenabled(string provider) { Toast.makeText(this, "Enabled new provider " + provider, Toast.LENGTH_SHORT).show(); @Override public void onproviderdisabled(string provider) { Toast.makeText(this, "Disabled provider " + 92
provider, AGUS HARYANTO Toast.LENGTH_SHORT).show(); 4. Untuk menambahkan permission pada AndroidManifets.xml Tambahkan yang bercetak tebal <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/andr oid" package="net.agusharyanto.lokasiku" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="19" /> <uses-permission android:name="android.permission.internet" > </uses-permission> <uses-permission android:name="android.permission.access_fine_location" /> <uses-permission android:name="android.permission.access_coarse_locatio N" > </uses-permission> <application android:allowbackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/apptheme" > <activity android:name="net.agusharyanto.lokasiku.mainactivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.main" /> 93 Android Google Map
<category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application> </manifest> 5. Mari kita run projectnya Jika belum ada koordinat maka Latitude dan Longitude akan berisi Lokasi tidak tersedia. Untuk itu kita bisa menset koordinatnya melalui emulator kontrol. Untuk membuka emulator kontrol pada eclipse menu klik Window Show View Other lalu klik folder Android lalu pilih Emulator Cotrol. Isikan Latiude dan Longitude seperti diatas lalu klik Send, maka sekarang nilai Latitude dan Longitude pada emulator sudah terisi. 94
AGUS HARYANTO Selain melalui emulator control, untuk menset GPS kita juga bisa lakukan lewat telnet localhost 5554 lalu ketikan command geo fix -6.23326 106.85324 MENAMPILKAN MAP PA D A ANDROID Apakah informasi koordinat gps berupa nilai latitude dan longitude itu cukup bagi user untuk menunjukkan lokasinya. Tentu banyak user yang bingung, untuk itu kita ditantang bagaimana cara menginformasikan lokasi ke User. Beruntung android sudah menyiapkan Library Peta GoogleMap sehingga kita bisa memanfaatkannya untuk menampilkan Lokasi tersebut dipeta. 95 Android Google Map
Pertama kita harus menginstall Google Play Service. Pada Eclipse klik menu Window lalu klik Android SDK Manager Centang Google Play Services dari jendela Android SDK Manager klik folder Extra lalu centang Google Play Services Khusus untuk Map AVD yang dipakai harus yang Ada Goggle APIs, untuk itu dari jendela Android SDK Manager centang juga Google APIs (ARM System Image). Setelah instalasi selesai. Buatlah AVD yang menggunakan Google APIs 96
97 Android Google Map AGUS HARYANTO
Sekarang mari kita mulai kodingnya. 1. Buat New Android Project beri nama PetaLokasi. Catat nama packagenya net.agusharyanto.petalokasi karena ini akan digunakan untuk membuat API KEY Google Map V2. 98
AGUS HARYANTO 2. Langkah selanjutnya adalah menyediakan API KEY Googlemap. Karena saat ini Key untuk GoogleMap API v1 sudah tidak bisa lagi digunakan maka kita harus menggunakan Key GoogleMap API v2. 3. Cari lokasi file debug.keystore biasanya terdapat pada direktori c:\users\<user>\.android\debug.keystore contoh c:\users\agus\.android\debug.keystore 4. Masuk kedirektori bin pada java jdk contoh C:\Program Files\Java\jdk1.7.0_10\bin 5. Jalankan command untuk mendapatkan key debug.keystore sha1 dari Syntak Commandnya adalah keytool -list -v -alias androiddebugkey -keystore <path_to_debug_keystore>debug.keystore -storepass android -keypass android contoh eksekusinya keytool -list -v -alias androiddebugkey -keystore C:\Users\HP\.android\debug.keystore -storepass android -keypass android Catat nilai SHA1: 22:C8:72:0A:9A:88:9E:63:72:A9:23:0E:FE:70:36:3B:CE:3E:11:42 99 Android Google Map
Registerkan Key diatasi melalui Google Api Console (https://code.google.com/apis/console/?pli=1 ). Untuk masuk kesini kita harus punya Account GMAIL Klik Create project... akan muncul jendela New Project, Isi Project Name dengan Android Map Project 100
AGUS HARYANTO Setelah tombol create diklik tungg sebentar maka akan muncul project dashboard 101 Android Google Map
Klik Enable an API lalu Aktifkan Google Maps Android API V2 Sekarang Saatnya membuat Key untuk aplikasinya. Klik Google Maps Android V2 lalau klik Quota 102
103 Android Google Map AGUS HARYANTO
isikan dengan 22:C8:72:0A:9A:88:9E:63:72:A9:23:0E:FE:70:36:3B:CE:3E:11:42;ne t.agusharyanto.petalokasi Klik Create Catat API Keynya, ini akan digunakan dalam aplikasi. AIzaSyBeF0umtjOV4xQe8MJe1oZsEYfm3p3GzPc 104
AGUS HARYANTO 2. Selanjutnya kita harus menginclude Google Play Services sebagai library projectnya. Hal yang harus dilakukan terlibuh dahulu adalah meng Project Google Play Service Library ke workspace saat ini. Klik Import Android Project, set Root Directory ke direktori kita menginstall Google Play Service, misalnya saja C:\adt-bundle-windows-x8620131030\sdk\extras\google\google_play_services\libproject\googl e-play-services_lib Centang Copy projects into workspace 105 Android Google Map
Selanjutnya adalah menyertakan library ini dalam project kita. Caranya klik kanan pada project PetaLokasi lalu pilih properties 3. Kita harus mendaftarkan Key yang kita dapat pada AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="net.agusharyanto.petalokasi" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="14" 106
AGUS HARYANTO android:targetsdkversion="19" /> <permission android:name="net.agusharyanto.petalokasi.permission.maps_r ECEIVE" android:protectionlevel="signature" /> <uses-feature android:glesversion="0x00020000" android:required="true" /> <uses-permission android:name="android.permission.internet" /> <uses-permission android:name="android.permission.access_network_state" /> <uses-permission android:name="android.permission.write_external_storage" /> <!-The following two permissions are not required to use Google Maps Android API v2, but are recommended. --> <uses-permission android:name="android.permission.access_coarse_location" /> <uses-permission android:name="android.permission.access_fine_location" /> <application android:allowbackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/apptheme" > <activity android:name="net.agusharyanto.petalokasi.mainactivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> 107 Android Google Map
<meta-data android:name="com.google.android.maps.v2.api_key" android:value="aizasybef0umtjov4xqe8mje1ozseyfm3p3gzpc" /> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> </application> </manifest> 4. Edit file activity_main.xml lalu ketikkan kode berikut <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/andr oid" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".mainactivity" > <fragment android:id="@+id/map" android:layout_width="match_parent" android:layout_height="match_parent" class="com.google.android.gms.maps.mapfragment" /> </RelativeLayout> 5. Edit clas MainActivity.java lalu ketikan kode berikut package net.agusharyanto.petalokasi; android.app.activity; android.os.bundle; com.google.android.gms.maps.cameraupdatefactory; com.google.android.gms.maps.googlemap; 108
AGUS HARYANTO com.google.android.gms.maps.mapfragment; com.google.android.gms.maps.model.bitmapdescriptorfactory; com.google.android.gms.maps.model.latlng; com.google.android.gms.maps.model.marker; com.google.android.gms.maps.model.markeroptions; public class MainActivity extends Activity { static final LatLng RAGUNAN = new LatLng(-6.3039, 106.8267); static final LatLng TAMANMINI = new LatLng(6.29436, 106.8859); private GoogleMap map; @Override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); map = ((MapFragment) getfragmentmanager().findfragmentbyid(r.id.map)).getmap(); Marker ragunan = map.addmarker(new MarkerOptions().position(RAGUNAN).title("Ragunan")); Marker tamanmini = map.addmarker(new MarkerOptions().position(TAMANMINI).title("Taman Mini").snippet("Taman Mini itu Indah").icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher))); // Move the camera instantly to hamburg with a zoom of 15. map.movecamera(cameraupdatefactory.newlatlngzoom(ragunan, 15)); // Zoom in, animating the camera. map.animatecamera(cameraupdatefactory.zoomto(10), 2000, null); 109 Android Google Map
6. Agar kita dapat menjalankan project Gooogle Map API 2 ini di emulator kita perlu install 2 apk yaitu venton.apk dam gms.apk melalui adb command. Sebelum pastikan emulator (Bukan Google API) sudah dijalankan. 7. Mari kita jalankan projectnya. 110
AGUS HARYANTO Pertama akan muncul 2 marker, lalu tap lah masing-masing marker akan memunculkan info window. MENAMPILKAN DIRECTION PA D A MAP Tentunya akan lebih menarik apabila kita dapat menampilkan jalur yang harus ditempuh dari sebuah lokasi ke lokasi lainnya. Kita ingin apabila infowindow diklik maka akan muncul petunjuk jalur (driving direction) diantara kedua titik tersebut. Berikut langkah-langkahnya 8. Masih dalam project yang sama buat class baru dengan nama GmapV2Direction.java lalu ketikan kode berikut package net.agusharyanto.petalokasi; 111 Android Google Map
java.io.inputstream; java.util.arraylist; javax.xml.parsers.documentbuilder; javax.xml.parsers.documentbuilderfactory; org.apache.http.httpresponse; org.apache.http.client.httpclient; org.apache.http.client.methods.httppost; org.apache.http.impl.client.defaulthttpclient; org.apache.http.protocol.basichttpcontext; org.apache.http.protocol.httpcontext; org.w3c.dom.document; org.w3c.dom.node; org.w3c.dom.nodelist; android.util.log; com.google.android.gms.maps.model.latlng; public class GMapV2Direction { public final static String MODE_DRIVING = "driving"; public final static String MODE_WALKING = "walking"; public GMapV2Direction() { public Document getdocument(latlng start, LatLng end, String mode) { String url = "http://maps.googleapis.com/maps/api/directions/xml?" + "origin=" + start.latitude + "," + start.longitude + "&destination=" + end.latitude + "," + end.longitude + "&sensor=false&units=metric&mode=driving"; try { HttpClient httpclient = new DefaultHttpClient(); HttpContext localcontext = new BasicHttpContext(); HttpPost httppost = new HttpPost(url); 112
AGUS HARYANTO HttpResponse response = httpclient.execute(httppost, localcontext); InputStream in = response.getentity().getcontent(); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder (); Document doc = builder.parse(in); return doc; catch (Exception e) { e.printstacktrace(); return null; public String getdurationtext (Document doc) { NodeList nl1 = doc.getelementsbytagname("duration"); Node node1 = nl1.item(0); NodeList nl2 = node1.getchildnodes(); Node node2 = nl2.item(getnodeindex(nl2, "text")); Log.i("DurationText", node2.gettextcontent()); return node2.gettextcontent(); public int getdurationvalue (Document doc) { NodeList nl1 = doc.getelementsbytagname("duration"); Node node1 = nl1.item(0); NodeList nl2 = node1.getchildnodes(); Node node2 = nl2.item(getnodeindex(nl2, "value")); Log.i("DurationValue", node2.gettextcontent()); return Integer.parseInt(node2.getTextContent()); public String getdistancetext (Document doc) { NodeList nl1 = doc.getelementsbytagname("distance"); Node node1 = nl1.item(0); NodeList nl2 = node1.getchildnodes(); Node node2 = nl2.item(getnodeindex(nl2, "text")); 113 Android Google Map
Log.i("DistanceText", node2.gettextcontent()); return node2.gettextcontent(); public int getdistancevalue (Document doc) { NodeList nl1 = doc.getelementsbytagname("distance"); Node node1 = nl1.item(0); NodeList nl2 = node1.getchildnodes(); Node node2 = nl2.item(getnodeindex(nl2, "value")); Log.i("DistanceValue", node2.gettextcontent()); return Integer.parseInt(node2.getTextContent()); public String getstartaddress (Document doc) { NodeList nl1 = doc.getelementsbytagname("start_address"); Node node1 = nl1.item(0); Log.i("StartAddress", node1.gettextcontent()); return node1.gettextcontent(); public String getendaddress (Document doc) { NodeList nl1 = doc.getelementsbytagname("end_address"); Node node1 = nl1.item(0); Log.i("StartAddress", node1.gettextcontent()); return node1.gettextcontent(); public String getcopyrights (Document doc) { NodeList nl1 = doc.getelementsbytagname("copyrights"); Node node1 = nl1.item(0); Log.i("CopyRights", node1.gettextcontent()); return node1.gettextcontent(); public ArrayList<LatLng> getdirection (Document doc) { NodeList nl1, nl2, nl3; ArrayList<LatLng> listgeopoints = new ArrayList<LatLng>(); 114
AGUS HARYANTO nl1 = doc.getelementsbytagname("step"); if (nl1.getlength() > 0) { for (int i = 0; i < nl1.getlength(); i++) { Node node1 = nl1.item(i); nl2 = node1.getchildnodes(); Node locationnode = nl2.item(getnodeindex(nl2, "start_location")); nl3 = locationnode.getchildnodes(); Node latnode = nl3.item(getnodeindex(nl3, "lat")); double lat = Double.parseDouble(latNode.getTextContent()); Node lngnode = nl3.item(getnodeindex(nl3, "lng")); double lng = Double.parseDouble(lngNode.getTextContent()); listgeopoints.add(new LatLng(lat, lng)); locationnode = nl2.item(getnodeindex(nl2, "polyline")); nl3 = locationnode.getchildnodes(); latnode = nl3.item(getnodeindex(nl3, "points")); ArrayList<LatLng> arr = decodepoly(latnode.gettextcontent()); for(int j = 0 ; j < arr.size() ; j++) { listgeopoints.add(new LatLng(arr.get(j).latitude, arr.get(j).longitude)); locationnode = nl2.item(getnodeindex(nl2, "end_location")); nl3 = locationnode.getchildnodes(); latnode = nl3.item(getnodeindex(nl3, "lat")); lat = Double.parseDouble(latNode.getTextContent()); lngnode = nl3.item(getnodeindex(nl3, "lng")); lng = Double.parseDouble(lngNode.getTextContent()); listgeopoints.add(new LatLng(lat, lng)); 115 Android Google Map
return listgeopoints; private int getnodeindex(nodelist nl, String nodename) { for(int i = 0 ; i < nl.getlength() ; i++) { if(nl.item(i).getnodename().equals(nodename)) return i; return -1; private ArrayList<LatLng> decodepoly(string encoded) { ArrayList<LatLng> poly = new ArrayList<LatLng>(); int index = 0, len = encoded.length(); int lat = 0, lng = 0; while (index < len) { int b, shift = 0, result = 0; do { b = encoded.charat(index++) 63; result = (b & 0x1f) << shift; shift += 5; while (b >= 0x20); int dlat = ((result & 1)!= 0? ~(result >> 1) : (result >> 1)); lat += dlat; shift = 0; result = 0; do { b = encoded.charat(index++) 63; result = (b & 0x1f) << shift; shift += 5; while (b >= 0x20); int dlng = ((result & 1)!= 0? ~(result >> 1) : (result >> 1)); lng += dlng; 116
AGUS HARYANTO LatLng position = new LatLng((double) lat / 1E5, (double) lng / 1E5); poly.add(position); return poly; 9. Buat Class baru dengan nama DirectionActivity.java ketikkan kode berikut package net.agusharyanto.petalokasi; lalu java.util.arraylist; org.w3c.dom.document; android.app.activity; android.content.context; android.graphics.color; android.location.location; android.location.locationlistener; android.location.locationmanager; android.os.asynctask; android.os.bundle; com.google.android.gms.maps.cameraupdatefactory; com.google.android.gms.maps.googlemap; com.google.android.gms.maps.googlemap.oninfowindowclickliste ner; com.google.android.gms.maps.mapfragment; com.google.android.gms.maps.model.bitmapdescriptorfactory; com.google.android.gms.maps.model.latlng; com.google.android.gms.maps.model.marker; com.google.android.gms.maps.model.markeroptions; com.google.android.gms.maps.model.polylineoptions; public class DirectionActivity extends Activity { static final LatLng TAMANMINI = new LatLng(-6.29436, 106.8859); 117 Android Google Map
private GoogleMap map; private GMapV2Direction md; private LocationManager locmanager; private LocationListener loclistener; Marker ragunan = null; LatLng fromposition = new LatLng(-6.3039, 106.8267); LatLng toposition = TAMANMINI; @Override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); md = new GMapV2Direction(); map = ((MapFragment) getfragmentmanager().findfragmentbyid(r.id.map)).getmap(); Marker tamanmini = map.addmarker(new MarkerOptions().position(TAMANMINI).title("Taman Mini").snippet("Taman Mini Indonesia Indah")); // Move the camera instantly to hamburg with a zoom of 15. map.movecamera(cameraupdatefactory.newlatlngzoom(tamanmini, 15)); // Zoom in, animating the camera. map.animatecamera(cameraupdatefactory.zoomto(11), 2000, null); map.setoninfowindowclicklistener(new OnInfoWindowClickListener() { public void oninfowindowclick(marker marker) { String stitle = marker.gettitle(); if (!stitle.equals("current Location")) { 118
AGUS HARYANTO calldirectiontask(); ); initlocationmanager(); private void calldirectiontask() { String arg[] = { "dummy" ; new LongOperation().execute(arg); private class LongOperation extends AsyncTask<String, Void, Document> { @Override protected Document doinbackground(string... params) { Document doc = md.getdocument(fromposition, toposition, GMapV2Direction.MODE_DRIVING); return doc; @Override protected void onpostexecute(document result) { // this.dialog.cancel(); setresult(result); @Override protected void onpreexecute() { @Override protected void onprogressupdate(void... values) { 119 Android Google Map
public void setresult(document doc) { ArrayList<LatLng> directionpoint = md.getdirection(doc); PolylineOptions rectline = new PolylineOptions().width(3).color( Color.RED); for (int i = 0; i < directionpoint.size(); i++) { rectline.add(directionpoint.get(i)); map.addpolyline(rectline); /** * Initialize the location manager. */ private void initlocationmanager() { locmanager = (LocationManager) getsystemservice(context.location_service); loclistener = new LocationListener() { // method ini akan dijalankan apabila koordinat GPS berubah public void onlocationchanged(location newlocation) { tampilkanposisikemap(newlocation); public void onproviderdisabled(string arg0) { public void onproviderenabled(string arg0) { 120
AGUS HARYANTO public void onstatuschanged(string arg0, int arg1, Bundle arg2) { ; locmanager.requestlocationupdates(locationmanager.gps_provi DER, 5, 100, loclistener); Location location = locmanager.getlastknownlocation(locationman ager.gps_provider); tampilkanposisikemap(location); /** * This method will be called when current position changed is submitted via * the GPS. * * @param newlocation */ protected void tampilkanposisikemap(location newlocation) { LatLng currlok = new LatLng(newLocation.getLatitude(), newlocation.getlongitude()); fromposition = currlok; if (ragunan!= null)ragunan.remove(); ragunan = map.addmarker(new MarkerOptions().position(currlok).title( "Current Location").icon(BitmapDescriptorFactory.fromResource(R.draw able.ic_launcher))); map.movecamera(cameraupdatefactory.newlatlngzoom(currlok, 11)); // first remove old overlay 121 Android Google Map
10. Sebelum kita jalankan projectnya. Terlbih dahulu kita harus merubah AndroidMainfest.xml agar yang diryun adalah DirectionActivity maka ganti tulisan MainActivity dengan DirectionActivity. <activity android:name="net.agusharyanto.petalokasi.directionactivity " android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> 11. Sekarang mari kita jalankan projectnya. Terlihat Posisi Terakhir dipeta, kecilkan peta agar marker taman mini terlihat, klik marker taman mini lalu klik infowindownya akan muncul direction dari posisi kita ke taman mini 122
AGUS HARYANTO Tugas Buatlah Aplikasi yang menampilkan lokasi-lokasi disekitar kita yang datanya diambil dari Database SQLite 123 Android Google Map
5 A N D R O I D PH P M Y SQL Kali ini kita akan membahas Bagaimana Android dapat mengirim data ke server dan membacanya. Ada beberapa pendekatan untuk komunikasi dengan server ini tetapi yang sering dipakai adalah melalui http. Dengan demikian untuk mempraktekannya kita harus menginstall apache web server lengakap dengan PHP dan MySQLnya. CRUD ANDROID PHP MYSQL Aplikasi yang menggunakan database pada umumnya memiliki fungsi untuk Menampilkan data Menambah data Menghapus data Merubah data Database SQLite pada android mempunyai keterbatasan pada salah satunya pada kapasitas penyimpanan data. Akan bermasalah apabila kita memaksakan menyimpan data yang besar (lebih dari 10000 data) pada SQLite. Selain itu jika kita ingin perubahan data aplikasi dirasakan oleh semua user tanpa harus install ulang aplikasi, maka data harus disimpan di Server. Cara yang paling sering digunakan adalah dengan perantara Webserver, PHP dan MySQL. Dimana an-
droid untuk melakukan perubahan data atau mendapatkan data dari database server cukup dengan memanggil url php yang telah ditentukan. Agar lebih dimengerti mari kita buat aplikasi tentang maintenance data harga handphone yang database servernya menggunakan MySQL dengan Web Server Apache dan Server Side Scriptnya menggunakan PHP untuk itu hal yang penting untuk dilakukan sebelum memulai pembuatan aplikasinya adalah menyiaplkan environment servernya dengan menginstall XAMPP (Windows) atau LAMP (Linux). Setelah selesai Instalasi lalu kita lakukan langkah berikut. 1. Pekerjaan di MySql, buat database dan tablenya. CREATE DATABASE db_phone; CREATE TABLE tbl_phone ( id INT(4) NOT NULL AUTO_INCREMENT, phone_name VARCHAR(32) NOT NULL, price INT(10) NOT NULL, PRIMARY KEY (id) ) ENGINE=MyISAM; insert into tbl_phone values(null,'galaxy S3',6000000); insert into tbl_phone values(null,'galaxy Ace 2',3000000); insert into tbl_phone values( null,'htc One',6000000); 2. Siapkan Script PHP untuk memasukkan data baru ke tbl_phone, simpan dengan nama add_phone.php simpan didirectory document_root/phone contoh htdoc/phone jadi urlnya adalah http://yourdomain/phone/add_phone.php <?php $phone_name = $_POST['phone_name']; $price = $_POST['price']; $link = mysql_connect('localhost', 'user', 'password') or die('cannot connect to the DB'); mysql_select_db('db_phone', $link) or die('cannot select the DB'); /* grab the posts from the db */ 126
AGUS HARYANTO $query = "insert into tbl_phone (phone_name,price) values('". $phone_name."',".$price.")"; $result = mysql_query($query, $link) or die('error query: '.$query); if ($result == 1){echo "Save Data Success";else{ echo "Save Data Fail";?> 3. Siapkan Script untuk menampilkan data yang sudah disimpan, simpan dengan nama list_phone.php <?php $link = mysql_connect('localhost', 'user', 'password') or die('cannot connect to the DB'); mysql_select_db('db_phone', $link) or die('cannot select the DB'); $result["errorcode"]="0"; /* grab the posts from the db */ $query = "SELECT id, phone_name, price FROM tbl_phone"; $rs= mysql_query($query, $link) or die('errorquery: '.$query); $countrow= mysql_affected_rows(); $items = array(); while($row = mysql_fetch_object($rs)){ array_push($items, $row); if($countrow >0){ $result["errorcode"] = "1"; $result["data"] = $items; else{ $result["errormsg"] = "Tidak ada data"; echo json_encode($result);?> 4. Siapkan Script untuk Melakkukan perubahan data phone diserver, simpan dengan nama edit_phone.php <?php $id = $_POST['id']; $phone_name = $_POST['phone_name']; $price = $_POST['price']; $link = mysql_connect('localhost', 'user', 'password') or die('cannot connect to the DB'); 127 Android PHP MySQL
mysql_select_db('db_phone', $link) or die('cannot select the DB'); /* grab the posts from the db */ $query = "update tbl_phone set phone_name='$phone_name',price=$price where id=$id"; $result = mysql_query($query, $link) or die('error query: '.$query); if ($result == 1){echo "Save Data Success";else{ echo "Save Data Fail";?> 5. Siakan Scritpt untuk menghapus data phone di server, simpan dengan nama delete_phone.php <?php $id = $_POST['id']; $link = mysql_connect('localhost', 'user', 'password') or die('cannot connect to the DB'); mysql_select_db('db_phone', $link) or die('cannot select the DB'); /* grab the posts from the db */ $query = "delete from tbl_phone where id=$id"; $result = mysql_query($query, $link) or die('error query: '.$query); if ($result == 1){echo "Save Data Success";else{ echo "Save Data Fail";?> 6. Sekarang mari kita siapkan bagian androidnya, buat new android project MySQLPhone 128
AGUS HARYANTO 7. Buat Class HttpHelper lalu ketikkan kode berikut package net.agusharyanto.mysqlphone; java.io.bufferedreader; java.io.inputstream; java.io.inputstreamreader; 129 Android PHP MySQL
org.apache.http.httpresponse; org.apache.http.client.httpclient; org.apache.http.client.methods.httpget; org.apache.http.impl.client.defaulthttpclient; android.util.log; public class HttpHelper { /** * Method untuk Mengirimkan data kes erver event by button login diklik * * @param view */ public static String getrequest(string Url) { String sret=""; HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(Url); try { HttpResponse response = client.execute(request); sret= request(response); catch (Exception ex) { return sret; /** * Method untuk Menenrima data dari server * * @param response * @return */ public static String request(httpresponse response) { String result = ""; try { InputStream in = response.getentity().getcontent(); 130
BufferedReader( AGUS HARYANTO BufferedReader reader = new new InputStreamReader(in)); StringBuilder str = new StringBuilder(); String line = null; while ((line = reader.readline())!= null) { str.append(line + "\n"); in.close(); result = str.tostring(); catch (Exception ex) { result = "Error"; return result; Class HttpHelper ini digunakan untuk mengirim data keserver dan menangkap nilai yang dikembalikan server. 8. Buat class JSONFunction lalu ketikkan kode berikut package net.agusharyanto.mysqlphone; java.io.bufferedreader; java.io.inputstream; java.io.inputstreamreader; org.apache.http.httpentity; org.apache.http.httpresponse; org.apache.http.client.httpclient; org.apache.http.client.methods.httppost; org.apache.http.impl.client.defaulthttpclient; org.apache.http.params.basichttpparams; org.apache.http.params.httpconnectionparams; org.apache.http.params.httpparams; org.json.jsonexception; org.json.jsonobject; android.util.log; 131 Android PHP MySQL
public class JSONfunctions { public static JSONObject getjsonfromurl(string url) { InputStream is = null; String result = "0"; JSONObject jarray = null; try { HttpParams httpparameters = new BasicHttpParams(); int timeoutconnection = 60000; HttpConnectionParams.setConnectionTimeout(httpParameter s, timeoutconnection); int timeoutsocket = 60000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutsocket); HttpClient httpclient = new DefaultHttpClient(httpParameters); HttpPost httppost = new HttpPost(url); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getentity(); is = entity.getcontent(); catch (Exception e) { Log.e("log_tag", "Error intimeout http connection " + e.tostring()); // convert response to string try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new 132
StringBuilder(); AGUS HARYANTO null) { String line = null; while ((line = reader.readline())!= sb.append(line + "\n"); is.close(); result = sb.tostring(); catch (Exception e) { Log.e("log_tag", "Error converting result " + e.tostring()); result = "{\"errorcode\":\"0\""; try { jarray = new JSONObject(result); catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.tostring()); result = "{\"errorcode\":\"0\""; try { jarray = new JSONObject(result); catch (JSONException e1) { // TODO Auto-generated catch block e1.printstacktrace(); return jarray; public static String getstringjsonfromurl(string url) { InputStream is = null; String result = "0"; // http post try { HttpParams httpparameters = new BasicHttpParams(); int timeoutconnection = 60000; 133 Android PHP MySQL
HttpConnectionParams.setConnectionTimeout(httpParameter s, timeoutconnection); int timeoutsocket = 60000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutsocket); HttpClient httpclient = new DefaultHttpClient(httpParameters); HttpPost(url); HttpPost httppost = new HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getentity(); is = entity.getcontent(); catch (Exception e) { Log.e("log_tag", "Error intimeout http connection " + e.tostring()); // convert response to string try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readline())!= null) { sb.append(line + "\n"); is.close(); result = sb.tostring(); catch (Exception e) { Log.e("log_tag", "Error converting result " + e.tostring()); result = "{\"errorcode\":\"0\""; 134
AGUS HARYANTO return result; Class JSONFunction ini digunakan untuk menangkap nilai kembalian dari server yang datanya berupa JSON 9. Buat Layoutbaru dengan nama add.xml lalu ketikan kode berikut <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/andr oid" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:text="smart Phone Name :" android:id="@+id/textview01" android:layout_width="wrap_content" android:layout_height="wrap_content"></textview> <EditText android:text="" android:id="@+id/edtname" android:layout_width="fill_parent" android:layout_height="wrap_content"></edittext> <TextView android:text="price :" android:id="@+id/textview02" android:layout_width="wrap_content" android:layout_height="wrap_content"></textview> <EditText android:text="" android:id="@+id/edtprice" android:layout_width="fill_parent" android:layout_height="wrap_content"></edittext> <Button android:text="simpan" android:id="@+id/btnsave" android:layout_width="fill_parent" android:layout_height="wrap_content"></button> </LinearLayout> 10. Buat Layout dengan nama listphone.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout 135 Android PHP MySQL
xmlns:android="http://schemas.android.com/apk/res/andr oid" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/textview1" android:layout_width="150sp" android:layout_height="wrap_content" android:layout_alignparentleft="true" android:layout_alignparenttop="true" android:text="phone Name" android:background="@drawable/border" android:textsize="20sp" android:padding="5sp" /> /> <TextView android:id="@+id/textview2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignparenttop="true" android:background="@drawable/border" android:layout_torightof="@+id/textview1" android:text="price" android:textsize="20sp" android:padding="5sp" <ListView android:id="@+id/list1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" android:layout_alignparentleft="true" android:layout_below="@+id/textview1"/> </RelativeLayout> 11. Buat layout dengan nama row.xml <?xml version="1.0" encoding="utf-8"?> 136
AGUS HARYANTO <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/andr oid" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal" android:paddingbottom="5sp" android:paddingtop="5sp" > <TextView android:id="@+id/phonename" android:layout_width="150sp" android:layout_height="wrap_content" android:layout_alignparentleft="true" android:padding="5sp" /> <TextView android:id="@+id/price" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="right" android:layout_torightof="@+id/phonename" android:padding="5sp" /> <TextView android:id="@+id/idphone" android:layout_width="0sp" android:layout_height="wrap_content" android:layout_torightof="@+id/indonesia" android:visibility="gone"/> </RelativeLayout> 12. Semua Layout sudah siap, saatnya membuat bagian javanya. Pada awal yang ditampilkan adalah list smartphone dan harganya, buat class baru dengan nama ListDataPhoneActivity.java package net.agusharyanto.mysqlphone; java.util.arraylist; java.util.hashmap; org.json.jsonarray; org.json.jsonexception; 137 Android PHP MySQL
org.json.jsonobject; android.app.activity; android.app.progressdialog; android.content.context; android.content.intent; android.os.asynctask; android.os.bundle; android.util.log; android.view.contextmenu; android.view.menu; android.view.menuitem; android.view.view; android.widget.adapterview; android.widget.listadapter; android.widget.listview; android.widget.simpleadapter; android.widget.toast; public class ListDataPhoneActivity extends Activity { /** Called when the activity is first created. */ private ListView listview1; private static final int REQUEST_CODE = 1; private ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>(); private static final int ADD_ID = Menu.FIRST + 1; private static final int EDIT_ID = Menu.FIRST + 2; private static final int DELETE_ID = Menu.FIRST + 3; @Override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.listphone); try { getdataphone(); catch (Exception e) { Log.e("log_tag", "Error parsing data " + e.tostring()); 138
AGUS HARYANTO /** * Class CallWebPageTask untuk implementasi class AscyncTask */ private class requesttask extends AsyncTask<String, Void, String> { private ProgressDialog dialog; protected Context applicationcontext; private String actionflag; @Override protected void onpreexecute() { this.dialog = ProgressDialog.show(applicationContext, "Load Data From Server Process", "Please Wait...", true); urls) { @Override protected String doinbackground(string... { String response = ""; response = getdataserver(urls[0]); return response; @Override protected void onpostexecute(string result) this.dialog.cancel(); if (actionflag.equals("list")) { if (result.equals("1")) setlistdata(); else if (actionflag.equals("delete")) { getdataphone(); public void getdataphone() { mylist.clear(); 139 Android PHP MySQL
requesttask task = new requesttask(); task.applicationcontext = ListDataPhoneActivity.this; task.actionflag = "list"; String url = "http://192.168.235.1/phone/list_phone.php"; task.execute(new String[] { url ); public String getdataserver(string url) { String sret = "1"; JSONObject json = JSONfunctions.getJSONfromURL(url); try { if (json.getstring("errorcode").equals("0")) { Toast.makeText(getBaseContext(), json.getstring("errormsg"), Toast.LENGTH_SHORT).show(); sret = "0"; JSONArray makanan = json.getjsonarray("data"); for (int i = 0; i < makanan.length(); i++) { HashMap<String, String> map = new HashMap<String, String>(); JSONObject jsonobj = makanan.getjsonobject(i); map.put("id", jsonobj.getstring("id")); ; map.put("phone_name", jsonobj.getstring("phone_name")); map.put("price", jsonobj.getstring("price")); 140
AGUS HARYANTO mylist.add(map); catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.tostring()); return sret; private void showtoast(string msg, int flag) { Toast.makeText(getBaseContext(), "Result " + msg, Toast.LENGTH_LONG).show(); private void setlistdata() { listview1 = (ListView) findviewbyid(r.id.list1); ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.row, new String[] { "phone_name", "price", new int[] { R.id.phonename, R.id.price ); listview1.setadapter(adapter); registerforcontextmenu(listview1); @Override public void oncreatecontextmenu(contextmenu menu, View v, ContextMenu.ContextMenuInfo menuinfo) { menu.add(menu.none, ADD_ID, Menu.NONE, "Add").setIcon(R.drawable.ic_launche r).setalphabeticshortcut('a'); menu.add(menu.none, EDIT_ID, Menu.NONE, "Edit").setIcon(R.drawable.ic_launche 141 Android PHP MySQL
r).setalphabeticshortcut('d'); menu.add(menu.none, DELETE_ID, Menu.NONE, "Delete").setIcon(R.drawable.ic_launche r).setalphabeticshortcut('e'); @Override public boolean oncontextitemselected(menuitem item) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getmenuinfo(); int idphone = (int) info.id; HashMap<String, String> o = (HashMap<String, String>) listview1.getitematposition(idphone); switch (item.getitemid()) { case ADD_ID: adddata(o, "add"); return (true); case DELETE_ID: deletedata(o); return (true); case EDIT_ID: editdata(o, "edit"); return (true); return (super.onoptionsitemselected(item)); private void editdata(hashmap<string, String> o, String action) { Log.d("****editData*****", "ïd:" + o.get("id")); callintent(o, action); 142
AGUS HARYANTO o) { private void deletedata(hashmap<string, String> requesttask task = new requesttask(); task.applicationcontext = ListDataPhoneActivity.this; task.actionflag = "delete"; String url = "http://192.168.235.1/phone/delete_phone.php?id=" + o.get("id"); task.execute(new String[] { url ); private void adddata(hashmap<string, String> o, String action) { callintent(o, action); private void callintent(hashmap<string, String> o, String action) { Intent i = new Intent(this, AddPhoneActivity.class); i.putextra("action", action); i.putextra("dataphone", o); startactivityforresult(i, REQUEST_CODE); @Override protected void onactivityresult(int requestcode, int resultcode, Intent data) { if (resultcode == RESULT_OK && requestcode == REQUEST_CODE) { if (data.hasextra("refreshflag")) { if (data.getextras().getstring("refreshflag").equals("1")) getdataphone(); 143 Android PHP MySQL
13. Tentunya Aplikasikita tidak hanya menampilkan data saja tetapi dapat juga menambahkan data dan mengedit data, buat class baru dengan nama AddPhoneActivity.java package net.agusharyanto.mysqlphone; java.io.unsupportedencodingexception; java.net.urlencoder; java.util.hashmap; android.app.activity; android.content.intent; android.os.asynctask; android.os.bundle; android.util.log; android.view.view; android.widget.button; android.widget.edittext; android.widget.toast; public class AddPhoneActivity extends private EditText edtname; private EditText edtprice; Activity { private Button btnsave; // Seusuaikan url dengan nama domain yang anda gunakan private String url = ""; String action=""; String phoneid=""; /** * Method yang dipanggil pada saat aplikaasi dijalankan * */ @Override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.add); edtname = (EditText) findviewbyid(r.id.edtname); edtprice = (EditText) findviewbyid(r.id.edtprice); 144
AGUS HARYANTO btnsave = (Button) findviewbyid(r.id.btnsave); Bundle extras = getintent().getextras(); if (extras == null) { return; action = extras.getstring("action"); HashMap <String,String> dataphone= (HashMap<String, String>) extras.get("dataphone"); if (action.equals("edit")){ edtname.settext(dataphone.get("phone_name")); edtprice.settext(dataphone.get("price")); phoneid=dataphone.get("id"); // daftarkan even onclick pada btnsave btnsave.setonclicklistener(new Button.OnClickListener() { @Override public void onclick(view v) { try { if (action.equals("add")) { url="http://192.168.235.1/phone/add_phone.php"; else{ url="http://192.168.235.1/phone/edit_phone.php"; String phone_name = URLEncoder.encode(edtName.getText().toString(), "utf-8"); String price = URLEncoder.encode(edtPrice.getText().toString(), "utf-8"); url += "?phone_name=" + phone_name + "&price=" + price; if (action.equals("edit")){ 145 Android PHP MySQL
url+="&id="+phoneid; Log.d("url**","url:"+url); new RequestTask().execute(url); catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printstacktrace(); ); @Override public void finish() { Intent data = new Intent(); data.putextra("refreshflag", "1"); setresult(result_ok, data); super.finish(); private void setresult(string result){ Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show(); finish(); class RequestTask extends AsyncTask<String, String, String>{ @Override protected String doinbackground(string... uri) { String responsestring = null; responsestring= HttpHelper.getRequest(uri[0]); 146
AGUS HARYANTO return responsestring; @Override protected void onpostexecute(string result) { super.onpostexecute(result); setresult(result); //Do anything with response.. 14. Edit AndroidManifest.xml lalu ketikan kode berikut <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/andr oid" package="net.agusharyanto.mysqlphone" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="17" /> <uses-permission android:name="android.permission.internet" /> <application android:allowbackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/apptheme" > <activity android:name="net.agusharyanto.mysqlphone.listdataphon eactivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.main" /> 147 Android PHP MySQL
<category android:name="android.intent.category.launcher" /> </intent-filter> </activity> <activity android:name="addphoneactivity" android:label="add Edit"/> </application> </manifest> 15. Sekarang mari kita jalankan programnya. Tekan yang lama pada salah satu baris 148
AGUS HARYANTO Akan muncul konteks menu, jika ingin menambah data sentuh ADD, untuk merubah data sentuh Edit, untuk menghapus data sentih Delete. 149 Android PHP MySQL
Tugas Buatlah Aplikasi User Management yang inputannya terdiri dari username, password, nama_lengkap. 150
5 PENUTUP S E M A N G AT Setelah memnyelesaikan materi yang ada dibuku ini, berarti kita sudah punya modal dasar untuk membuat aplikasi android sendiri. Disini kita sudah mempelajari tentang Dasar pembuatan project android Dasar Layout dan viewnya Aplikasi Android CRUD SQLite (Kamus) alokasi) Aplikasi Peta dengan Android Googlemaps API V2 (PetAplikasi CRUD PHP MySQL (Smartphone Price) Ilmu itu harus sering dilatih agar semakin mantap penguasaanya dan kita semkin produktif. Tanpa sering latihan janganlah kita bermimpi jadi programmer hebat dan produktif. Jadi harus semangat. SEMINAR WORKSHOP ANDROID Untuk kampus atau sekolah yang berminat mengadakan seminar atau workshop android atau lainnya bisa hubungi saya di email agus.superwriter@gmail.com,twitter @agus_inovator atau di 08551000444 / 089673371119. Khusus untuk luar kota biaya transportasi dan akomodasi ditanggung penyelenggara acara.
REFERENSI Untuk buku Android Fast Track ini, saya menggunakan referensi dari http://developerandroid.com http://stackoverflow.com http://vogella.com http://mobile.tutplus.com Beginning Android 4 Application Development Wei Meng Lee 152