Anda di halaman 1dari 105

i

Android Application and Development


Disusun Oleh :
Ardiansyah Prasaja, S.Kom
Nanang Agung Nugroho

Editor :
Sigit Arifianto, S.T

Hak Cipta 2016, pada penerbit


Dilarang memperbanyak tanpa seijin dari penerbit.

Diterbitkan Oleh :
Pusat Studi Mobile Technology Innovation Center (MoTic)
Universitas Ahmad Dahlan
Jl. Gondosuli No 1. Semaki Yogyakarta
Diterbitkan untuk kalangan terbatas.

ii

Kata Pengantar
Pertama-tama puji dan syukur kami panjatkan ke hadirat Allah SWT yang telah memberikan karunia
berupa nikmat kesehatan dan kejernihan berpikir sehingga bisa menyelesaikan penulisan modul
pelatihan Android dan Web.

Permintaan akan pemrogram piranti bergerak (mobile) dan web masih sangat besar. Sedangkan
pada kenyataannya ketersediaan tenaga terampil di kedua bidang tersebut di lapangan masih selalu
kurang untuk dipenuhi. Untuk itu Pusat Studi MoTIC UAD berinisiatif untuk turut berkontribusi
dengan menghasilkan talenta-talenta pemrogram Android dan Web yang terampil.

Modul ini dibuat sebagai pegangan dan acuan peserta selama masa pelatihan. Modul ini terdiri dari
bab-bab yang dibuat berurut sesuai jenjang materi yang diberikan, mulai dari dasar-dasar hingga
tingkat menengah. Harapannya peserta bisa terbantu dalam mengikuti langkah demi langkah
petunjuk yang ada di dalamnya dengan mudah. Akan tetapi, untuk lebih meningkatkan kemampuan
lebih lanjut tentu saja tidak cukup jika hanya mengandalkan modul ini. Peserta harus aktif berlatih
untuk memecahkan masalah-masalah yang lebih kompleks dan rumit.

Demikianlah semoga modul pelatihan ini bisa memberikan banyak manfaat kepada peserta sehingga
bisa senantiasa membantu dalam masa pelatihan dan di pascapelatihan. Masukan yang sifatnya
membangun sangat kami nantikan untuk terus menerus meningkatkan kualitas dan isi modul ini.

Yogyakarta, Maret 2016

Pusat Studi MoTIC UAD

iii

Daftar Isi

Kata Pengantar ................................................................................................................................ iii


Daftar Isi .......................................................................................................................................... iv

Materi 1 Pengenalan Android ...................................................................................................... 1


Materi 2 User Interface ................................................................................................................ 10
Materi 3 Dialogs .......................................................................................................................... 20
Materi 4 Listview .......................................................................................................................... 26
Materi 5 Gridview ......................................................................................................................... 35
Materi 6 Intens ............................................................................................................................. 40
Materi 7 Fragment ....................................................................................................................... 44
Materi 8 Navigation Drawer ......................................................................................................... 51
Materi 9 Webview ....................................................................................................................... 60
Materi 10 Android Google Maps ................................................................................................... 66
Materi 11 SQLite ............................................................................................................................ 76
Materi 12 Android dan Web Service .............................................................................................. 94

iv

I.

Pengenalan Android

A. Membuat Project Baru


Langkah-langkah untuk membuat project baru di Android Studio :
1. Create New Project -> Isikan nama aplikasi -> klik Next

2. Pilih minimum SDK -> klik Next

3. Pilih Add No Activity -> klik Finish

4. Klik kanan folder res -> New -> XML -> Layout XML File

5. Isikan nama file layout -> klik Finish

6. Pada file activity_main.xml tambahkan widget TextView, sebagai berikut:

7. Di dalam folder res/values, buka file string.xml dan tambahkan source code
sebagai berikut:

8. Di dalam folder app/java, klik kanan di package -> NEW -> Java Class

9. Isikan nama kelas -> klik OK

10. Di dalam file MainActivity, Ketikkan kode sebagai berikut:

11. Buka folder app/manifests, buka file AndroidManifest.xml. Ketikkan kode


sebagai berikut:

12. Pada toolbar android studio klik


5

Run

B. Pengenalan Pemrograman Berorientasi Objek


Pemrograman berorientasi objek (Object Oriented Programming) merupakan
pemrograman yang berorientasikan objek, dimana semua data dan fungsi berada
dalam class-class atau objek-objek.
Ada beberapa istilah yang harus diketahui dalam pemrograman berorientasi objek,
yaitu sebagai berikut:
-

Kelas
Kelas adalah kumpulan atas definisi data dan fungsi-fungsi dalam suatu unit
untuk suatu tujuan tertentu.

Attribute
Attribute merupakan nilai data yang terdapat pada suatu object yang berasal dari
class. Attribute merepresentasikan karakteristik dari suatu object.

Method
Method adalah sesuatu yang dapat dilakukan oleh objek. Method menentukan
perilaku objek, yakni

apa yang terjadi ketika objek itu dibuat serta berbagai

operasi yang dapat dilakukan objek.

Encapsulation
Encapsulation adalah kombinasi data dan fungsionalitas dalam sebuah unit
tunggal sebagai bentuk untuk menyembunyikan detail informasi.

Inheritance
Inheritance adalah pewarisan yang artinya sebuah class dapat mewarisi atribut
dan method dari class lain.

Langkah selanjutnya implementasi ke dalam project yang sudah dibuat sebelumnya:


1. Klik kanan package -> New
2. Isikan nama package

3. Klik kanan package yang baru dibuat, pilih New -> Java Class
4. Isikan nama class dengan nama Person

5. Di dalam class Person, ketikkan code sebagai berikut:

6. Buat class MyName dengan code sebagai berikut:

7. Buka file activity_main.xml dan tambahkan code sebagai berikut:

8. Buka class MainActivity, ketikkan code sebagai berikut:

9. Pada toolbar android studio klik

Run

II.

User Interface

A. Linear Layout
Linear layout adalah tampilan yang semua widget-widgetnya berada dalam posisi
searah, yaitu vertikal atau horisontal. Langkah selanjutnya implementasi ke dalam
sebuah project:
1. Create New Project -> Isikan nama aplikasi -> klik Next

10

2. Pilih minimum SDK -> klik Next

3. Pilih empty activity -> klik Next

11

4. Isikan nama activity -> klik Finish

5. Buka file activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.app.layoutlinear.MainActivity">
<EditText
android:id="@+id/edtNama"
android:hint="@string/edt_nama"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/edtPhone"
android:inputType="phone"
android:hint="@string/edt_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/edtEmail"
android:inputType="textEmailAddress"
android:hint="@string/edt_email"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btnOK"
android:text="@string/btn_ok"
android:layout_width="match_parent"

12

android:layout_height="wrap_content" />
<TextView
android:id="@+id/txtIdentitas"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

6. Buka file strings.xml


<resources>
<string name="app_name">Layoutlinear</string>
<string name="edt_nama">Nama</string>
<string name="edt_phone">Telpon</string>
<string name="edt_email">Email</string>
<string name="btn_ok">OK</string>
</resources>

7. Buka file MainActivity.java


package com.app.layoutlinear;
import
import
import
import
import
import

android.support.v7.app.AppCompatActivity;
android.os.Bundle;
android.view.View;
android.widget.Button;
android.widget.EditText;
android.widget.TextView;

public class MainActivity extends AppCompatActivity {


EditText edtNama;
EditText edtPhone;
EditText edtEmail;
Button btnOk;
TextView txtIdentitas;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtNama = (EditText)findViewById(R.id.edtNama);
edtPhone = (EditText) findViewById(R.id.edtPhone);
edtEmail = (EditText)findViewById(R.id.edtEmail);
btnOk = (Button)findViewById(R.id.btnOK);
txtIdentitas = (TextView)findViewById(R.id.txtIdentitas);
btnOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String nama = edtNama.getText().toString();
String phone = edtPhone.getText().toString();
String email = edtEmail.getText().toString();
txtIdentitas.setText("Nama : " + nama + "\n" +
"Phone : " + phone + "\n" +
"Email : " + email);
}
});
}
}

