Anda di halaman 1dari 65

UJIAN TENGAH SEMESTER REKAYASA PERANGKAT LUNAK

TUTORIAL PEMBUATAN APLIKASI CRUD(Create Read Update Delete)


DATA SEPEDA MOTOR

Kelas XM
Dosen: Samidi, MM, M. Kom

Disusun oleh :
1411600818

Muhammad Saipul Rohman

Program Pasca Sarjana Magister Komputer


Universitas Budi Luhur
2015

Tutorial Pembuatan Aplikasi simple CRUD data sepeda motor

Prasyarat untuk mengikuti tutorial ini adalah pastikan software software


pendukung sudah terinstall di computer anda, yaitu :
1. Android Studio with SDK
2. Emulator android Genymotion. Penulis menyarankan untuk menggunakan
software emulator ini untuk mempercepat proses running aplikasi android

Tahap tahap untuk membuat aplikasi ini , yaitu :


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

Merancang database baru berikut dengan table motorcycle dan table merk
Membuat project baru di android studio
Membuat splash screen aplikasi dan main activity
Membuat tampilan interface aplikasi android
Membuat class database helper, model dan DAO
Membuat class adapter
Membuat class fragment
Modifikasi source code activity MainActivity dan Testing aplikasi

1. Merancang database baru berikut dengan table motorcycle dan table merk
Aplikasi ini menggunakan 2 table dengan struktur table berikut ini :

2. Membuat project baru di android studio

Buat project baru dengan nama Motorcycle. Kemudian buat package baru yaitu adapter,
helper, model, dao dan fragment di dalam package aplikasi utama android

3. Membuat splash screen aplikasi dan main activity


Buat blank activity baru dengan nama SplashScreen. Buka activity_splash_screen.xml yang
berada di res folder kemudian copy paste listing coding di bawah ini :
<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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".SplashScreen"
android:background ="@drawable/gradient_background">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/ic_motor"
android:layout_centerInParent="true"/>
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/progressBar"
android:layout_marginLeft="105dp"
android:layout_marginStart="105dp"
android:layout_marginBottom="26dp"
android:layout_alignBottom="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
Listing coding activity_splash_screen.xml
Buka activity SplashScreen kemudian copy paste listing coding dibawah ini :

package kana.com.motorcycle;
/**
* Created by M Saipul R on 4/22/2015.
*/
import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
public class SplashScreen extends Activity {
private static int splashInterval = 2000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowMana
ger.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash_screen);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Intent i = new Intent(SplashScreen.this, MainActivity.class);
startActivity(i);
//jeda selesai Splashscreen
this.finish();
}
private void finish() {
// TODO Auto-generated method stub
}
}, splashInterval);
}
}
Listing coding SplashScreen.java
Tampilan splash screen aplikasi

Kemudian buat activity baru dengan nama MainActivity. Untuk isi source code MainActivity
akan dibahas di step terakhir

4. Membuat tampilan interface aplikasi android


4.1
Resources
4.1.1 color.xml
Buat baru value resource file di res/values dengan nama color kemudian copy paste listing
code di bawah ini :

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


<resources>
<color name="list_item_title">#fff</color>
<color name="list_background">#BABABA</color>
<color name="list_background_pressed">#199faf</color>
<color name="list_divider">#B0B0B0</color>
<color name="transparent">#00000000</color>
<color name="list_item_bg">#ffffff</color>
<color name="counter_text_bg">#626262</color>
<color name="counter_text_color">#c5c4c4</color>
</resources>
Listing coding color.xml
4.1.2 strings.xml
Buka file strings.xml di res/values kemudian edit isi listing codingnya menjadi seperti di
bawah ini :
<resources>
<string name="app_name">Motorcycle</string>
<string name="hello_world">Selamat Datang di aplikasi simple data
motorcycle</string>
<string name="action_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
<!-- Navigation Drawer Menu Items -->
<string-array name="nav_drawer_items">
<item >Home</item>
<item >Merk</item>
<item >Motorcycle</item>
</string-array>
<!-- List Item Icons(Images) with strings(text of company name) -->
<!-- Keep them with titles array accordingly -->
<array name="nav_drawer_icons">
<item>@drawable/ic_home</item>
<item>@drawable/ic_merk</item>
<item>@drawable/ic_motorcycle</item>
</array>
<string name="nama_motor">Nama Motor</string>
<string name="merk">Merk</string>
<string name="nama_merk">Nama Merk</string>
<string name="negara_asal">Negara Asal</string>
<string name="update">Update</string>
<string name="delete">Delete</string>
<string name="add">Add</string>
<string name="reset">Reset</string>
<string name="cancel">Cancel</string>
<!-- drawer_list_item Imageview Description -->
<string name="description_list_icon">Item Icon</string>
<!-- TODO: Remove or change this placeholder text -->
<string name="hello_blank_fragment">Hello blank fragment</string>

</resources>
Listing coding strings.xml
4.1.3 activity_main.xml
File layout ini digunakan untuk menampilkan halaman utama dan menampung semua
halaman fragment aplikasi.
Buka file activity_main.xml di folder res/layout kemudian edit listing codingnya menjadi
seperti di bawah ini :
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Displaying Fragments -->
<FrameLayout
android:id="@+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<!-- Displaying Drawer -->
<ListView
android:id="@+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@color/list_divider"
android:dividerHeight="1dp"
android:listSelector="@drawable/drawer_list_selection"
android:background="@color/list_background"/>
</android.support.v4.widget.DrawerLayout>
Listing coding activity_main.xml
4.1.4 drawer_list_item.xml
File layout ini digunakan untuk tampilan list navigasi side bar aplikasi.
Buat file layout baru dengan nama drawer_list_item.xml kemudian copy paste listing coding
di bawah ini :
<?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="48dp"
android:background="@drawable/drawer_list_selection">
<ImageView
android:id="@+id/icon"
android:layout_width="28dp"
android:layout_height="28dp"
android:layout_alignParentLeft="true"
android:layout_marginLeft="12dp"

android:layout_marginRight="12dp"
android:contentDescription="@string/description_list_icon"
android:src="@drawable/ic_home"
android:layout_centerVertical="true" />
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_toRightOf="@id/icon"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:textColor="@color/list_item_title"
android:gravity="center_vertical"
android:paddingRight="40dp"/>
</RelativeLayout>
Listing coding drawer_list_item.xml
4.1.5 fragment_main.xml
File ini berfungsi untuk menampilkan halaman utama aplikasi setelah splash screen.
Buat file layout baru dengan nama fragment_main.xml kemudian copy paste listing coding di
bawah ini :
<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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity$PlaceholderFragment">
<TextView android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/lblhelo"
android:layout_marginTop="166dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Aplikasi Motorcycle"
android:id="@+id/textView5"
android:layout_marginBottom="45dp"
android:layout_alignBottom="@+id/lblhelo"
android:layout_centerHorizontal="true" />
<ImageView

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/ic_motorcycle"
android:layout_above="@+id/textView5"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Silahkan pilih menu navigasi di sebelah kiri "
android:id="@+id/textView6"
android:layout_marginTop="24dp"
android:layout_below="@+id/lblhelo"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Listing coding fragment_main.xml
4.1.6 list_item_merk
File ini berfungsi menampilkan list data merk.
Buat file layout baru dengan nama list_item_merk.xml kemudian copy paste listing coding di
bawah ini :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@color/list_item_bg"
android:descendantFocusability="blocksDescendants" >
<RelativeLayout
android:id="@+id/layout_item"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/txt_id_merk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="6dp" />
<TextView
android:id="@+id/txt_nama_merk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/txt_id_merk"
android:padding="6dp" />
<TextView
android:id="@+id/kosong"
android:layout_width="wrap_content"