13

8. Pada toolbar android studio klik

Run

B. Relative Layout
Relative layout adalah tampilan yang semua widget-widgetnya dapat diposisikan
dimana saja. Langkah selanjutnya implementasi ke dalam sebuah project.
1. Create New Project -> Isikan nama aplikasi -> klik Next

14

2. Pilih minimum SDK -> klik Next

3. Pilih empty activity -> klik Next

15

4. Isikan nama activity -> klik Finish

5. Pilih activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
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_margin"
android:paddingTop="@dimen/activity_vertical_margin">
<EditText
android:id="@+id/edtNama"
android:hint="@string/edt_nama"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/edtPhone"
android:layout_below="@+id/edtNama"
android:inputType="phone"
android:hint="@string/edt_phone"
android:layout_width="190dp"
android:layout_height="wrap_content" />
<Spinner
android:id="@+id/spinTipe"
android:layout_below="@id/edtNama"
android:layout_toRightOf="@id/edtPhone"
android:layout_toEndOf="@+id/edtPhone"
android:entries="@array/type_phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<EditText
android:id="@+id/edtEmail"
android:layout_below="@+id/edtPhone"

16

android:inputType="textEmailAddress"
android:hint="@string/edt_email"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<RadioGroup
android:id="@+id/rgroup"
android:layout_below="@+id/edtEmail"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/rbtnPria"
android:text="@string/rbtn_pria"
android:checked="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<RadioButton
android:id="@+id/rbtnPerempuan"
android:text="@string/rbtn_perempuan"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RadioGroup>
<Button
android:id="@+id/btnOK"
android:layout_below="@+id/rgroup"
android:text="@string/btn_ok"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/txtIdentitas"
android:layout_below="@+id/btnOK"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>

6. Buka file strings.xml


<resources>
<string
<string
<string
<string
<string
<string
<string

name="app_name">Layoutrelative</string>
name="edt_nama">Name</string>
name="edt_phone">Phone</string>
name="edt_email">Email</string>
name="btn_ok">OK</string>
name="rbtn_pria">Male</string>
name="rbtn_perempuan">Female</string>

<string-array name="type_phone">
<item>Home</item>
<item>Mobile</item>
</string-array>
</resources>

17

7. Buka file MainActivity.java


package com.app.layoutrelative;
import
import
import
import
import
import
import
import
import

android.support.v7.app.AppCompatActivity;
android.os.Bundle;
android.view.View;
android.widget.Button;
android.widget.EditText;
android.widget.RadioButton;
android.widget.RadioGroup;
android.widget.Spinner;
android.widget.TextView;

public class MainActivity extends AppCompatActivity {


EditText edtNama;
EditText edtPhone;
EditText edtEmail;
Button btnOk;
TextView txtIdentitas;
RadioGroup rgJenisKelamin;
RadioButton rbJenisKelamin;
Spinner spinTipe;
String
String
String
String
String

nama;
phone;
tipe;
email;
jenisKelamin;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtNama = (EditText)findViewById(R.id.edtNama);
edtPhone = (EditText) findViewById(R.id.edtPhone);
edtEmail = (EditText)findViewById(R.id.edtEmail);
rgJenisKelamin = (RadioGroup)findViewById(R.id.rgroup);
spinTipe = (Spinner)findViewById(R.id.spinTipe);
btnOk = (Button)findViewById(R.id.btnOK);
txtIdentitas = (TextView)findViewById(R.id.txtIdentitas);
btnOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int selectRGroup =
rgJenisKelamin.getCheckedRadioButtonId();
rbJenisKelamin = (RadioButton)findViewById(selectRGroup);
nama = edtNama.getText().toString();
phone = edtPhone.getText().toString();
tipe = spinTipe.getSelectedItem().toString();
email = edtEmail.getText().toString();
jenisKelamin = rbJenisKelamin.getText().toString();
txtIdentitas.setText("Name : " + nama + "\n" +
tipe + " phone : " + phone + "\n" +
"Email : " + email + "\n" +
"Gender : " + jenisKelamin);
}
});
}
}

18

8. Pada toolbar android studio klik

19

Run

III.

Dialogs

Dialogs adalah tampilan kecil yang meminta pengguna untuk membuat keputusan atau
masukkan informasi tambahan. Contoh penggunaan dialogs pada android.

20

Tahapan implementasi.
1. Create New Project -> Isikan nama aplikasi -> klik Next

2. Pilih minimum SDK -> klik Next

21

3. Pilih empty activity -> klik Next

4. Isikan nama activity -> klik Finish

5. Buka file activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
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_margin"
android:paddingTop="@dimen/activity_vertical_margin">

22

<EditText
android:id="@+id/edtNama"
android:hint="@string/edt_nama"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/edtPhone"
android:layout_below="@+id/edtNama"
android:inputType="phone"
android:hint="@string/edt_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/edtEmail"
android:layout_below="@+id/edtPhone"
android:inputType="textEmailAddress"
android:hint="@string/edt_email"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<RadioGroup
android:id="@+id/rgroup"
android:layout_below="@+id/edtEmail"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/rbtnPria"
android:text="@string/rbtn_pria"
android:checked="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<RadioButton
android:id="@+id/rbtnPerempuan"
android:text="@string/rbtn_perempuan"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RadioGroup>
<Button
android:id="@+id/btnOK"
android:layout_below="@+id/rgroup"
android:text="@string/btn_ok"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/txtIdentitas"
android:layout_below="@+id/btnOK"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>

23

6. Buka file strings.xml


<resources>
<string name="app_name">AlertDialog</string>
<string name="edt_nama">Nama</string>
<string name="edt_phone">Telpon</string>
<string name="edt_email">Email</string>
<string name="btn_ok">OK</string>
<string name="rbtn_pria">Laki-laki</string>
<string name="rbtn_perempuan">Perempuan</string>
</resources>

7. Buka file MainActivity.java


package com.app.layoutlinear;
import
import
import
import
import
import
import
import
import
import

android.app.AlertDialog;
android.content.DialogInterface;
android.support.v7.app.AppCompatActivity;
android.os.Bundle;
android.view.View;
android.widget.Button;
android.widget.EditText;
android.widget.RadioButton;
android.widget.RadioGroup;
android.widget.TextView;

public class MainActivity extends AppCompatActivity {


EditText edtNama;
EditText edtPhone;
EditText edtEmail;
Button btnOk;
TextView txtIdentitas;
RadioGroup rgJenisKelamin;
RadioButton rbJenisKelamin;
String
String
String
String

nama;
phone;
email;
jenisKelamin;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtNama = (EditText)findViewById(R.id.edtNama);
edtPhone = (EditText) findViewById(R.id.edtPhone);
edtEmail = (EditText)findViewById(R.id.edtEmail);
rgJenisKelamin = (RadioGroup)findViewById(R.id.rgroup);
btnOk = (Button)findViewById(R.id.btnOK);
txtIdentitas = (TextView)findViewById(R.id.txtIdentitas);
btnOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int selectRGroup = rgJenisKelamin.getCheckedRadioButtonId();
rbJenisKelamin = (RadioButton)findViewById(selectRGroup);
nama = edtNama.getText().toString();
phone = edtPhone.getText().toString();
email = edtEmail.getText().toString();
jenisKelamin = rbJenisKelamin.getText().toString();

24

AlertDialog.Builder builder = new


AlertDialog.Builder(MainActivity.this);
builder.setMessage("Apakah identitas anda sudah sesuai?")
.setPositiveButton("Benar", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
txtIdentitas.setText("Nama : " + nama + "\n" +
"Phone : " + phone + "\n" +
"Email : " + email + "\n" + "Jenis Kelamin :
" + jenisKelamin);
}
}).setNegativeButton("Salah", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
txtIdentitas.setText("Silahkan isikan kembali
identitas anda.");
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
}

8. Pada toolbar android studio klik

Run

25

IV.

Listview

List view adalah tampilan yang digunakan untuk menampilkan data atau item dalam satu
kolom. Tahap implementasi ke dalam kode program, sebagai berikut:
A. Listview satu item
1. Create New Project -> Isikan nama aplikasi -> klik Next

26

2. Pilih minimum SDK -> klik Next

3. Pilih empty activity -> klik Next

27

4. Isikan nama activity -> klik Finish

5. Buka file activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.app.listviewoneitem.MainActivity">
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>

6. Buka file strings.xml


<resources>
<string name="app_name">ListviewOneItem</string>
<string-array name="list_item">
<item>Merah</item>
<item>Kuning</item>
<item>Hijau</item>
<item>Biru</item>
<item>Pink</item>
<item>Putih</item>
<item>Hitam</item>
<item>Abu-abu</item>
<item>Orange</item>
<item>Coklat</item>
<item>Ungu</item>
</string-array>
</resources>

28

7. Buka file MainActivity.java


package com.app.listviewoneitem;
import
import
import
import

android.support.v7.app.AppCompatActivity;
android.os.Bundle;
android.widget.ArrayAdapter;
android.widget.ListView;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1,
getResources().getStringArray(R.array.list_item));
ListView listView = (ListView)findViewById(R.id.listview);
listView.setAdapter(adapter);
}
}

8. Pada toolbar android studio klik Run

B. Listview multiple item


1. Create New Project -> Isikan nama aplikasi -> klik Next

29

2. Pilih minimum SDK -> klik Next

3. Pilih empty activity -> klik Next

30

4. Isikan nama activity -> klik Finish

5. Buka file activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.app.listviewmultipleitem.MainActivity">
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>

6. Buka file strings.xml


<resources>
<string name="app_name">ListviewMultipleItem</string>
<string-array name="array_nama">
<item>Batman</item>
<item>Ironman</item>
<item>Captain Amerika</item>
<item>Doraemon</item>
<item>Naruto</item>
<item>Zoro</item>
</string-array>
<string-array name="array_email">
<item>Batman@gmail.com</item>
<item>Ironman@gmail.com</item>
<item>CaptainAmerika@gmail.com</item>
<item>Doraemon@gmail.com</item>

31

<item>Naruto@gmail.com</item>
<item>Zoro@gmail.com</item>
</string-array>
<string-array name="array_phone">
<item>085725345670</item>
<item>085725345671</item>
<item>085725345672</item>
<item>085725345673</item>
<item>085725345674</item>
<item>085725345675</item>
</string-array>
</resources>

7. Buat file list_item.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_margin="5dp"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/itemNama"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/itemPhone"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/itemEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

8. Buat file class CustomAdapter.java


package com.app.listviewmultipleitem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import java.util.List;
public class CustomAdapter extends BaseAdapter{
List<View> items;
public CustomAdapter(List<View> items) {
this.items = items;
}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int position) {

32

return items.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
return items.get(position);
}
}

9. Buat file class Identitas.java


package com.app.listviewmultipleitem;
public class Identitas {
public String nama;
public String phone;
public String email;
public String getNama() {
return nama;
}
public void setNama(String nama) {
this.nama = nama;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}

10. Buka file MainActivity.java


package com.app.listviewmultipleitem;
import
import
import
import
import
import

android.support.v7.app.AppCompatActivity;
android.os.Bundle;
android.view.LayoutInflater;
android.view.View;
android.widget.ListView;
android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {

33

ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.listview);
fillData();
}
private List<Identitas> getIdentitas(){
List<Identitas> list = new ArrayList<>();
String[] nama =
getResources().getStringArray(R.array.array_nama);
String[] email =
getResources().getStringArray(R.array.array_email);
String[] phone =
getResources().getStringArray(R.array.array_phone);
for(int i = 0; i < 6 ; i++){
Identitas identitas = new Identitas();
identitas.setNama(nama[i]);
identitas.setEmail(email[i]);
identitas.setPhone(phone[i]);
list.add(identitas);
}
return list;
}
private void fillData(){
List<Identitas> list = getIdentitas();
View view;
List<View> views = new ArrayList<>();
LayoutInflater inflater =
LayoutInflater.from(getApplicationContext());
TextView txtNama;
TextView txtEmail;
TextView txtPhone;
for(int i=0; i < list.size(); i++){
view = inflater.inflate(R.layout.list_item, listView, false);
txtNama = (TextView)view.findViewById(R.id.itemNama);
txtEmail = (TextView)view.findViewById(R.id.itemEmail);
txtPhone = (TextView)view.findViewById(R.id.itemPhone);
String name = "Nama : " + list.get(i).getNama();
String email = "Email : " + list.get(i).getEmail();
String phone = "Phone : " + list.get(i).getPhone();
txtNama.setText(name);
txtEmail.setText(email);
txtPhone.setText(phone);
views.add(view);
}
listView.setAdapter(new CustomAdapter(views));
}
}

11. Pada toolbar android studio klik


34

Run

V.

Grid View

Grid view adalah tampilan yang digunakan untuk menampilkan data atau item
berdasarkan kolom dan baris.
1. Create New Project -> Isikan nama aplikasi -> klik Next

35

2. Pilih minimum SDK -> klik Next

3. Pilih empty activity -> klik Next

36

4. Isikan nama activity -> klik Finish

5. Buka file activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_margin="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numColumns="2"
android:verticalSpacing="5dp"
android:horizontalSpacing="5dp"
android:gravity="center"/>

6. Buat file layout grid_item.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/imgView"
android:contentDescription="@string/app_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/lblNama"
android:layout_centerHorizontal="true"
android:textColor="@android:color/black"
android:layout_below="@+id/imgView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>

37

7. Buat class CustomAdapter.java


package com.app.gridviewlayout;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import java.util.List;
public class CustomAdapter extends BaseAdapter{
List<View> items;
public CustomAdapter(List<View> items) {
this.items = items;
}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int position) {
return items.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return items.get(position);
}
}

8. Buka file MainActivity.java


package com.app.gridviewlayout;
import
import
import
import
import
import
import

android.support.v7.app.AppCompatActivity;
android.os.Bundle;
android.view.LayoutInflater;
android.view.View;
android.widget.GridView;
android.widget.ImageView;
android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private int[] mThumb = {R.drawable.kue1, R.drawable.kue2,
R.drawable.kue3,
R.drawable.kue1, R.drawable.kue2, R.drawable.kue3,
R.drawable.kue1, R.drawable.kue2};
private String[] mKue = {"Kue Satu", "Kue Dua", "Kue Tiga",
"Kue Empat", "Kue Lima", "Kue Enam",
"Kue Tujuh", "Kue Delapan"};
GridView gridView;
@Override

38

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = (GridView)findViewById(R.id.gridview);
fillData();
}
private void fillData(){
View view;
List<View> views = new ArrayList<>();
LayoutInflater inflater =
LayoutInflater.from(getApplicationContext());
ImageView img;
TextView lblNama;
for(int i=0; i<8; i++){
view = inflater.inflate(R.layout.grid_item, gridView, false);
img = (ImageView) view.findViewById(R.id.imgView);
lblNama = (TextView)view.findViewById(R.id.lblNama);
img.setImageResource(mThumb[i]);
lblNama.setText(mKue[i]);
views.add(view);
}
gridView.setAdapter(new CustomAdapter(views));
}
}

9. Pada toolbar android studio klik

Run

39

VI.

Intents

1. Create New Project -> Isikan nama aplikasi -> klik Next

2. Pilih minimum SDK -> klik Next

40

3. Pilih empty activity -> klik Next

4. Isikan nama activity -> klik Finish

41

5. Buka file activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
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_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.app.intentsapp.MainActivity">
<EditText
android:id="@+id/edtNama"
android:hint="@string/hint_nama"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/edtTlp"
android:hint="@string/hint_tlp"
android:inputType="phone"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btnOk"
android:text="@string/btn_ok"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

6. Buka file strings.xml


<resources>
<string name="app_name">Intentsapp</string>
<string name="hint_nama">Nama</string>
<string name="hint_tlp">Telpon</string>
<string name="btn_ok">Oke</string>
</resources>

7. Buat file activity_data.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_margin="15dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/txtData"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

42

8. Buat file class DataActivity.java


package com.app.intentsapp;
import
import
import
import

android.app.Activity;
android.content.Intent;
android.os.Bundle;
android.widget.TextView;