android:layout_height="wrap_content"
android:layout_below="@+id/txt_nama_merk"
android:padding="6dp" />
<TextView
android:id="@+id/txt_negara_asal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/kosong"
android:layout_below="@+id/txt_nama_merk"
android:padding="6dp" />
</RelativeLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="@+id/layout_item"
android:background="@color/list_divider" />
</RelativeLayout>
4.1.7 list_item_motorcycle.xml
File ini berfungsi untuk menampilkan list data motorcycle.
Buat file layout baru dengan nama list_item_motorcycle.xml kemudian copy paste listing
coding di bawah ini :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@color/list_item_bg"
android:descendantFocusability="blocksDescendants" >
<RelativeLayout
android:id="@+id/layout_item"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/txt_id_motor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="6dp" />
<TextView
android:id="@+id/txt_nama_motor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/txt_id_motor"
android:padding="6dp" />
<TextView
android:id="@+id/kosong"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:layout_below="@+id/txt_nama_motor"
android:padding="6dp" />
<TextView
android:id="@+id/txt_merk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/kosong"
android:layout_below="@+id/txt_nama_motor"
android:padding="6dp" />
</RelativeLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="@+id/layout_item"
android:background="@color/list_divider" />
</RelativeLayout>
4.1.8

merk_add_fragment.xml
File ini digunakan untuk menampilkan form add merk.
Buat file layout baru dengan nama merk_add_fragment.xml kemudian copy paste
listing coding di bawah ini :
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp" >
<EditText
android:id="@+id/txt_nama_merk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/nama_merk"
android:textColorHint="@color/counter_text_color"
android:singleLine="true"
android:nextFocusDown="@+id/txt_negara_asal"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_toRightOf="@+id/textView"
android:layout_toEndOf="@+id/textView" />
<EditText
android:id="@+id/txt_negara_asal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:hint="@string/negara_asal"
android:textColorHint="@color/counter_text_color"
android:singleLine="true"
android:layout_below="@+id/txt_nama_merk"
android:layout_alignLeft="@+id/txt_nama_merk"
android:layout_alignStart="@+id/txt_nama_merk"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<LinearLayout
android:id="@+id/layout_submit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/txt_negara_asal"
android:layout_margin="5dp"
android:textColorHint="@color/counter_text_color"
android:orientation="horizontal"
android:weightSum="2" >
<Button
android:id="@+id/button_add"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/add" />
<Button
android:id="@+id/button_reset"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/reset"
/>
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Nama Merk :"
android:id="@+id/textView"
android:textAlignment="center"
android:layout_alignBaseline="@+id/txt_nama_merk"
android:layout_alignBottom="@+id/txt_nama_merk"
android:layout_alignLeft="@+id/layout_submit"
android:layout_alignStart="@+id/layout_submit" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Negara Asal :"
android:id="@+id/textView2"

android:textAlignment="center"
android:layout_alignBaseline="@+id/txt_negara_asal"
android:layout_alignBottom="@+id/txt_negara_asal"
android:layout_alignLeft="@+id/layout_submit"
android:layout_alignStart="@+id/layout_submit" />
</RelativeLayout>
</ScrollView>
4.1.9

merk_fragment.xml
File ini berfungsi untuk menampilkan semua data merk yang ada di tabel merk.
Buat file layout bernama merk_fragment dan copy paste listing coding di bawah ini :
<?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"
>
<!-- Layout set for data you can use accordingly -->
<RelativeLayout
android:id="@+id/rel_data"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dip"
android:layout_marginTop="70dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">
<ListView
android:id="@+id/listViewMerk"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@color/transparent"
android:dividerHeight="10dp"
android:drawSelectorOnTop="true"
android:footerDividersEnabled="false"
android:padding="10dp"
android:scrollbarStyle="outsideOverlay" />
</RelativeLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Merk"
android:id="@+id/btnNewMerk"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="19dp"
android:layout_marginEnd="19dp"

android:layout_marginTop="17dp" />
</RelativeLayout>
4.1.10 motorcycle_add_fragment.xml
File ini digunakan untuk menampilkan form add motorcycle.
Buat file layout baru dengan nama motorcycle_add_fragment.xml kemudian copy
paste listing coding di bawah ini :
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp" >
<EditText
android:id="@+id/txt_nama_motor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/nama_motor"
android:textColorHint="@color/counter_text_color"
android:singleLine="true"
android:layout_alignParentTop="true"
android:layout_alignLeft="@+id/spinner_merk"
android:layout_alignStart="@+id/spinner_merk"
android:layout_alignRight="@+id/layout_submit"
android:layout_alignEnd="@+id/layout_submit"
/>
<Spinner
android:id="@+id/spinner_merk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/txt_nama_motor"
android:layout_toRightOf="@+id/textView4"
android:layout_toEndOf="@+id/textView4"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp" />
<LinearLayout
android:id="@+id/layout_submit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/spinner_merk"
android:layout_margin="5dp"
android:orientation="horizontal"
android:weightSum="2" >

<Button
android:id="@+id/button_add"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/add" />
<Button
android:id="@+id/button_reset"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/reset"
/>
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Nama Motor :"
android:id="@+id/textView3"
android:layout_above="@+id/spinner_merk"
android:layout_alignLeft="@+id/layout_submit"
android:layout_alignStart="@+id/layout_submit"
android:layout_marginBottom="11dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Merk Motor :"
android:id="@+id/textView4"
android:layout_below="@+id/textView3"
android:layout_alignLeft="@+id/textView3"
android:layout_alignStart="@+id/textView3"
android:layout_marginTop="15dp" />
</RelativeLayout>
</ScrollView>
4.1.11 motorcycle_fragment.xml
File ini berfungsi untuk menampilkan semua data motorcycle yang ada di tabel
motorcycle.
Buat file layout bernama motorcycle_fragment dan copy paste listing coding di
bawah ini :
<?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"
>
<!-- Layout set for data you can use accordingly -->
<RelativeLayout
android:id="@+id/rel_data"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dip"
android:layout_marginTop="70dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">
<ListView
android:id="@+id/listViewMotorcycle"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@color/transparent"
android:dividerHeight="10dp"
android:drawSelectorOnTop="true"
android:footerDividersEnabled="false"
android:padding="10dp"
android:scrollbarStyle="outsideOverlay" />
</RelativeLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New MotorCycle"
android:id="@+id/btnNewMotor"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="19dp"
android:layout_marginEnd="19dp"
android:layout_marginTop="17dp" />
</RelativeLayout>

5. Membuat class database helper, model dan DAO


5.1

Class database helper