public class DataActivity extends Activity{


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data);
TextView txtData = (TextView)findViewById(R.id.txtData);
Intent intent = getIntent();
String nama = intent.getStringExtra("nama");
String tlp = intent.getStringExtra("telpon");
String data = nama + "\n" + tlp;
txtData.setText(data);
}
}

9. Buka file AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app.intentsapp">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".DataActivity">
</activity>
</application>
</manifest>

10. Pada toolbar android studio klik

Run

43

VII. Fragment
1. Create New Project -> Isikan nama aplikasi -> klik Next

2. Pilih minimum SDK -> klik Next

44

3. Pilih empty activity -> klik Next

4. Isikan nama activity -> klik Finish

5. Buka file activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.app.fragmentapps.MainActivity">

45

<android.support.design.widget.TabLayout
android:id="@+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>

6. Buat file fragment_satu.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_gravity="center"
android:gravity="center"
android:background="@android:color/holo_red_light"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/fragSatu"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

7. Buat file fragment_dua.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_gravity="center"
android:gravity="center"
android:background="@android:color/holo_green_light"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/fragDua"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

8. Buat file fragment_tiga.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@android:color/holo_blue_dark"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/fragTiga"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

46

9. Buka file MainActivity.java


package com.app.fragmentapps;
import
import
import
import

android.support.design.widget.TabLayout;
android.support.v4.view.ViewPager;
android.support.v7.app.AppCompatActivity;
android.os.Bundle;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentAdapter adapter = new
FragmentAdapter(getSupportFragmentManager());
TabLayout tabLayout = (TabLayout)findViewById(R.id.tablayout);
ViewPager viewPager = (ViewPager)findViewById(R.id.viewpager);
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
}
}

10. Buat file FragmentSatu.java


package com.app.fragmentapps;
import
import
import
import
import
import
import

android.os.Bundle;
android.support.annotation.Nullable;
android.support.v4.app.Fragment;
android.view.LayoutInflater;
android.view.View;
android.view.ViewGroup;
android.widget.TextView;

public class FragmentSatu extends Fragment{


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_satu, container,
false);
TextView textView = (TextView)view.findViewById(R.id.fragSatu);
textView.setText(getResources().getString(R.string.fragment_satu));
return view;
}
}

11. Buat file FragmentDua.java


package com.app.fragmentapps;
import
import
import
import
import
import
import

android.os.Bundle;
android.support.annotation.Nullable;
android.support.v4.app.Fragment;
android.view.LayoutInflater;
android.view.View;
android.view.ViewGroup;
android.widget.TextView;

47

public class FragmentDua extends Fragment{


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_dua, container,
false);
TextView textView = (TextView)view.findViewById(R.id.fragDua);
textView.setText(getResources().getString(R.string.fragment_dua));
return view;
}
}

12. Buat file FragmentTiga.java


package com.app.fragmentapps;
import
import
import
import
import
import
import

android.os.Bundle;
android.support.annotation.Nullable;
android.support.v4.app.Fragment;
android.view.LayoutInflater;
android.view.View;
android.view.ViewGroup;
android.widget.TextView;

public class FragmentTiga extends Fragment{


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tiga, container,
false);
TextView textView = (TextView)view.findViewById(R.id.fragTiga);
textView.setText(getResources().getString(R.string.fragment_tiga));
return view;
}
}

13. Buat file FragmentAdapter.java


package com.app.fragmentapps;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class FragmentAdapter extends FragmentStatePagerAdapter{
public FragmentAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position){
case 0:
fragment = new FragmentSatu();
break;
case 1:
fragment = new FragmentDua();
break;

48

case 2:
fragment = new FragmentTiga();
break;
}
return fragment;
}
@Override
public int getCount() {
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return "Tab 1";
case 1:
return "Tab 2";
case 2:
return "Tab 3";
default:
return null;
}
}
}

14. Buka file AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app.fragmentapps">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

15. Buka file gradle, tambahkan


compile 'com.android.support:design:23.2.1'

16. Buka file strings.xml


<resources>
<string name="app_name">FragmentApps</string>
<string name="fragment_satu">Fragment Satu</string>
<string name="fragment_dua">Fragment Dua</string>
<string name="fragment_tiga">Fragment Tiga</string>
</resources>

49

17. Pada toolbar android studio klik

Run

50

VIII.

Navigation Drawer

Navigation drawer adalah panel yang menampilkan pilihan navigasi utama


aplikasi di tepi kiri layar.Sebagian besar tersembunyi, tetapi akan tampil ketika
pengguna gesekan jari dari tepi kiri layar atau, selain itu juga bisa ditampilkan
dengan menyentuh ikon drawer di action bar.
1. Create New Project -> Isikan nama aplikasi -> klik Next

51

2. Pilih minimum SDK -> klik Next

3. Pilih empty activity -> klik Next

4. Isikan nama activity -> klik Finish

52

5. Buat file tool_bar.xml


<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="@dimens/abc_action_bar_default_height_material"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:background="@color/PrimaryColor"/>

6. Buat file header.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="190dp"
android:background="@drawable/background_material"
android:orientation="vertical">
<de.hdodenhof.circleimageview.CircleImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/profile_image"
android:layout_width="76dp"
android:layout_height="76dp"
android:src="@drawable/profile"
app:border_color="#FF000000"
android:layout_marginLeft="24dp"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginStart="24dp" />
<TextView

53

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/header_nama"
android:textSize="14sp"
android:textColor="#FFF"
android:textStyle="bold"
android:gravity="start"
android:paddingBottom="4dp"
android:id="@+id/username"
android:layout_above="@+id/email"
android:layout_alignLeft="@+id/profile_image"
android:layout_alignStart="@+id/profile_image" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/header_email"
android:id="@+id/email"
android:gravity="start"
android:layout_marginBottom="8dp"
android:textSize="14sp"
android:textColor="#fff"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/username"
android:layout_alignStart="@+id/username" />
</RelativeLayout>

7. Buat file content_fragment.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/content_inbox"
android:padding="8dp"
android:textColor="#fff"
android:background="@color/PrimaryColor"
android:textSize="28sp"
android:id="@+id/textView"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>

8. Buka file activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.app.navigationlayout.MainActivity">
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical">
<include
android:id="@+id/toolbar"
layout="@layout/tool_bar"/>
<FrameLayout

54

android:id="@+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="@+id/navigation_view"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_gravity="start"
app:headerLayout="@layout/header"
app:menu="@menu/drawer"/>
</android.support.v4.widget.DrawerLayout>

9. Buka file colors.xml


<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="PrimaryColor">#2196F3</color>
<color name="PrimaryDarkColor">#1976D2</color>
</resources>

10. Buka file strings.xml


<resources>
<string name="app_name">NavigationLayout</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="navigation_item_1">Home</string>
<string name="navigation_item_2">Events</string>
<string name="starred_string">Starred</string>
<string name="inbox_string">Inbox</string>
<string name="sent_mail_string">Sent mail</string>
<string name="draft_string">Drafts</string>
<string name="subheader">Subheader</string>
<string name="trash_string">Trash</string>
<string name="all_mail_string">All mails</string>
<string name="spam_string">Spams</string>
<string name="closeDrawer">Navigation View</string>
<string name="openDrawer">Navigation View Closed</string>
<string name="content_inbox">INBOX</string>
<string name="content_starred">STARRED</string>
<string name="header_nama">Android</string>
<string name="header_email">Android@gmail.com</string>
</resources>

11. Buka file styles.xml


<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/PrimaryColor</item>
<item name="colorPrimaryDark">@color/PrimaryDarkColor</item>
<item name="colorAccent">@color/PrimaryColor</item>
</style>
</resources>

55

12. Buat file drawer.xml


<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="@+id/inbox"
android:checked="false"
android:icon="@drawable/ic_inbox_black"
android:title="@string/inbox_string" />
<item
android:id="@+id/starred"
android:checked="false"
android:icon="@drawable/ic_star_black"
android:title="@string/starred_string" />
<item
android:id="@+id/sent_mail"
android:checked="false"
android:icon="@drawable/ic_send_black"
android:title="@string/sent_mail_string" />
<item
android:id="@+id/drafts"
android:checked="false"
android:icon="@drawable/ic_drafts_black"
android:title="@string/draft_string" />
<item
android:id="@+id/allmail"
android:checked="false"
android:icon="@drawable/ic_email_black"
android:title="@string/all_mail_string" />
<item
android:id="@+id/trash"
android:checked="false"
android:icon="@drawable/ic_delete_black"
android:title="@string/trash_string" />
<item
android:id="@+id/spam"
android:checked="false"
android:icon="@drawable/ic_error_black"
android:title="@string/spam_string" />
</group>
</menu>

13. Buka file MainActivity.java


package com.app.navigationlayout;
import
import
import
import
import
import
import
import
import
import

android.support.design.widget.NavigationView;
android.support.v4.app.FragmentTransaction;
android.support.v4.widget.DrawerLayout;
android.support.v7.app.ActionBarDrawerToggle;
android.support.v7.app.AppCompatActivity;
android.os.Bundle;
android.support.v7.widget.Toolbar;
android.view.MenuItem;
android.view.View;
android.widget.Toast;

public class MainActivity extends AppCompatActivity {

56

//Defining Variables
Toolbar toolbar;
NavigationView navigationView;
DrawerLayout drawerLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing Toolbar and setting it as the actionbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing NavigationView
navigationView = (NavigationView)
findViewById(R.id.navigation_view);
//Setting Navigation View Item Selected Listener to handle the item
click of the navigation menu
navigationView.setNavigationItemSelectedListener(new
NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Checking if the item is in checked state or not, if not
make it in checked state
if(menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
//Closing drawer on item click
drawerLayout.closeDrawers();
switch (menuItem.getItemId()){
case R.id.inbox:
Toast.makeText(getApplicationContext(),"Inbox
Selected",Toast.LENGTH_SHORT).show();
ContentFragment fragment = new ContentFragment();
FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame, fragment);
fragmentTransaction.commit();
return true;
case R.id.starred:
Toast.makeText(getApplicationContext(),"Stared
Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.sent_mail:
Toast.makeText(getApplicationContext(),"Send
Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.drafts:
Toast.makeText(getApplicationContext(),"Drafts
Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.allmail:
Toast.makeText(getApplicationContext(),"All Mail
Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.trash:
Toast.makeText(getApplicationContext(),"Trash
Selected",Toast.LENGTH_SHORT).show();

57

return true;
case R.id.spam:
Toast.makeText(getApplicationContext(),"Spam
Selected",Toast.LENGTH_SHORT).show();
return true;
default:
Toast.makeText(getApplicationContext(),"Somethings
Wrong",Toast.LENGTH_SHORT).show();
return true;
}
}
});
// Initializing Drawer Layout and ActionBarToggle
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle = new
ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.openDrawer,
R.string.closeDrawer){
@Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we
dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
@Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we
dont want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawerLayout.addDrawerListener(actionBarDrawerToggle);
//calling sync state is necessay or else your hamburger icon wont
show up
actionBarDrawerToggle.syncState();
}
}

14. Buat file class ContentFragment.java


package com.app.navigationlayout;
import
import
import
import
import
import

android.os.Bundle;
android.support.annotation.Nullable;
android.support.v4.app.Fragment;
android.view.LayoutInflater;
android.view.View;
android.view.ViewGroup;

public class ContentFragment extends Fragment{


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v;
v = inflater.inflate(R.layout.content_fragment,container,false);
return v;
}
}

58

15. Pada toolbar android studio klik Run

59

IX.

WebView

WebView adalah sebuah class pada Android yang berfungsi sebagai semacam sandbox
untuk menampilkan dan menjalan aplikasi mobile yang berbasiskan web, entah itu HTML5,
JQuery Mobile, dan sebagainya. Cara gampangnya WebView itu seperti Android browser,
tetapi tidak mempunyai address bar tempat memasukkan alamat URL. Karena URL yang
mau kita buka sudah didefinisikan di aplikasi dan tidak bisa kita ganti.

Dalam implementasinya, WebView mempunyai dua buah klien yang bisa kita gunakan
untuk me-render halaman web, dan tiap-tiap klien tersebut mempunyai fungsionalitas yang
berbeda-beda. Kedua klien tersebut adalah WebViewClient dan WebChromeClient.

WebViewClient adalah sebuah browser klien yang menyediakan fungsi-fungsi dasar


dalam menampilkan halaman web. Sedangkan, WebChromeClient adalah browser klien yang
menyediakan fitur-fitur advanced dalam rendering halaman web, kebanyakan berhubungan
dengan interaksi antara browser dengan javascript, menampilkan objek seperti video, dan
fitur-fitur advanced lainnya. Kalian bisa menggunakan kedua klien tersebut, namun apabila
kalian hanya ingin me-render halaman web yang tidak membutuhkan banyak fitur (misal
berisi HTML saja, tanpa javascript) maka kalian cukup menggunakan WebViewClient.

Pada dasarnya inisialisasi sebuah aplikasi WebView di Android adalah seperti berikut :
webView= (WebView) findViewById(R.id.webview);
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new WebViewClient());

//mengaktifkan dukungan untuk javascript


webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.portal.uad.ac.id");

Adapun untuk aplikasi yang lebih advanced, contoh kodenya seperti berikut :
webView = (WebView) findViewById(R.id.wv_twoh);
webSettings = (WebSettings) webView.getSettings();

String url ="http://www.portal.uad.ac.id";

60

// memberitahukan browser untuk mengaktifkan Wide


ViewPort
webSettings.setUseWideViewPort(true);

// otomatis website akan diload dengan zoom out


webSettings.setLoadWithOverviewMode(true);

// otomatis menampilkan javascript window


webSettings.setJavaScriptCanOpenWindowsAutomatically(true);

// mengaktifkan fungsi-fungsi storage HTML5


webSettings.setDatabaseEnabled(true);
webSettings.setDomStorageEnabled(true);
String databasePath = this.getApplicationContext()
.getDir("databases", Context.MODE_PRIVATE).getPath();
webSettings.setDatabasePath(databasePath);
webSettings.setJavaScriptEnabled(true);

// mengaktifkan fitur geolocation (deteksi lokasi)


webSettings.setGeolocationEnabled(true);
webSettings.setGeolocationDatabasePath(databasePath);

// menonaktifkan hw acceleration yang kadang bermasalah


// dengan mengaktifkan software layer
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
webView.loadUrl(url);

61

Berikut contoh implementasi dari webview di applikasi android:

62

Tahap implementasi

1.

File > New Project > isikan nama project

2.

Next > pilih minimum SDK

63

3.

Next > addActivity to Project > finish

4. Edit activity class yang dibuat tadi menjadi seperti di bawah ini
package com.nangs.MyWebView.controller;
import
import
import
import
import
import
import
import
import
import
import

android.app.Activity;
android.content.Intent;
android.net.Uri;
android.os.Bundle;
android.support.v7.app.AppCompatActivity;
android.view.Window;
android.webkit.WebChromeClient;
android.webkit.WebSettings;
android.webkit.WebView;
android.webkit.WebViewClient;
android.widget.Toast;

import com.nangs.MyWebView.R;
/**
* Created by nangs-an on 09/03/16.
*/
public class Webview extends AppCompatActivity {
WebView myWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myWebView = new WebView(this);
setContentView(myWebView);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setBuiltInZoomControls(true);
myWebView.getSettings().setDisplayZoomControls(false);

64

final Activity activity = this;


myWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int
progress) {
activity.setTitle("Loading...");
activity.setProgress(progress * 100);
if(progress == 100)
activity.setTitle(view.getTitle());
}
});
myWebView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int
errorCode, String description, String failingUrl) {
Toast.makeText(activity, description,
Toast.LENGTH_SHORT).show();
}
});
myWebView.loadUrl("http://portal.uad.ac.id/");
}
@Override
public void onBackPressed() {
if (myWebView.canGoBack()) {
myWebView.goBack();
} else {
super.onBackPressed();
}
}
}

5. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.nangs.SQLiteDemo" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity android:name=".WebView" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity>
</application>
</manifest>