Class database helper berfungsi untuk membuat database baru beserta table motorcycle
dan table merk.
Buat java class file baru dengan nama DatabaseHelper.java di package
kana.com.motorcycle.helper kemudian copy paste listing coding berikut ini :
package kana.com.motorcycle.helper;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBaseHelper extends SQLiteOpenHelper {


//define database name and database version
private static final String DATABASE_NAME = "FragmentMotorcycle.db";
private static final int DATABASE_VERSION = 1;
//define table name
public static final String MOTOR_TABLE = "motor";
public static final String MERK_TABLE = "merk";
//define table column
public static final String ID_COLUMN = "id";
public static final String NAMA_MOTOR = "nama_motor";
public static final String MERK_ID = "merk_id";
public static final String TIPE_MOTOR = "tipe_motor";
public static final String NAMA_MERK = "nama_merk";
public static final String NEGARA_ASAL = "negara_asal";
//function to create merk table
public static final String CREATE_MERK_TABLE = "CREATE TABLE "
+ MERK_TABLE + "(" + ID_COLUMN + " INTEGER PRIMARY KEY
AUTOINCREMENT NOT NULL, "
+ NAMA_MERK + " TEXT, "+ NEGARA_ASAL + " TEXT) ";
//function to create motor table
public static final String CREATE_MOTOR_TABLE = "CREATE TABLE "
+ MOTOR_TABLE + "(" + ID_COLUMN + " INTEGER PRIMARY KEY
AUTOINCREMENT NOT NULL,"
+ NAMA_MOTOR + " TEXT ," +MERK_ID+ " INT, " + "FOREIGN KEY(" +
MERK_ID + ") REFERENCES "
+ MERK_TABLE + "(id) " + ")";
private static DataBaseHelper instance;
public static synchronized DataBaseHelper getHelper(Context context) {
if (instance == null)
instance = new DataBaseHelper(context);
return instance;
}
private DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
if (!db.isReadOnly()) {
// Enable foreign key constraints
db.execSQL("PRAGMA foreign_keys=ON;");
}
}
@Override