6.

Lakukan Run dengan shortcut Alt+Shif+F10 atau klik kanan run > run pada menu bar
android studio.
65

X.

Android Google Maps

Google Maps Android API memungkinkan Kita untuk menampilkan peta Google
dalam aplikasi Android Anda. Peta ini memiliki penampilan yang sama seperti peta yang
Anda lihat di aplikasi Google Maps for Mobile (GMM), dan API memaparkan banyak
fitur yang sama. Dua perbedaan mencolok antara Application GMM dan Maps
ditampilkan oleh Google Maps Android API adalah:
Peta yang ditampilkan oleh API tidak mengandung materi yang bersifat pribadi,
seperti ikon pribadi.
Tidak semua ikon pada peta dapat diklik. Sebagai contoh, ikon stasiun transit tidak
bisa diklik. Namun, marker yang Anda tambahkan ke peta yang dapat diklik, dan
API memiliki listener callback interface untuk berbagai interaksi marker.

Selain fungsi pemetaan, API juga mendukung berbagai macam interaksi yang
konsisten dengan model UI Android. Misalnya, Anda dapat mengatur interaksi dengan
peta dengan mendefinisikan listeners yang merespon gerakan pengguna.
Kelas kunci ketika bekerja dengan objek Peta adalah kelas GoogleMap. GoogleMap
memodelkan objek peta dalam aplikasi Anda. Dalam UI, peta akan diwakili oleh salah
satu objek MapFragment atau MapView.

GoogleMap menangani operasi berikut secara otomatis:


Menghubungkan ke Google Maps Service.
Men-download map tiles.
Menampilkan tiles pada layar perangkat.
Menampilkan berbagai kontrol seperti pan dan zoom.
Merespon gerakan pan dan zoom dengan menggerakkan peta dan memperbesar atau
memperkecilnya.
Selain operasi-operasi otomatis, Anda dapat mengontrol perilaku peta dengan obyek
dan metode API. Sebagai contoh, GoogleMap memiliki metode callback yang merespon
penekanan tombol dan touch gestures pada peta. Anda juga dapat mengatur ikon marker
pada peta Anda dan menambahkan lapisan untuk itu, dengan menggunakan benda-benda
yang Anda berikan kepada GoogleMap.

66

Contoh implementasi penggunaan google maps:

Tahap implementasi
7. Mengaktifkan google maps android API
Masuk ke situs https://code.google.com/apis/console/ dan login menggunkan akun
Google. Kemudian Masuk ke halaman API api manager dan enable Google Maps
Android API.

8. Masuk ke menu Credentials kemudian Create credentials API key. Pilih yang
Android key.
67

9. Isikan name kemudian nama package serta SHA-1 fingerprint untuk mendapatkan
API key

Untuk SHA-1 Fingerprint dapat diperoleh dengan cara sebagai berikut :


Bukan Terminal emulator untuk Linux atau OS X atau Command prompt
untuk windows
Eksekusi perintah berikut

Untuk sistem operasi Linux atau OS X:


keytool -list -v -keystore
~/.android/debug.keystore -alias androiddebugkey storepass android -keypass android

68

Untuk sistem operasi windows:


keytool -list -v -keystore
"%USERPROFILE%\.android\debug.keystore" -alias
androiddebugkey

-storepass

android

-keypass

android
Apabila eksekusi perintah benar maka akan diperoleh seperti gambar berikut

10. Create project File > New Project > isikan nama project

69

11. Next > pilih minimum SDK

12. Next > addActivity to Project > finish

70

13. Import google play service library


Tambahkan compile 'com.google.android.gms:play-services:8.4.0' Pada file
build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.nangs.maps"
minSdkVersion 19
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles
getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.google.android.gms:playservices:8.4.0'
}
14. Tambahkan permission dan beberapa baris konfigurasi pada AndroidManifest.xml
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"
/>
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION"
/>
<uses-permission
71

android:name="android.permission.INTERNET" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity android:name=".MapsActivity" >
<intent-filter>
<action
android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="API KEY" />
</application>

15. Buat tampilan di layout activity_map.xml seperti berikut


<fragment
xmlns:android="http://schemas.android.com/apk/res/androi
d"
xmlns:tools="http://schemas.android.com/tools"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/map"
tools:context="com.nangs.motic.controller.MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFrag
ment" />
72

16. Edit activity class yang dibuat tadi menjadi seperti di bawah ini
package com.nangs.maps;
import
import
import
import
import
import
import
import
import
import
import