public void onCreate(SQLiteDatabase db) {


db.execSQL(CREATE_MERK_TABLE);
db.execSQL(CREATE_MOTOR_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}

5.2

Class model
Kita akan membuat 3 class model yaitu Merk, Motorcycle dan NavDrawerItem.
5.2.1 Merk
Tujuan class model Merk :
- Class ini merepresentasikan objek Merk yang tersimpan di database
- Class ini menggunakan interface Parcelable karena kita butuhkan untuk
membungkus objek merk sebagai argumen ketika menampilkan custom
dialog fragmen untuk memperbarui rincian merk
Buat java class baru dengan nama Merk.java di package
kana.com.motorcycle.model kemudian copy paste listing coding berikut ini :
package kana.com.motorcycle.model;
import android.os.Parcel;
import android.os.Parcelable;
public class Merk implements Parcelable {
private int id;
private String namaMerk;
private String negaraAsal;
public Merk() {
}
public Merk(String namaMerk, String negaraAsal) {
this.namaMerk = namaMerk;
this.negaraAsal = negaraAsal;
}
public Merk(Parcel parcel) {
super();
this.id = parcel.readInt();
this.namaMerk= parcel.readString();
}
public int getId() {
return id;
}

public void setId(int id) {


this.id = id;
}
public String getnamaMerk() {
return namaMerk;
}
public void setnamaMerk(String namaMerk) {
this.namaMerk = namaMerk;
}
public String getNegaraAsal() {
return negaraAsal;
}
public void setNegaraAsal(String negaraAsal) {
this.negaraAsal = negaraAsal;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(getId());
dest.writeString(getnamaMerk());
}
public static final Creator<Merk> CREATOR = new Creator<Merk>() {
@Override
public Merk createFromParcel(Parcel source) {
return new Merk(source);
}
@Override
public Merk[] newArray(int size) {
return new Merk[size];
}
};
@Override
public int hashCode() {
final int prime= 31;
int result =1;
result =prime* result+id;
return result;
}
@Override
public String toString() {
return namaMerk ;
}

}
5.2.2

Motorcycle
Tujuan class model Motorcycle :
- Class ini merepresentasikan objek Motorcycle yang tersimpan di database
- Class ini menggunakan interface Parcelable karena kita butuhkan untuk
membungkus objek motorcycle sebagai argumen ketika menampilkan
custom dialog fragmen untuk memperbarui rincian merk
Buat java class baru dengan nama Motorcycle.java di package
kana.com.motorcycle.model kemudian copy paste listing coding berikut ini :
package kana.com.motorcycle.model;
import android.os.Parcel;
import android.os.Parcelable;
public class Motorcycle implements Parcelable {
private int id;
private String namaMotor;
private Merk merk;
public Motorcycle() {
super();
}
public Motorcycle(Parcel in) {
this.id = in.readInt();
this.namaMotor = in.readString();
this.merk = in.readParcelable(Merk.class.getClassLoader());
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNamaMotor() {
return namaMotor;
}
public void setNamaMotor(String namaMotor) {
this.namaMotor = namaMotor;
}
public Merk getMerk() {
return merk;
}

public void setMerk(Merk merk) {


this.merk = merk;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(getId());
dest.writeString(getNamaMotor());
dest.writeParcelable(getMerk(), flags);
}

public static final Creator<Motorcycle> CREATOR = new Creator<Motorcycle>


@Override
public Motorcycle createFromParcel(Parcel source) {
return new Motorcycle(source);
}
@Override
public Motorcycle[] newArray(int size) {
return new Motorcycle[size];
}
};
@Override
public String toString() {
return "Motorcycle{" +
"id=" + id +
", namaMotor='" + namaMotor + '\'' +
", merk=" + merk +
'}';
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
}
5.2.3

NavDrawerItem
Tujuan class model NavDrawerItem untuk merepresentasikan objek navigasi
sidebar aplikasi seperti icon dan Title. Buat java class baru dengan nama
NavDrawerItem.java di package kana.com.motorcycle.model kemudian copy
paste listing coding berikut ini :

package kana.com.motorcycle.model;
public class NavDrawerItem {
private String title;
private int icon;
private String count = "0";
private boolean isCounterVisible = false;
public NavDrawerItem(){}
public NavDrawerItem(String title, int icon){
this.title = title;
this.icon = icon;
}

public NavDrawerItem(String title, int icon, boolean isCounterVi


String count){
this.title = title;
this.icon = icon;
this.isCounterVisible = isCounterVisible;
this.count = count;
}
public String getTitle(){
return this.title;
}
public int getIcon(){
return this.icon;
}
public String getCount(){
return this.count;
}
public boolean getCounterVisibility(){
return this.isCounterVisible;
}
public void setTitle(String title){
this.title = title;
}
public void setIcon(int icon){
this.icon = icon;
}
public void setCount(String count){
this.count = count;
}
public void setCounterVisibility(boolean isCounterVisible){

this.isCounterVisible = isCounterVisible;
}
}

5.3 Class DAO


5.3.1

MerkDAO
Class MerkDAO adalah ekstend dari class MerkDBDAO yang berfungsi
untuk melakukan operasi database seperti save, update, delete, dan get Merk.
Buat java class file baru dengan nama MerkDAO di package
kana.com.motorcycle.dao kemudian copy paste listing coding di bawah ini :
package kana.com.motorcycle.dao;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import kana.com.motorcycle.helper.DataBaseHelper;
import kana.com.motorcycle.model.Merk;
public class MerkDAO extends MerkDBDAO {
private static final String WHERE_ID_EQUALS = "id" + " =?";
public MerkDAO(Context context) {
super(context);
}

public long save(Merk merk) {


ContentValues values = new ContentValues();
values.put(DataBaseHelper.NAMA_MERK, merk.getnamaMerk(
values.put(DataBaseHelper.NEGARA_ASAL, merk.getNegaraAsal());
return database.insert(DataBaseHelper.MERK_TABLE, null, valu
}

public long update(Merk merk) {


ContentValues values = new ContentValues();
values.put(DataBaseHelper.NAMA_MERK, merk.getnamaMerk(
values.put(DataBaseHelper.NEGARA_ASAL, merk.getNegaraAsal());
long result = database.update(DataBaseHelper.MERK_TABLE, v
WHERE_ID_EQUALS,
new String[] { String.valueOf(merk.getId()) });
Log.d("Update Result:", "=" + result);
return result;
}

public int deleteMerk(Merk merk) {


return database.delete(DataBaseHelper.MERK_TABLE,
WHERE_ID_EQUALS, new String[] { merk.ge
"" });

public void loadMerk() {


Merk merk = new Merk();
List<Merk> listMerk = new ArrayList<Merk>();
for (Merk a : listMerk) {
ContentValues values = new ContentValues();
values.put(DataBaseHelper.NAMA_MERK, merk.getnamaMerk());
values.put(DataBaseHelper.NEGARA_ASAL, merk.getNegaraAsal());
database.insert(DataBaseHelper.MERK_TABLE, null, val
}
}
public ArrayList<Merk> getMerk(){
ArrayList<Merk> merkArrayList = new ArrayList<Merk>();
String query = "SELECT * FROM merk";
Log.d("query", query);
Cursor cursor = database.rawQuery(query, null);
while (cursor.moveToNext()){
Merk objMerk = new Merk();
objMerk.setId(cursor.getInt(0));
objMerk.setnamaMerk(cursor.getString(1));
objMerk.setNegaraAsal(cursor.getString(2));
merkArrayList.add(objMerk);
}
return merkArrayList;
}
}
5.3.2

MerkDBDAO
Class MerkDBDAO ini berfungsi untuk menulis dan membaca data dari
database menggunakan class SQLite Database dengan memanggil method
getWritableDatabase() pada database helper. Kemudian kita akan membuat
MerkDAO dan MotorcycleDAO dimana class tersebut akan meng-extend
class MekDBDAO ini dan menggunakan SQLiteDatabase object yang
menyediakan method pada operasi database CRUD(Create, Read, Update,
Delete) di SQLite.
Buat java class file baru dengan nama MerkDBDAO di package
kana.com.motorcycle.dao kemudian copy paste listing coding di bawah ini :
package kana.com.motorcycle.dao;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import kana.com.motorcycle.helper.DataBaseHelper;
public class MerkDBDAO {
protected SQLiteDatabase database;
private DataBaseHelper dbHelper;
private Context mContext;

public MerkDBDAO(Context context) {


this.mContext = context;
dbHelper = DataBaseHelper.getHelper(mContext);
open();
}
public void open() throws SQLException {
if(dbHelper == null)
dbHelper = DataBaseHelper.getHelper(mContext);
database = dbHelper.getWritableDatabase();
}
}

5.3.3

MotorcycleDAO

Class MotorcycleDAO adalah ekstend dari class MotorcycleDAO yang


berfungsi untuk melakukan operasi database seperti save, update,
delete, dan get Motorcycle.
Buat java class file baru dengan nama MotorcycleDAO di package
kana.com.motorcycle.dao kemudian copy paste listing coding di bawah
ini :
package kana.com.motorcycle.dao;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import java.util.ArrayList;
import kana.com.motorcycle.helper.DataBaseHelper;
import kana.com.motorcycle.model.Merk;
import kana.com.motorcycle.model.Motorcycle;
public class MotorcycleDAO extends MerkDBDAO {

public static final String MOTOR_ID_WITH_PREFIX = "motor.id";


public static final String NAMA_MOTOR_WITH_PR
"motor.nama_motor";
public static final String NAMA_MERK_WITH_PREF
"merk.nama_merk";
private
static
final
DataBaseHelper.ID_COLUMN + "=?";

String

public MotorcycleDAO(Context context) {


super(context);

WHERE_ID_EQUAL

public long save(Motorcycle motorcycle){


ContentValues values = new ContentValues();
values.put(DataBaseHelper.NAMA_MO
motorcycle.getNamaMotor());
values.put(DataBaseHelper.MERK_ID, motorcycle.getMerk().getId())
return database.insert(DataBaseHelper.MOTOR_TABLE, null, value
}

public long update(Motorcycle motorcycle){


ContentValues values = new ContentValues();
values.put(DataBaseHelper.NAMA_MO
motorcycle.getNamaMotor());
values.put(DataBaseHelper.MERK_ID, motorcycle.getMerk().getId())
long result = database.update(DataBaseHelper.MOTOR_TABLE, valu
WHERE_ID_EQUALS, new S
{String.valueOf(motorcycle.getId())});
Log.d("Update Result :" , "="+ result);
return result;
}

public int delete(Motorcycle motorcycle){


return database.delete(DataBaseHelper.MOTOR_T
WHERE_ID_EQUALS,
new String[]{motorcycle.getId()+ ""});
}

public ArrayList<Motorcycle> getMotorcycle(){


ArrayList<Motorcycle> arrayMotorcycle = new ArrayList<Motorcycl
String query = " SELECT " + MOTOR_ID_WITH_PREFIX + ","
+DataBaseHelper.NAMA_MOTOR + ","
+DataBaseHelper.MERK_ID +"," +
NAMA_MERK_WITH_PREFIX + "" +
" FROM "
+ DataBaseHelper.MOTOR_TABLE + ","
+ DataBaseHelper.MERK_TABLE
+ " WHERE motor."
+DataBaseHelper.MERK_ID + "= merk."
+DataBaseHelper.ID_COLUMN;
Log.d("hasil query : ", query);
Cursor cursor = database.rawQuery(query, null);
while (cursor.moveToNext()){
Motorcycle motorcycle = new Motorcycle();
motorcycle.setId(cursor.getInt(0));
motorcycle.setNamaMotor(cursor.getString(1));
Merk merk = new Merk();
merk.setId(cursor.getInt(2));
merk.setnamaMerk(cursor.getString(3));

motorcycle.setMerk(merk);
arrayMotorcycle.add(motorcycle);
}
return arrayMotorcycle;
}
}
6. Membuat class adapter
6.1 ListMerkAdapter
Class ini adalah custom list adapter yang berfungsi untuk menampikan data
merk id, nama merk dan Negara asal.
Buat class java file baru dengan nama ListMerkAdapter.java di package
kana.com.motorcycle.adapter kemudian copy paste listing coding di bawah ini :
package kana.com.motorcycle.adapter;
/**
* Created by M Saipul R on 4/20/2015.
*/
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
import kana.com.motorcycle.R;
import kana.com.motorcycle.model.Merk;
public class ListMerkAdapter extends ArrayAdapter<Merk>{
private Context context;
List<Merk> listMerk;
public ListMerkAdapter(Context context, List<Merk> listMerk ) {
super(context, R.layout.list_item_merk, listMerk);
this.context = context;
this.listMerk = listMerk;
}
private class ViewHolder {
TextView merkIdTxt;
TextView merkNamaTxt;
TextView negaraAsalTxt;
}

@Override
public int getCount() {
return listMerk.size();
}
@Override
public Merk getItem(int position) {
return listMerk.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_merk, null);
holder = new ViewHolder();
holder.merkIdTxt= (TextView)
convertView.findViewById(R.id.txt_id_merk);
holder.merkNamaTxt =(TextView)
convertView.findViewById(R.id.txt_nama_merk);
holder.negaraAsalTxt =(TextView)
convertView.findViewById(R.id.txt_negara_asal);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
Merk merk = (Merk) getItem(position);
holder.merkIdTxt.setText(merk.getId()+ "");
holder.merkNamaTxt.setText(merk.getnamaMerk());
holder.negaraAsalTxt.setText(merk.getNegaraAsal());
return convertView;
}
@Override
public void add(Merk merk) {
listMerk.add(merk);
notifyDataSetChanged();
super.add(merk);
}

@Override
public void remove(Merk merk) {
listMerk.remove(merk);
notifyDataSetChanged();
super.add(merk);
}
}
6.2 ListMotorcycleAdapter
Class ini adalah custom list adapter yang berfungsi untuk menampikan data
motorcycle id, nama motorcycle dan Merk.
Buat class java file baru dengan nama ListMotorcycleAdapter.java di package
kana.com.motorcycle.adapter kemudian copy paste listing coding di bawah ini :
package kana.com.motorcycle.adapter;
/**
* Created by M Saipul R on 4/20/2015.
*/
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
import kana.com.motorcycle.R;
import kana.com.motorcycle.model.Motorcycle;
public class ListMotorcycleAdapter extends ArrayAdapter<Motorcycle> {
private Context context;
List<Motorcycle> listMotorcycle;
public ListMotorcycleAdapter(Context context, List<Motorcycle>
listMotorcycle) {
super(context, R.layout.list_item_motorcycle, listMotorcycle);
this.context = context;
this.listMotorcycle = listMotorcycle;
}
private class ViewHolder{
TextView motorcycleIdTxt;
TextView motorcycleNamaTxt;
TextView motorcycleMerkTxt;
}

@Override
public int getCount() {
return listMotorcycle.size();
}
@Override
public Motorcycle getItem(int position) {
return listMotorcycle.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView= inflater.inflate(R.layout.list_item_motorcycle, null);
holder = new ViewHolder();
holder.motorcycleIdTxt = (TextView)
convertView.findViewById(R.id.txt_id_motor);
holder.motorcycleNamaTxt= (TextView)
convertView.findViewById(R.id.txt_nama_motor);
holder.motorcycleMerkTxt= (TextView)
convertView.findViewById(R.id.txt_merk);
convertView.setTag(holder);
}else{
holder= (ViewHolder) convertView.getTag();
}
Motorcycle motorcycle= (Motorcycle) getItem(position);
holder.motorcycleIdTxt.setText(motorcycle.getId()+ "");
holder.motorcycleNamaTxt.setText(motorcycle.getNamaMotor());
holder.motorcycleMerkTxt.setText(motorcycle.getMerk().getnamaMerk());
return convertView;
}
@Override
public void add(Motorcycle motorcycle) {
listMotorcycle.add(motorcycle);
notifyDataSetChanged();
super.add(motorcycle);
}
@Override

public void remove(Motorcycle motorcycle) {


listMotorcycle.remove(motorcycle);
notifyDataSetChanged();
super.remove(motorcycle);
}
}
6.3 NavDrawerListAdapter
Class ini berfungsi untuk menampilkan data gambar dan title navigasi sidebar
aplikasi. Buat class java file baru dengan nama NavDrawerListAdapter.java di
package kana.com.motorcycle.adapter kemudian copy paste listing coding di
bawah ini :
package kana.com.motorcycle.adapter;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import kana.com.motorcycle.R;
import kana.com.motorcycle.model.NavDrawerItem;
public class NavDrawerListAdapter extends BaseAdapter {
private Context context;
private ArrayList<NavDrawerItem> navDrawerItems;
public NavDrawerListAdapter(Context context,
ArrayList<NavDrawerItem> navDrawerItems){
this.context = context;
this.navDrawerItems = navDrawerItems;
}
@Override
public int getCount() {
return navDrawerItems.size();
}
@Override
public Object getItem(int position) {
return navDrawerItems.get(position);
}

@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView,
ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE
);
convertView =
mInflater.inflate(R.layout.drawer_list_item,null);
}
ImageView imgIcon = (ImageView)
convertView.findViewById(R.id.icon);
TextView txtTitle = (TextView)
convertView.findViewById(R.id.title);
imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
txtTitle.setText(navDrawerItems.get(position).getTitle());
return convertView;
}
}
7. Membuat class fragment
7.1 FragmentMain
Class ini digunakan untuk memanggil file layout fragment_main.xml.
Buat class java file baru dengan nama FragmentMain.java di package
kana.com.motorcycle.fragment kemudian copy paste listing coding di bawah
ini :
package kana.com.motorcycle.fragment;
/**
* Created by M Saipul R on 4/20/2015.
*/
import android.annotation.TargetApi;
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;

import android.view.View;
import android.view.ViewGroup;
import kana.com.motorcycle.R;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class FragmentMain extends Fragment {
// this Fragment will be called from MainActivity
public FragmentMain(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
7.2 FragmentMerk
Class ini digunakan untuk :
- Menjalankan sebuah tugas secara background(AsyncTask) ketika
memanggil method getMerk() di class MerkDAO dan menampilkan list
merk di Listview
- Ketika salah satu item list di click akan menampilkan sebuah custom
dialog fragment untuk merubah Merk detail
Buat java class baru dengan nama FragmentMerk.java di package
kana.com.motorcycle.fragment kemudian copy paste listing coding di bawah
ini :
package kana.com.motorcycle.fragment;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;

import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import kana.com.motorcycle.R;
import kana.com.motorcycle.adapter.ListMerkAdapter;
import kana.com.motorcycle.dao.MerkDAO;
import kana.com.motorcycle.helper.DataBaseHelper;
import kana.com.motorcycle.model.Merk;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Toast;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class FragmentMerk extends Fragment implements OnItemClickListener,
OnItemLongClickListener {
// this Fragment will be called from MainActivity
public Button buttonNew;
private Fragment contentFragment;
private FragmentMerk fragmentMerk;
Activity activity;
ListView listViewMerk;
ArrayList<Merk> merkArrayList;
ListMerkAdapter listMerkAdapter;
MerkDAO merkDAO;
final FragmentMerk context = this;
private GetMerkTask task;
public FragmentMerk(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.merk_fragment, container, false);
findViewsById(rootView);
task = new GetMerkTask(activity);
task.execute((Void) null);
listViewMerk.setOnItemClickListener(this);

listViewMerk.setOnItemLongClickListener(this);
buttonNew = (Button) rootView.findViewById(R.id.btnNewMerk);
buttonNew.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Fragment fragment = new FragmentNewMerk();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container,
fragment).commit();
}
});
return rootView;
}
public void panggilUlang(){
Fragment fragment = new FragmentMerk();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container,
fragment).commit();
}
private void findViewsById(View view) {
listViewMerk = (ListView) view.findViewById(R.id.listViewMerk);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
merkDAO = new MerkDAO(activity);
//Initially loads Merk
if(merkDAO.getMerk().size() <= 0)
merkDAO.getMerk();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Merk merk = (Merk) parent.getItemAtPosition(position);
if(merk != null){
Bundle arguments = new Bundle();
arguments.putParcelable("selectedMerk", merk);

CustomMerkDialogFragment customMerkDialogFragment = new


CustomMerkDialogFragment();
customMerkDialogFragment.setArguments(arguments);
customMerkDialogFragment.show(getFragmentManager(),
CustomMerkDialogFragment.ARG_ITEM_ID) ;
}
}
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position,
long id) {
final Merk merk = (Merk) parent.getItemAtPosition(position);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setTitle("yakin Hapus Data ?");
alertDialogBuilder
.setMessage("Tekan Yes Untuk Menghapus !")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
listMerkAdapter.remove(merk);
merkDAO.deleteMerk(merk);
panggilUlang();
Toast.makeText(activity, "Record " + merk.getnamaMerk() + " Data
Deleted !", Toast.LENGTH_LONG).show();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
return true;
}
public class GetMerkTask extends AsyncTask<Void, Void, ArrayList<Merk>> {
private final WeakReference<Activity> activityWeakReference;
public GetMerkTask(Activity context) {

this.activityWeakReference = new WeakReference<Activity>(context);


}
@Override
protected ArrayList<Merk> doInBackground(Void... params) {
ArrayList<Merk> merkArrayList1 = merkDAO.getMerk();
return merkArrayList1;
}
@Override
protected void onPostExecute(ArrayList<Merk> merkList) {
if (activityWeakReference.get() != null
&& !activityWeakReference.get().isFinishing()) {
merkList = merkList;
if (merkList != null) {
if (merkList.size() != 0) {
listMerkAdapter = new ListMerkAdapter(activity, merkList);
listViewMerk.setAdapter(listMerkAdapter);
} else {
Toast.makeText(activity, "No Data Records",
Toast.LENGTH_LONG).show();
}
}
}
}
}
public void updateView() {
task = new GetMerkTask(activity);
task.execute((Void) null);
}
}
7.3 FragmentNewMerk
Class ini digunakan untuk menampilkan custom dialog fragment form add Merk.
Setelah di save maka akan menjalankan proses save ke database di background
(AsyncTask).
Buat java class file baru dengan nama FragmentNewMerk.java kemudian copy
paste listing coding berikut ini :
package kana.com.motorcycle.fragment;
import android.annotation.TargetApi;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.lang.ref.WeakReference;
import kana.com.motorcycle.R;
import kana.com.motorcycle.dao.MerkDAO;
import kana.com.motorcycle.model.Merk;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class FragmentNewMerk extends Fragment implements
View.OnClickListener{
private EditText merkNamaText;
private EditText merkNegaraAsalText;
private Button addButton;
private Button resetButton;
private AddMerkTask addMerkTask;
Merk merk= null;
private MerkDAO merkDAO;
public static final String ARG_ITEM_ID = "merk_add_fragment";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
merkDAO = new MerkDAO(getActivity());
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.merk_add_fragment, container,
false);
findViewsById(rootView);
setListeners();
return rootView;
}
private void setListeners() {
merkNamaText.setOnClickListener(this);

merkNegaraAsalText.setOnClickListener(this);
addButton.setOnClickListener(this);
resetButton.setOnClickListener(this);
}
protected void resetAllFields() {
merkNamaText.setText("");
}
private void setMerk() {
merk = new Merk();
merk.setnamaMerk(merkNamaText.getText().toString());
merk.setNegaraAsal(merkNegaraAsalText.getText().toString());
}
private void findViewsById(View rootView) {
merkNamaText = (EditText) rootView.findViewById(R.id.txt_nama_merk);
merkNegaraAsalText= (EditText)
rootView.findViewById(R.id.txt_negara_asal);
addButton = (Button) rootView.findViewById(R.id.button_add);
resetButton = (Button) rootView.findViewById(R.id.button_reset);
}
@Override
public void onClick(View v) {
if(v == addButton){
setMerk();
addMerkTask = new AddMerkTask(getActivity());
addMerkTask.execute((Void) null);
}else if(v == resetButton){
resetAllFields();
}
}
public class AddMerkTask extends AsyncTask<Void, Void, Long> {
private final WeakReference<Activity> activityWeakRef;
public AddMerkTask(Activity context) {
this.activityWeakRef = new WeakReference<Activity>(context);
}
@Override
protected Long doInBackground(Void... arg0) {
long result = merkDAO.save(merk);
return result;
}
@Override
protected void onPostExecute(Long result) {

if (activityWeakRef.get() != null
&& !activityWeakRef.get().isFinishing()) {
if (result != -1)
Toast.makeText(activityWeakRef.get(), "Data Merk Saved",
Toast.LENGTH_LONG).show();
resetAllFields();
Fragment fragment = new FragmentMerk();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container,
fragment).commit();
}
}
}
}
7.4 FragmentMotorcycle
Class ini digunakan untuk :
- Menjalankan sebuah tugas secara background(AsyncTask) ketika
memanggil method getMotorcycle() di class MotorcycleDAO dan
menampilkan list merk di Listview
- Ketika salah satu item list di click akan menampilkan sebuah custom
dialog fragment untuk merubah Motorcycle detail
Buat java class baru dengan nama FragmentMotorcycle.java di package
kana.com.motorcycle.fragment kemudian copy paste listing coding di bawah
ini :
package kana.com.motorcycle.fragment;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import kana.com.motorcycle.R;
import kana.com.motorcycle.adapter.ListMotorcycleAdapter;
import kana.com.motorcycle.dao.MotorcycleDAO;
import kana.com.motorcycle.model.Motorcycle;