android.Manifest;
android.content.pm.PackageManager;
android.location.Criteria;
android.location.Location;
android.location.LocationListener;
android.location.LocationManager;
android.os.Build;
android.support.v4.app.FragmentActivity;
android.os.Bundle;
android.util.Log;
android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import
com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.nangs.maps.R;
public class MapsActivity extends FragmentActivity
implements LocationListener, OnMapReadyCallback {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get
notified when the map is ready to be used.
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
int state =
73

GooglePlayServicesUtil.isGooglePlayServicesAvailable(get
BaseContext());
if (state != ConnectionResult.SUCCESS) {
Log.e("error", "google play services not
available");
} else {
if (mMap == null) {
mMap = ((SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map)).
getMap();
if (mMap != null) {
if (Build.VERSION.SDK_INT >=
Build.VERSION_CODES.M) {
if
(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOC
ATION) != PackageManager.PERMISSION_GRANTED &&
checkSelfPermission(Manifest.permission.ACCESS_COARSE_LO
CATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
}
mMap.setMyLocationEnabled(true);
LocationManager locationManager =
(LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider =
locationManager.getBestProvider(criteria, true);
Location location =
locationManager.getLastKnownLocation(provider);
if(location != null){
onLocationChanged(location);
}else{
Toast.makeText(getBaseContext(),
"lokasine kosong", Toast.LENGTH_SHORT).show();
}
locationManager.requestLocationUpdates(provider, 20000,
0, (LocationListener) this);
}
}
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
74

LatLng latlng = new LatLng(-8, 110);


mMap.addMarker(new
MarkerOptions().position(latlng).title("Nama Lokasi"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
double lati = location.getLatitude();
double longi = location.getLongitude();
LatLng coordinate = new LatLng(lati,longi);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coo
rdinate, 16));
Log.e("lokasi : ", String.valueOf(coordinate));
Toast.makeText(this, "longitude : " + longi + ",
latitude : " + lati, Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int
status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
}

17. Lakukan Run dengan shortcut Alt+Shif+F10 atau klik kanan run > run pada menu
bar android studio.

75

XI. SQLite Database

Android menyediakan dukungan penuh untuk database SQLite. Metode yang


disarankan untuk membuat database SQLite baru adalah untuk menciptakan sebuah
subclass dari SQLiteOpenHelper dan menimpa OnCreate () metode, di mana dapat
mengeksekusi perintah SQLite untuk membuat tabel dalam database.
Jika applikasi yang membutuhkan sebuah database maka database ini akan disimpan
dalam direktori DATA/data/APP_NAME/databases/FILENAME.

database biasanya dalam lokasi SD Card.


Untuk membuat dan meng-upgrade database dalam aplikasi Android biasanya
subclass SQLiteOpenHelper. SQLiteOpenHelper menyediakan metode
getReadableDatabase() dan getWriteableDatabase() untuk mendapatkan akses ke obyek
SQLiteDatabase yang memungkinkan akses database baik dalam modus membaca atau
menulis. Metode execSQL() memungkinkan untuk mengeksekusi SQL secara langsung.
Contoh penerapan sqlite, membangun sebuah aplikasi penyimpanan data pertemanan.

76

Tahap implementasi
1. File > New Project > isikan nama project

2. Next > pilih minimum SDK

77

3. Next > addActivity to Project > finish

4. list_friendzone.xml (main view)


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/androi
d"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="My Friendszone"
android:layout_gravity="center"
android:padding="20dp"
android:textSize="20dp"
android:textStyle="bold"/>
<EditText
android:id="@+id/name"
android:hint="name"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/phone"
android:inputType="number"
android:hint="phone"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

78

<EditText
android:hint="address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:id="@+id/address" />
<Button
android:id="@+id/save"
android:text="SAVE"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</ScrollView>
<ListView
android:id="@+id/frinzone"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>

5. item_friendzone.xml (item list view)


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/androi
d"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp">
<TextView
android:id="@+id/ids"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="name"
79

android:textStyle="bold"
android:textSize="30dp"/>
<TextView
android:id="@+id/phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="00000"/>
<TextView
android:id="@+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="address"/>
</LinearLayout>

80

6. single_friend.xml (detail item dari listview)


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="Detail"
android:gravity="center"
android:padding="10dp"
android:textSize="18dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/name"
android:hint="name"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/phone"
android:hint="phone"
android:inputType="number"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<EditText
android:id="@id/address"
android:hint="address"
android:inputType="textMultiLine"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<RelativeLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:gravity="center_horizontal"
android:layout_height="wrap_content">
<Button
android:id="@+id/update"
android:text="update"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/delete"
android:text="Delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
81

android:layout_alignParentTop="true"
android:layout_toEndOf="@+id/update" />
</RelativeLayout>
</LinearLayout>

82

7. Membuat class MyFriendzone (controller main activity)


package com.nangs.SQliteDemo.controller;
import
import
import
import
import
import
import
import
import
import
import

android.content.Intent;
android.database.Cursor;
android.os.Bundle;
android.support.v7.app.AppCompatActivity;
android.view.View;
android.widget.AdapterView;
android.widget.Button;
android.widget.EditText;
android.widget.ListView;
android.widget.TextView;
android.widget.Toast;

import
import
import
import

com.nangs.SQliteDemo.R;
com.nangs.SQliteDemo.adapter.AdapterFriendszone;
com.nangs.SQliteDemo.helper.Friendszone;
com.nangs.SQliteDemo.model.DBHelper;

import java.util.ArrayList;
import java.util.List;
/**
* Created by nangs-an on 08/03/16.
*/
public class MyFriendzone extends AppCompatActivity {
EditText name, phone, address;
Button save;
DBHelper friendsDb = null;
ListView lv;
private Friendzone adapter;
private List<Friendszone> frenzones = new
ArrayList<Friendszone>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_friendzone);
friendsDb = new DBHelper(this);
friendsDb.createTableMahasiswa();
name = (EditText) findViewById(R.id.name);
phone = (EditText) findViewById(R.id.phone);
address = (EditText) findViewById(R.id.address);
save = (Button) findViewById(R.id.save);
lv = (ListView) findViewById(R.id.frinzone);
adapter = new AdapterFriendszone(this, frenzones);
lv.setAdapter(adapter);
83

getData();
lv.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
String itemId = ((TextView)
view.findViewById(R.id.ids)).getText().toString();
Intent i = new
Intent(getApplicationContext(), SIngleFriendzone.class);
i.putExtra("id", Integer.valueOf(itemId));
startActivity(i);
}
});
save.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
addRecord();
}
});
}
public void addRecord(){
if (name.getText().toString().length() != 0 &&
address.getText().toString().length() !=0 &&
address.getText().toString().length() != 0){
Toast.makeText(getApplicationContext(),
"Save", Toast.LENGTH_SHORT).show();
friendsDb.addFriends(name.getText().toString(),
phone.getText().toString(), address.getText().toString());
name.setText("");
phone.setText("");
address.setText("");
getData();
} else {
Toast.makeText(getApplicationContext(), "all
field is required", Toast.LENGTH_SHORT).show();
}
}
public void getData(){
frenzones.clear();
Cursor res = friendsDb.getAllData();
res.moveToFirst();
84

while(res.isAfterLast() == false){
Friendszone fr = new Friendszone();
fr.setId(res.getInt(res.getColumnIndex("id")));
fr.setName(res.getString(res.getColumnIndex("name")));
fr.setPhone(res.getString(res.getColumnIndex("phone")));
fr.setAddress(res.getString(res.getColumnIndex("address"))
);
frenzones.add(fr);
res.moveToNext();
}
adapter.notifyDataSetChanged();
}
}

85

8. Membuat class DBHelper


package com.nangs.SQliteDemo.model;
import
import
import
import
import

android.content.ContentValues;
android.content.Context;
android.database.Cursor;
android.database.sqlite.SQLiteDatabase;
android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper{


private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME =
"friendzone";
// Contacts table name
private static final String TABLE_FRINDZONE =
"TABLE_FRINDZONE";
// Contacts Table Columns names
private static final String KEY_ADDRESS = "address";
private static final String KEY_NAME = "name";
private static final String KEY_PHONE = "phone";
private static final String KEY_ID = "id";
public DBHelper (Context context){
super(context, DATABASE_NAME, null,
DATABASE_VERSION);
}
@Override
public void onUpgrade(SQLiteDatabase db, int
oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
public void createTable(){
SQLiteDatabase db = getWritableDatabase();
String CREATE_CONTACTS_TABLE = "CREATE TABLE if
not exists " + TABLE_FRINDZONE + " ("
+ KEY_ID+ " INTEGER PRIMARY KEY
AUTOINCREMENT," + KEY_NAME + " TEXT,"
+ KEY_PHONE + " TEXT, " + KEY_ADDRESS + "
TEXT)";
db.execSQL(CREATE_CONTACTS_TABLE);
86

}
public void addFriends( String name, String phone,
String address){
SQLiteDatabase db = this.getReadableDatabase();
ContentValues data = new ContentValues();
data.put(KEY_NAME, name);
data.put(KEY_PHONE, phone);
data.put(KEY_ADDRESS, address);
db.insert(TABLE_FRINDZONE, null, data);
}
public void updateData(int id, String name, String
phone, String address){
SQLiteDatabase db = this.getReadableDatabase();
ContentValues value = new ContentValues();
value.put(KEY_NAME, name);
value.put(KEY_PHONE, phone);
value.put(KEY_ADDRESS, address);
db.update(TABLE_FRINDZONE, value, KEY_ID+" =" +
id, null);
}
public void deleteData(int id){
SQLiteDatabase db = this.getReadableDatabase();
db.delete(TABLE_FRINDZONE, KEY_ID+" =" + id,
null);
}
public Cursor getAllData()
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.query(TABLE_FRINDZONE, new
String[]{KEY_ID, KEY_NAME, KEY_PHONE, KEY_ADDRESS}, null,
null, null, null, KEY_ID+" DESC", null);
return res;
}
public Cursor getSingleData(int id)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.query(TABLE_FRINDZONE, new
String[] { KEY_ID,KEY_NAME, KEY_PHONE, KEY_ADDRESS },
KEY_ID+"="+id, null,null,null,null,null);
return res;
}
}
87

9. Membuat class Friendszone


package com.nangs.SQliteDemo.helper;
/**
* Created by nangs-an on 08/03/16.
*/
public class Friendszone {
private String name, phone,address;
private int id;
public Friendszone() {
}
public Friendszone(String name, String address,
String phone) {
this.name = name;
this.phone = phone;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public void setId(int id){
this.id = id;
}
public int getId(){
88

return id;
}
}

10. Membuat Class AdapterFriendszone


package com.nangs.SQliteDemo.adapter;
import
import
import
import
import
import
import
import

android.app.Activity;
android.app.usage.UsageEvents;
android.content.Context;
android.view.LayoutInflater;
android.view.View;
android.view.ViewGroup;
android.widget.BaseAdapter;
android.widget.TextView;

import com.nangs.SQliteDemo.R;
import com.nangs.SQliteDemo.helper.Friendszone;
import java.util.List;
/**
* Created by nangs-an on 08/03/16.
*/
public class AdapterFriendszone extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Friendszone> FriendItems;
public AdapterFriendszone (Activity activity,
List<Friendszone> FriendItems) {
this.activity = activity;
this.FriendItems = FriendItems;
}
@Override
public int getCount() {
return FriendItems.size();
}
@Override
public Object getItem(int position) {
return FriendItems.get(position) ;
}
@Override
public long getItemId(int position) {
89

return position;
}
@Override
public View getView(int position, View convertView,
ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView =
inflater.inflate(R.layout.item_friendzone, null);
TextView id = (TextView)
convertView.findViewById(R.id.ids);
TextView name = (TextView)
convertView.findViewById(R.id.name);
TextView phone = (TextView)
convertView.findViewById(R.id.address);
TextView address = (TextView)
convertView.findViewById(R.id.phone);
Friendszone e = FriendItems.get(position);
id.setText(String.valueOf(e.getId()));
name.setText(e.getName());
phone.setText(e.getPhone());
address.setText(e.getAddress());
return convertView;
}
}