public class FragmentMotorcycle extends Fragment implements


AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener{
public static final String ARG_ITEM_ID ="motor_list";
Button btnNew;
Activity activity;
ListView motorListVIew;
ArrayList<Motorcycle> motorArrayList;
ListMotorcycleAdapter listMotorcycleAdapter;
MotorcycleDAO motorcycleDAO;
private GetMotorTask task;
// this Fragment will be called from MainActivity
public FragmentMotorcycle(){}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
motorcycleDAO = new MotorcycleDAO(activity);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.motorcycle_fragment, container,
false);
findViewById(rootView);
task = new GetMotorTask(activity);
task.execute((Void) null);
motorListVIew.setOnItemClickListener(this);
motorListVIew.setOnItemLongClickListener(this);
btnNew = (Button) rootView.findViewById(R.id.btnNewMotor);
btnNew.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Fragment fragment = new FragmentNewMotorcycle();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container,
fragment).commit();
}
});

return rootView;
}
private void findViewById(View view){
motorListVIew =(ListView) view.findViewById(R.id.listViewMotorcycle);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long
id) {
Motorcycle motorcycle =(Motorcycle) parent.getItemAtPosition(position);
if(motorcycle != null){
Bundle arguments = new Bundle();
arguments.putParcelable("selectedMotorcycle", motorcycle);
CustomMotorcycleDialogFragment customMotorcycleDialogFragment =
new CustomMotorcycleDialogFragment();
customMotorcycleDialogFragment.setArguments(arguments);
customMotorcycleDialogFragment.show(getFragmentManager(),
CustomMotorcycleDialogFragment.ARG_ITEM_ID);
}
}
public void panggilUlang(){
Fragment fragment = new FragmentMotorcycle();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container,
fragment).commit();
}
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int
position, long id) {
final Motorcycle motorcycle = (Motorcycle)
parent.getItemAtPosition(position);
AlertDialog.Builder alertDialogBuilder = new
AlertDialog.Builder(getActivity());
alertDialogBuilder.setTitle("yakin Hapus Data ?");
alertDialogBuilder
.setMessage("Tekan Yes Untuk Menghapus !")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
listMotorcycleAdapter.remove(motorcycle);
motorcycleDAO.delete(motorcycle);
panggilUlang();
Toast.makeText(activity, "Record " + motorcycle.getNamaMotor()
+ " Data Deleted !", Toast.LENGTH_LONG).show();

}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
return true;
}
public class GetMotorTask extends AsyncTask<Void, Void,
ArrayList<Motorcycle>> {
private final WeakReference<Activity> activityWeakRef;
public GetMotorTask(Activity context) {
this.activityWeakRef = new WeakReference<Activity>(context);
}
@Override
protected ArrayList<Motorcycle> doInBackground(Void... arg0) {
ArrayList<Motorcycle> motorcycleList =
motorcycleDAO.getMotorcycle();
return motorcycleList;
}
@Override
protected void onPostExecute(ArrayList<Motorcycle> list) {
if (activityWeakRef.get() != null
&& !activityWeakRef.get().isFinishing()) {
motorArrayList = list;
if (list != null) {
if (list.size() != 0) {
listMotorcycleAdapter = new ListMotorcycleAdapter(activity,
list);
motorListVIew.setAdapter(listMotorcycleAdapter);
} else {
Toast.makeText(activity, "No Motorcycle Records",
Toast.LENGTH_LONG).show();
}
}
}
}
}

}
7.5 FragmentNewMotorcycle
Class ini digunakan untuk menampilkan custom dialog fragment form add
Motorcycle. Setelah di save maka akan menjalankan proses save ke database di
background (AsyncTask).
Buat java class file baru dengan nama FragmentNewMotorcycle.java kemudian
copy paste listing coding berikut ini :
package kana.com.motorcycle.fragment;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import java.lang.ref.WeakReference;
import java.util.List;
import kana.com.motorcycle.R;
import kana.com.motorcycle.dao.MotorcycleDAO;
import kana.com.motorcycle.dao.MerkDAO;
import kana.com.motorcycle.model.Merk;
import kana.com.motorcycle.model.Motorcycle;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class FragmentNewMotorcycle extends Fragment implements
View.OnClickListener{
private EditText motorcycleNamalText;
private Spinner albumSPinner;
private Button addButton;
private Button resetButton;
private AddMotorcycleTask addMotorcycleTask;
private GetMerkTask task;
Motorcycle motorcycle= null;

private MotorcycleDAO motorcycleDAO;


private MerkDAO merkDAO;
public static final String ARG_ITEM_ID = "merk_add_fragment";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
merkDAO = new MerkDAO(getActivity());
motorcycleDAO = new MotorcycleDAO(getActivity());
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.motorcycle_add_fragment,
container, false);
findViewsById(rootView);
setListeners();
task= new GetMerkTask(getActivity());
task.execute((Void) null);
return rootView;
}
private void setListeners() {
addButton.setOnClickListener(this);
resetButton.setOnClickListener(this);
}
protected void resetAllFields() {
motorcycleNamalText.setText("");
if(albumSPinner.getAdapter().getCount() > 0)
albumSPinner.setSelection(0);
}
private void setMotorcycle() {
motorcycle = new Motorcycle();
motorcycle.setNamaMotor(motorcycleNamalText.getText().toString());
Merk merk = (Merk) albumSPinner.getSelectedItem();
motorcycle.setMerk(merk);
}
private void findViewsById(View rootView) {
motorcycleNamalText = (EditText)
rootView.findViewById(R.id.txt_nama_motor);
albumSPinner= (Spinner) rootView.findViewById(R.id.spinner_merk);
addButton = (Button) rootView.findViewById(R.id.button_add);
resetButton = (Button) rootView.findViewById(R.id.button_reset);
}
@Override

public void onClick(View v) {


if(v == addButton){
setMotorcycle();
addMotorcycleTask = new AddMotorcycleTask(getActivity());
addMotorcycleTask.execute((Void) null);
}else if(v == resetButton){
resetAllFields();
}
}
public class GetMerkTask extends AsyncTask<Void, Void, Void> {
private final WeakReference<Activity> activityWeakRef;
private List<Merk> listMerk;
public GetMerkTask(Activity context) {
this.activityWeakRef = new WeakReference<Activity>(context);
}
@Override
protected Void doInBackground(Void... arg0) {
listMerk = merkDAO.getMerk();
return null;
}
@Override
protected void onPostExecute(Void v) {
if (activityWeakRef.get() != null
&& !activityWeakRef.get().isFinishing()) {
ArrayAdapter<Merk> adapter = new ArrayAdapter<Merk>(
activityWeakRef.get(),
android.R.layout.simple_list_item_1, listMerk);
albumSPinner.setAdapter(adapter);
addButton.setEnabled(true);
}
}
}
public class AddMotorcycleTask extends AsyncTask<Void, Void, Long> {
private final WeakReference<Activity> activityWeakRef;
public AddMotorcycleTask(Activity context) {
this.activityWeakRef = new WeakReference<Activity>(context);
}
@Override
protected Long doInBackground(Void... arg0) {

long result = motorcycleDAO.save(motorcycle);


return result;
}
@Override
protected void onPostExecute(Long result) {
if (activityWeakRef.get() != null
&& !activityWeakRef.get().isFinishing()) {
if (result != -1)
Toast.makeText(activityWeakRef.get(), "Data Motorcycle Saved",
Toast.LENGTH_LONG).show();
resetAllFields();
Fragment fragment = new FragmentMotorcycle();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container,
fragment).commit();
}
}
}
}
7.6 CustomMerkDialogFragment
Class ini berfungsi untuk menerima objek Merk di bundle sebagai sebuah
argument dan menampilkan dialog box berisi detail informasi Merk(Merk Name
dan Negara Asal).
Buat java class file baru dengan nama CustomMerkDialogFragment.java
kemudian copy paste listing coding berikut ini :
package kana.com.motorcycle.fragment;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
import kana.com.motorcycle.R;