11. Membuat class SingleFriendzone


package com.nangs.SQliteDemo.controller;
import
import
import
import
import
import
import

android.content.Intent;
android.database.Cursor;
android.os.Bundle;
android.support.v7.app.AppCompatActivity;
android.view.View;
android.widget.Button;
android.widget.EditText;
90

import android.widget.Toast;
import com.nangs.SQliteDemo.R;
import com.nangs.SQliteDemo.model.DBHelper;
/**
* Created by nangs-an on 09/03/16.
*/
public class SIngleFriendzone extends AppCompatActivity {
EditText name, phone, address;
Button update, delete;
DBHelper friendsDb = null;
public int id;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_friend);
name = (EditText) findViewById(R.id.name);
phone = (EditText) findViewById(R.id.phone);
address = (EditText) findViewById(R.id.address);
update = (Button) findViewById(R.id.update);
delete = (Button) findViewById(R.id.delete);
Bundle bundle = getIntent().getExtras();
id = bundle.getInt("id");
friendsDb = new DBHelper(this);
getData();
update.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
updateData();
}
});
delete.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
deleteData();
}
});
}
91

public void getData(){


Cursor res =friendsDb.getSingleData(id);
res.moveToFirst();
while(res.isAfterLast() == false){
name.setText(res.getString(res.getColumnIndex("name")));
phone.setText(res.getString(res.getColumnIndex("phone")))
;
address.setText(res.getString(res.getColumnIndex("address
")));
res.moveToNext();
}
}
public void updateData(){
Toast.makeText(getApplicationContext(),
"Updating", Toast.LENGTH_SHORT).show();
friendsDb.updateData(id,
name.getText().toString(), phone.getText().toString(),
address.getText().toString());
getData();
}
public void deleteData(){
Toast.makeText(getApplicationContext(), "Delete",
Toast.LENGTH_SHORT).show();
friendsDb.deleteData(id);
Intent i = new Intent(getApplicationContext(),
MyFriendzone.class);
startActivity(i);
finish();
}
}

12.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
92

xmlns:android="http://schemas.android.com/apk/res/android
"
package="com.nangs.SQLiteDemo" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity android:name=".MyFriendzone" >
<intent-filter>
<action
android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SIngleFriendzone"
android:parentActivityName=".MyFriendzone" />
</application>
</manifest>

13. Lakukan Run dengan shortcut Alt+Shif+F10 atau klik kanan run > run pada menu
bar android studio.

93

XII.

Android dan Web Service

Web service adalah suatu sistem perangkat lunak yang dirancang untuk mendukung
interoperabilitas dan interaksi antar sistem pada suatu jaringan. Web service
digunakan sebagai suatu fasilitas yang disediakan oleh suatu web site untuk
menyediakan layanan (dalam bentuk informasi) kepada sistem lain, sehingga sistem
lain dapat berinteraksi dengan sistem tersebut melalui layanan-layanan (service)
yang disediakan oleh suatu sistem yang menyediakan web service.
Pada android web service diperlukan ketika data yang dibutuhkan tidak lagi di lokal
device. Tujuannya adalah supaya data tersinkronisasi antara aplikasi satu dengan
yang lainnya.

1. Create New Project -> Isikan nama aplikasi -> klik Next

2. Pilih minimum SDK -> klik Next

94

3. Pilih empty activity -> klik Next

4. Isikan nama activity -> klik Finish

95

5. Buka file AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app.jsonparsing">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

6. Buka file activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"

96

android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.app.jsonparsing.MainActivity">
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>

7. Buat file list_item.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/name"
android:textColor="@android:color/black"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/email"
android:textColor="@android:color/holo_red_dark"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/phone"
android:textColor="@android:color/black"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

8. Buat file class JsonParse.java


package com.app.jsonparsing;
import
import
import
import
import
import
import
import

java.io.BufferedInputStream;
java.io.BufferedReader;
java.io.IOException;
java.io.InputStream;
java.io.InputStreamReader;
java.net.HttpURLConnection;
java.net.MalformedURLException;
java.net.URL;

public class JsonParse {


private static final int CONNECTION_TIMEOUT = 1500; //dalam milliseconds
private static final int READ_TIMOUT = 1500; //dalam milliseconds
public JsonParse() {
}
public String getJsonParse(String url){
String json = null;
try {
URL jsonUrl = new URL(url);

97

HttpURLConnection httpURLConnection =
(HttpURLConnection)jsonUrl.openConnection();
httpURLConnection.setConnectTimeout(CONNECTION_TIMEOUT);
httpURLConnection.setReadTimeout(READ_TIMOUT);
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("Content-Type",
"application/json");
httpURLConnection.setRequestProperty("Accept",
"application/json");
int statusCode = httpURLConnection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_OK){ //cek response
code = 200
InputStream inputStream = new
BufferedInputStream(httpURLConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null){
stringBuilder.append(line);
}
json = stringBuilder.toString();
httpURLConnection.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
}

9. Buka file MainActivity.java


package com.app.jsonparsing;
import
import
import
import
import
import
import
import
import
import
import

android.app.ListActivity;
android.app.ProgressDialog;
android.os.AsyncTask;
android.os.Bundle;
android.view.View;
android.widget.AdapterView;
android.widget.ListAdapter;
android.widget.ListView;
android.widget.SimpleAdapter;
android.widget.TextView;
android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends ListActivity {
private ProgressDialog dialog;
String url_json = "http://api.androidhive.info/contacts/";
private static final String TAG_CONTACTS = "contacts";

98

private
private
private
private
private

static
static
static
static
static

final
final
final
final
final

String
String
String
String
String

TAG_ID = "id";
TAG_NAME = "name";
TAG_EMAIL = "email";
TAG_PHONE = "phone";
TAG_PHONE_MOBILE = "mobile";

JSONArray contact;
ArrayList<HashMap<String, String>> contactList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
ListView listView = getListView();
listView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
// getting values from selected ListItem
String name = ((TextView)
view.findViewById(R.id.name)).getText().toString();
String email = ((TextView)
view.findViewById(R.id.email)).getText().toString();
String phone = ((TextView)
view.findViewById(R.id.phone)).getText().toString();
Toast.makeText(MainActivity.this,
"Name: " + name + "\n" + "email: " + email + "\n" +
"phone: " + phone,
Toast.LENGTH_SHORT).show();
}
});
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void>{
@Override
protected void onPreExecute() {
super.onPreExecute();
//tampilkan progress dialog
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Please wait...");
dialog.setCancelable(true);
dialog.show();
}
@Override
protected Void doInBackground(Void... params) {
JsonParse jsonParse = new JsonParse();
String jsonData = jsonParse.getJsonParse(url_json);
if(jsonData != null){
try {
JSONObject jsonObject = new JSONObject(jsonData);
contact = jsonObject.getJSONArray(TAG_CONTACTS);

99

for (int i=0; i<contact.length(); i++){


JSONObject object = contact.getJSONObject(i);
String id = object.getString(TAG_ID);
String name = object.getString(TAG_NAME);
String email = object.getString(TAG_EMAIL);
// Phone JSON Object
JSONObject phone = object.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
// hashmap utk penyimpan per kontak
HashMap<String, String> contact = new HashMap<>();
// menambahkan ke hashmap
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
contact.put(TAG_PHONE_MOBILE, mobile);
// tambahkan contact ke contactlist
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
dialog.dismiss();
ListAdapter adapter = new SimpleAdapter(
MainActivity.this,
contactList,
R.layout.list_item,
new String[]{TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE},
new int[]{R.id.name, R.id.email, R.id.phone});
setListAdapter(adapter);
}
}
}

10. Pada toolbar android studio klik

Run

100