import kana.com.motorcycle.dao.MerkDAO;
import kana.com.motorcycle.model.Merk;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class CustomMerkDialogFragment extends DialogFragment {
//
//
//

// UI references
private EditText merkTxtNama;
private EditText merkTxtNegaraAsal;
private Spinner spinner;
private LinearLayout submitLayout;

//
private Merk merk;
//
MerkDAO merkDAO;
ArrayAdapter<Merk> adapter;
//
public static final String ARG_ITEM_ID = "merk_dialog_fragment";
public interface CustomEmpDialogFragmentListener {
void onFinishDialog();
}
//
public CustomMerkDialogFragment() {
}
//
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
merkDAO = new MerkDAO(getActivity());
Bundle bundle = this.getArguments();
merk = bundle.getParcelable("selectedMerk");
//
AlertDialog.Builder builder = new
AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
//
View customDialogView =
inflater.inflate(R.layout.merk_add_fragment,
null);
builder.setView(customDialogView);
//
merkTxtNama = (EditText)
customDialogView.findViewById(R.id.txt_nama_merk);
merkTxtNegaraAsal= (EditText)
customDialogView.findViewById(R.id.txt_negara_asal);

submitLayout = (LinearLayout) customDialogView


.findViewById(R.id.layout_submit);
submitLayout.setVisibility(View.GONE);
setValue();
//
builder.setTitle("Update Merk");
builder.setCancelable(false);
builder.setPositiveButton(R.string.update,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//
merk.setnamaMerk(merkTxtNama.getText().toString());
merk.setNegaraAsal(merkTxtNegaraAsal.getText().toString());
long result = merkDAO.update(merk);
if (result > 0) {
Toast.makeText(getActivity(),
"Data Updated ..", Toast.LENGTH_SHORT).show();
Fragment fragment = new FragmentMerk();
FragmentManager fragmentManager =
getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container,
fragment).commit();
} else {
Toast.makeText(getActivity(),
"Unable to update merk",
Toast.LENGTH_SHORT).show();
dialog.cancel();
}
}
});
builder.setNeutralButton(R.string.delete,
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
long result1 = merkDAO.deleteMerk(merk);
if(result1 > 0){
Toast.makeText(getActivity(),
"Data Deleted ..", Toast.LENGTH_SHORT).show();
Fragment fragment = new FragmentMerk();
FragmentManager fragmentManager =
getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container,
fragment).commit();
} else {
Toast.makeText(getActivity(),

"Unable to delete merk", Toast.LENGTH_SHORT).show();


dialog.cancel();
}
}
});
builder.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = builder.create();
return alertDialog;
}
//
private void setValue() {
MerkDAO DAO = new MerkDAO(getActivity());
if (merk != null) {
merkTxtNama.setText(merk.getnamaMerk());
merkTxtNegaraAsal.setText(merk.getNegaraAsal());
}
}
}
7.7 CustomMotorcycleDialogFragment
Class ini berfungsi untuk menerima objek Motorcycle di bundle sebagai sebuah
argument dan menampilkan dialog box berisi detail informasi Motorcycle(Nama
Motorcycle dan Merk).
Buat java class file baru dengan nama CustomMotorcycleDialogFragment.java
kemudian copy paste listing coding berikut ini :
package kana.com.motorcycle.fragment;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;

import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.List;
import kana.com.motorcycle.R;
import kana.com.motorcycle.dao.MotorcycleDAO;
import kana.com.motorcycle.dao.MerkDAO;
import kana.com.motorcycle.model.Merk;
import kana.com.motorcycle.model.Motorcycle;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class CustomMotorcycleDialogFragment extends DialogFragment {
//
//
//

// UI references
private EditText motorcycleTxtNamaMotor;
private Spinner merkSpinner;
private Spinner spinner;
private LinearLayout submitLayout;

//
private Motorcycle motorcycle;
//
MotorcycleDAO motorcycleDAO;
ArrayAdapter<Merk> adapter;
//
public static final String ARG_ITEM_ID =
"motorcycle_dialog_fragment";
public interface CustomMotorcycleDialogFragmentListener {
void onFinishDialog();
}
//
public CustomMotorcycleDialogFragment() {
}
//
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
motorcycleDAO = new MotorcycleDAO(getActivity());
Bundle bundle = this.getArguments();
motorcycle = bundle.getParcelable("selectedMotorcycle");
//
AlertDialog.Builder builder = new
AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();

//
View customDialogView =
inflater.inflate(R.layout.motorcycle_add_fragment,
null);
builder.setView(customDialogView);
//
motorcycleTxtNamaMotor = (EditText)
customDialogView.findViewById(R.id.txt_nama_motor);
merkSpinner= (Spinner)
customDialogView.findViewById(R.id.spinner_merk);
//
submitLayout = (LinearLayout) customDialogView
.findViewById(R.id.layout_submit);
submitLayout.setVisibility(View.GONE);
setValue();
//
builder.setTitle("Update Motorcycle");
builder.setCancelable(false);
builder.setPositiveButton(R.string.update,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//
motorcycle.setNamaMotor(motorcycleTxtNamaMotor.getText().toString());
Merk merk = (Merk)
adapter.getItem(merkSpinner.getSelectedItemPosition());
motorcycle.setMerk(merk);
long result = motorcycleDAO.update(motorcycle);
if (result > 0) {
Toast.makeText(getActivity(),
"Data Updated ..", Toast.LENGTH_SHORT).show();
Fragment fragment = new FragmentMotorcycle();
FragmentManager fragmentManager =
getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container,
fragment).commit();
} else {
Toast.makeText(getActivity(), "Unable to update motorcycle",
Toast.LENGTH_SHORT).show();
dialog.cancel();
}
}
});
builder.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();

}
});
AlertDialog alertDialog = builder.create();
return alertDialog;
}
//
private void setValue() {
MerkDAO DAO = new MerkDAO(getActivity());
//
List<Merk> listAlbum = DAO.getMerk();
adapter = new ArrayAdapter<Merk>(getActivity(),
android.R.layout.simple_list_item_1, listAlbum);
merkSpinner.setAdapter(adapter);
int pos = adapter.getPosition(motorcycle.getMerk());
if (motorcycle != null) {
motorcycleTxtNamaMotor.setText(motorcycle.getNamaMotor());
merkSpinner.setSelection(pos);
}
}
}
8. Modifikasi source code activity MainActivity dan Testing aplikasi
Class MainActivity ini berfungsi untuk mengatur fragment dan navigasi sidebar
seperti mengatur urutan navigasi dan icon tiap navigasi
Di tahap akhir, modif source code MainActivity seperti listing coding di bawah ini :
package kana.com.motorcycle;
import android.os.Bundle;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.StrictMode;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import kana.com.motorcycle.adapter.NavDrawerListAdapter;

import kana.com.motorcycle.fragment.FragmentMerk;
import kana.com.motorcycle.fragment.FragmentMain;
import kana.com.motorcycle.fragment.FragmentMotorcycle;
import kana.com.motorcycle.model.NavDrawerItem;
public class MainActivity extends ActionBarActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// NavigationDrawer title "Nasdaq" in this example
private CharSequence mDrawerTitle;
// App title "Navigation Drawer" in this example
private CharSequence mTitle;
// slider menu items details
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.AppTheme);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
// getting items of slider from array
navMenuTitles =
getResources().getStringArray(R.array.nav_drawer_items);
// getting Navigation drawer icons from res
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// list item in slider at 1
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0],
navMenuIcons.getResourceId(0, -1)));
// list item in slider at 2
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1],

navMenuIcons.getResourceId(1, -1)));
// list item in slider at 3
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2],
navMenuIcons.getResourceId(2, -1)));
// Recycle array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting list adapter for Navigation Drawer
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// Enable action bar icon_luncher as toggle Home Button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.app_name, R.string.app_name) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
invalidateOptionsMenu(); //Setting, Refresh and Rate App
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
displayView(0);
}
}
/**
* Slider menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected item
displayView(position);
}

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// title/icon
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if Navigation drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
private void displayView(int position) {
// update the main content with called Fragment
Fragment fragment = null;
switch (position) {
case 0:
fragment = new FragmentMain();
break;
case 1:
fragment = new FragmentMerk();
break;
case 2:
fragment = new FragmentMotorcycle();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();

fragmentManager.beginTransaction().replace(R.id.frame_container,
fragment).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
Log.e("this is mainActivity", "Error in else case");
}
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
Testing Aplikasi
Buka software genymotion kemudian pilih salah satu virtual device yang sudah
terinstall kemudian click Start

Untuk menjalankan aplikasi, klik icon run kemudian pilih virtual device yang
sudah jalan seperti di bawah ini

Saat menjalankan aplikasi, pertama kali muncul Splash Screen seperti di bawah
ini :

Kemudian setelah itu muncul halaman utama aplikasi seperti di bawah ini :

Untuk navigasi sidebar bias click icon sebelah kiri Home maka akan tampil
seperti di bawah ini :

Jika pilih menu Merk maka akan tampil halaman aplikasi seperti di bawah ini :

Click New Merk maka akan muncul halaman aplikasi seperti di bawah ini :

Klik save maka akan data akan bertambah dan kembali ke halaman sebelumnya
dengan menampilkan semua data

Klik salah satu data merk kemudian akan tampil dialog box seperti dibawah ini.

Jika pilih update maka akan mengupdate data sesuai data inputan, jika pilih
delete maka akan menghapus data yang di pilih, jika pilih cancel maka akan
kembali ke halaman sebelumnya

Begitu juga dengan halaman menu motorcycle