Professional Documents
Culture Documents
Modul Praktikum Pemrograman Mobile Penyu
Modul Praktikum Pemrograman Mobile Penyu
PEMROGRAMAN MOBILE
PENYUSUN
Joko Triyono, S.Kom., M.Cs.,
Wahyuni Eka Sari
Yunis Aprilianti
i
MODUL PRAKTIKUM
PEMROGRAMAN MOBILE
Disusun oleh:
Joko Triyono, S.Kom., M.Cs
Pengampu Matakuliah Pemrograman Mobile
Web : http://jack.akprind.ac.id/
e-Mail : zainjack@gmail.com
ii
KATA PENGANTAR
Modul ini dirancang untuk selalu dinamis mengikuti schedul tatap muka
dosen di kelas, sehingga apa yang disampaikan di kelas akan di pertajam lagi di
kelas praktikum. Dengan mengikuti step-step di modul ini secara tertip dan
terurut, diharapkan mahasiswa akan memahami tentang matakuliah ini dan bisa di
implementasikan dalam kehidupan akademis untuk menunjang keberhasilan
mahasiswa.
Demikian semoga modul ini bisa bermanfaat bagi kita semua. Amin.
iii
HALAMAN INI
SENGAJA
DI KOSONGKAN
iv
DAFTAR ISI
Halaman Judul ........................................................................................ i
Halaman Penulis ..................................................................................... ii
Kata Pengantar ........................................................................................ iii
Daftar Isi ......................................................................................... v
Pertemuan 1 Pengenalan Android ........................................................ 1
Pertemuan 2 Membuat Toast, List Dialog, Alert Dialog ...................... 9
Pertemuan 3 Membuat Intent................................................................ 14
Pertemuan 4 Membuat Aplikasi Kalkulator ......................................... 25
Pertemuan 5 SQL Lite .......................................................................... 36
Pertemuan 6 Pembuatan Projet ............................................................. 47
Pertemuan 7 Membuat Aplikasi Dengan Php Mysql (Relasi Tabel)
Part I ................................................................................ 76
Pertemuan 8 Membuat Aplikasi Dengan Php Mysql (Relasi Tabel)
Part II ............................................................................... 76
v
Modul praktikum Pemrograman Mobile
PERTEMUAN 1
Bagian ini akan menjelaskan tentang :
Konsep umum android
Proses instalasi Eclipse
Membuat Program Pertama
...........................................................................................................................................................
PENGENALAN ANDROID
Android adalah sistem operasi untuk telepon seluler yang berbasis
Linux.Android menyediakan platform yang bersifat open source bagi para pengembang
untuk menciptakan sebuah aplikasi.Awalnya, Google Inc. mengakuisi Android Inc. yang
mengembangkan software untuk ponsel yang berada di Palo Alto, California Amerika
Serikat. Kemudian untuk mengembangkan Android, dibentuklah Open Handset Alliance,
yaitu konsorsium dari 34 perusahaan hardware, software, dan telekomunikasi, termasuk
Google, HTC, Intel, Motorola, Qualcomm, T-Mobile, dan Nvidia.
Sebuah Activity biasanya ditampilkan dalam satu screen sebagai bagian
komponen dari View (yang terdiri dari komponen UI, widget atau control), yang bertugas
melakukan interaksi dengan user untuk melakukan sebuah task tunggal (misalnya,
melihat informasi, mengedit data, atau memasukkan data).
Sebuah aplikasi Android biasanya memiliki satu atau lebih Activity. Salah satu
Activity ditandai sebagai startup activity, yang pada gilirannya memulai activity
berikutnya, melalui sebuah intent. Untuk membuat suatu activity, kita melakukan extend
terhadap class android.app.Activity, dan melakukan override beberapa method, khususnya
method OnCreate().
Kita bisa mengatur konten view dari activity secara bahasa pemrograman java atau juga
bisa melalui kode layout file XML
Daur hidup sebuah activity diatur melalui method call-back, yang di definisikan pada
class dasar Activity pada gambar 1.1. tentang siklus hidup android.
Ketiga file tersebut sudah include didalam satu folder. Saat mendownload silahkan
sesuaikan dengan tipe sistem operasi komputer. Kemudian install JDK (Java Development
Kit) minimal versi 7 dan install di komputer. Berikut ini adalah langkah-langkah instalasi :
1
Modul praktikum Pemrograman Mobile
1. Instal JDK, Awal Instalasi pada gambar 1.2. Silahkan Klik Next hingga proses
instalasi selesai.
2
Modul praktikum Pemrograman Mobile
3
Modul praktikum Pemrograman Mobile
4. Selanjutnya adalah proses konfigurasi emulator android pada gambar 1.5, klik
New
4
Modul praktikum Pemrograman Mobile
6. Setelah itu, klik start untuk menjalankan emulator yang telah dibuat. Android
Device Virtual gambar 1.7 telah selesai dibuat.
6
Modul praktikum Pemrograman Mobile
7
Modul praktikum Pemrograman Mobile
6. Jalankan aplikasi dengan cara klik kanan package > pilih Run As > Android
Application Project, atau dengan shortcut CTRL + F11.
7. Aplikasi dapat didownload langsung ke perangkat android. File
ProjectPertama.apk terletak di folder ProjectPertama/bin.
8
Modul praktikum Pemrograman Mobile
PERTEMUAN 2
Bagian ini akan menjelaskan tentang :
Menampilkan gambar
Membuat dialog interaktif dengan toast, list, dan alert
...........................................................................................................................................................
MEMBUAT TOAST, LIST DIALOG, ALERT DIALOG
Pada pertemuan kedua kita akan membuat kotak dialog sebagai sarana interaktif antara
aplikasi dengan pengguna. Pada aplikasi ini kita akan mengimplementasikan 3 macam
• Toast
dialog, antara lain :
• List dialog
• Alert dialog
Untuk membuat aplikasi ini. Silahkan membuat project baru seperti pada gambar dibawah
ini.
1. Membuat project dengan nama alertlist pada gambar 2.1
9
Modul praktikum Pemrograman Mobile
<TextView
android:id="@+id/seleksi"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
<Button
android:id="@+id/pesantoast"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Tampilkan Toast" />
<Button
android:id="@+id/keluar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/seleksi"
android:layout_marginBottom="36dp"
android:text="Keluar" />
<Button
android:id="@+id/tampillist"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/pesantoast"
android:layout_marginTop="18dp"
android:text="Tampilkan List" />
</RelativeLayout>
10
Modul praktikum Pemrograman Mobile
11
Modul praktikum Pemrograman Mobile
@Override
public void onClick(DialogInterface arg0, int arg1) {
arg0.cancel();
// TODO Auto-generated method stub
}
} ).show();
}
else if (arg0 == tampillist){
final CharSequence[] item = {"Jeruk", "Jambu", "Nangka", "Nanas"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pilih Minuman");
builder.setItems(item, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getBaseContext(), item[arg1], Toast.LENGTH_SHORT).show();
// TODO Auto-generated method stub
}
}).show();
}
// TODO Auto-generated method stub
}
}
12
Modul praktikum Pemrograman Mobile
13
Modul praktikum Pemrograman Mobile
PERTEMUAN 3
Pada bagian ini, kita akan mempelajari :
Intent untuk memanggil activity
Penerapan intent pada aplikasi konversi berat badan
...........................................................................................................................................................
MEMBUAT INTENT
Pada pertemuan ketiga kita akan belajar membuat intent sederhana. Inti dari sebuah
aplikasi ada 3, yaitu activity, service dan broadcast. Intent digunakan untuk memanggil
activity, memanggil service, atau melakukan broadcast.
Pada bagian ini, kita akan memahami intent paling sederhana yaitu memanggil activity
lain.
1. Buat project dengan nama IntentPertama
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ActivityPertama" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next" />
</LinearLayout>
15
Modul praktikum Pemrograman Mobile
import android.widget.Button;
public class ActivityKedua extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kedua);
Button back = (Button)findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
// TODO Auto-generated method stub
}
});
}}
17
Modul praktikum Pemrograman Mobile
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Username" />
<EditText
android:id="@+id/username"
android:layout_width="match_parent"
18
Modul praktikum Pemrograman Mobile
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password" />
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword" />
<Button
android:id="@+id/login"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Login" />
</LinearLayout>
username = (EditText)findViewById(R.id.username);
password = (EditText)findViewById(R.id.password);
login = (Button)findViewById(R.id.login);
19
Modul praktikum Pemrograman Mobile
login.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onClick(View arg0) {
try{
if(arg0.getId() == R.id.login){
Intent i = new Intent(getBaseContext(), Main2Activity.class);
startActivityForResult(i, 0);
}
}
catch (Exception e){
Toast.makeText(getBaseContext(), "Anda Tidak Berhak Masuk",
Toast.LENGTH_LONG).show();
}
}
}
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Masukkan Tinggi Badan" />
<EditText
android:id="@+id/tinggi"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" />
<Button
android:id="@+id/hasil"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hasil" />
<TextView
android:id="@+id/output"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hasil" />
<Button
android:id="@+id/back"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Back" />
<Button
android:id="@+id/exit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Exit" />
</LinearLayout>
import android.app.Activity;
public class Main2Activity extends Activity implements OnClickListener {
Button hasil, back, exit;
EditText berat, tinggi;
TextView output;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
berat = (EditText)findViewById(R.id.berat);
tinggi = (EditText)findViewById(R.id.tinggi);
output = (TextView)findViewById(R.id.output);
hasil = (Button)findViewById(R.id.hasil);
back = (Button)findViewById(R.id.back);
exit = (Button)findViewById(R.id.exit);
hasil.setOnClickListener(this);
back.setOnClickListener(this);
exit.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main2, menu);
return true;
}
@Override
public void onClick(View v) {
int angka = 110; //angka ideal
int angka1 = Integer.parseInt(berat.getText().toString());
//merubah dari string edittext ke integer
int angka2 = Integer.parseInt(tinggi.getText().toString());
int ideal = angka2 - angka1; //berat badan ideal
int ideal2 = angka2 - angka; //berat badan yang disarankan
try{
if(v.getId() == R.id.hasil){ //button hasil
if(ideal == 110){
output.setText("Berat Badan Anda Ideal");
}else if (ideal > 110){
output.setText("Anda Kurus");
22
Modul praktikum Pemrograman Mobile
}else{
output.setText("Anda Gemuk, berat Anda "+angka1+" Tinggi Anda
"+angka2+" Seharusnya Berat badan anda "+ideal2);
}
}else if (v.getId() == R.id.exit){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Apakah Anda Ingin Keluar ?")
.setCancelable(false).setPositiveButton("OK", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
Main2Activity.this.finish();
}
})
.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}else if (v.getId() == R.id.back){
Intent i = new Intent(getBaseContext(), MainActivity.class);
startActivityForResult(i, 0);
}else{
Toast.makeText(getBaseContext(), "Masukkan Berat dan Tinggi
Badan Anda", Toast.LENGTH_SHORT).show();
output.setText("Masukkan Angka Dulu");
}
}catch(Exception e){
Toast.makeText(getBaseContext(), "Hahaha", Toast.LENGTH_SHORT).show();
}
}
}
23
Modul praktikum Pemrograman Mobile
24
Modul praktikum Pemrograman Mobile
PERTEMUAN 4
Pada bagian ini, kita akan mempelajari :
Membuat aplikasi kalkulator sederhana
Pengenalan Autocomplete
...........................................................................................................................................................
MEMBUAT APLIKASI KALKULATOR
1. Buat project dengan nama kalkulator
tambah.setOnClickListener(this);
kurang.setOnClickListener(this);
kali.setOnClickListener(this);
bagi.setOnClickListener(this);
next.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int angka1 = Integer.parseInt(a.getText().toString());
int angka2 = Integer.parseInt(b.getText().toString());
int hasil = angka1 + angka2;
int hasil2 = angka1 - angka2;
int hasil3 = angka1 * angka2;
float hasil4 = angka1 / angka2;
try {
if (v.getId() == R.id.tambah) {
26
Modul praktikum Pemrograman Mobile
c.setText(Integer.toString(hasil));
} else if (v.getId() == R.id.kurang) {
c.setText(Integer.toString(hasil2));
} else if (v.getId() == R.id.kali) {
c.setText(Integer.toString(hasil3));
} else if (v.getId() == R.id.bagi){
c.setText(Float.toString(hasil4));
} else {
Intent i = new Intent(getBaseContext(), MainActivity2.class);
startActivityForResult(i, 0);
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), "Salah",
Toast.LENGTH_LONG).show();
c.setText("Tak Terhingga ~");
}
// ketiga.settext(string.valueof(hasil)).tostring());
}
}
4. Modifikasi main2.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity2" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
<Button
android:id="@+id/back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignRight="@+id/textView1"
27
Modul praktikum Pemrograman Mobile
android:layout_marginTop="40dp"
android:text="Back" />
</RelativeLayout>
28
Modul praktikum Pemrograman Mobile
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="NIM" />
<EditText
android:id="@+id/nim"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" />
<TextView
android:id="@+id/seleksi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ASAL PROVINSI" />
<AutoCompleteTextView
android:id="@+id/provinsi"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:text="Provinsi" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="JENIS KELAMIN" />
<RadioGroup
android:id="@+id/jk"
android:padding="5px"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/pria"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pria" />
<RadioButton
android:id="@+id/wanita"
30
Modul praktikum Pemrograman Mobile
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Wanita" />
</RadioGroup>
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ANDA SETUJU DENGAN SEGALA KETENTUAN DARI
KAMI " />
<CheckBox
android:id="@+id/ya"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ya" />
<ImageButton
android:id="@+id/create"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:drawable/ic_input_add" />
</LinearLayout>
31
Modul praktikum Pemrograman Mobile
}
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
}
}
33
Modul praktikum Pemrograman Mobile
6. Jalankan aplikasi
35
Modul praktikum Pemrograman Mobile
PERTEMUAN 5
Pada bagian ini, kita akan mempelajari :
Membuat aplikasi database sederhana dengan SQLite
...........................................................................................................................................................
PENGENALAN SQLite
SQLite adalah database yang dibangun di Android. Hampir sama dengan SQL pada
dekstop, SQLite memiliki fiture relasional database namun membutuhkan sedikit
memori.
SQLite terdapat pada semua perangkat Android. Anda culup mendefinisikan perintah
SQL untuk meng-create atau meng-update database, selanjutnya sistem ada Android akan
menangani hal-hal yang berhubungan dengn database. SQLite database otomatis akan
tersimpan didalam path data/data/nama_package/database/nama_database.
PEMBUATAN APLIKASI
1. Buat project baru dengan nama AndroidCrudExample. Lalu setelah itu
modifikasi layout activity_main.xml sesuai dengan gambar 5.1;
36
Modul praktikum Pemrograman Mobile
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
protected static final String DATABASE_NAME = "StudentDatabase";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE students " +
"( id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"firstname TEXT, " +
"email TEXT ) ";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "DROP TABLE IF EXISTS students";
db.execSQL(sql);
onCreate(db);
}
}
5. Setelah itu modifikasi file MainActivity.java (bagi yang tidak memiliki atau
belum membuat file MainActivity.java buat terlebih dahulu)
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonCreateLocation = (Button)
findViewById(R.id.buttonCreateStudent);
buttonCreateLocation.setOnClickListener(new
OnClickListenerCreateStudent());
countRecords();
readRecords();
}
public void countRecords() {
int recordCount = new TableControllerStudent(this).count();
TextView textViewRecordCount = (TextView)
findViewById(R.id.textViewRecordCount);
textViewRecordCount.setText(recordCount + " records found.");
}
public void readRecords() {
LinearLayout linearLayoutRecords = (LinearLayout)
findViewById(R.id.linearLayoutRecords);
linearLayoutRecords.removeAllViews();
List<ObjectStudent> students = new
TableControllerStudent(this).read();
38
Modul praktikum Pemrograman Mobile
if (students.size() > 0) {
for (ObjectStudent obj : students) {
int id = obj.id;
String studentFirstname = obj.firstname;
String studentEmail = obj.email;
String textViewContents = studentFirstname + " - " + studentEmail;
TextView textViewLocationItem = new TextView(this);
textViewLocationItem.setPadding(0, 10, 0, 10);
textViewLocationItem.setText(textViewContents);
textViewLocationItem.setTag(Integer.toString(id));
textViewLocationItem.setOnLongClickListener(new
OnLongClickListenerStudentRecord());
linearLayoutRecords.addView(textViewLocationItem);
}
}
else {
TextView locationItem = new TextView(this);
locationItem.setPadding(8, 8, 8, 8);
locationItem.setText("No records yet.");
linearLayoutRecords.addView(locationItem);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
39
Modul praktikum Pemrograman Mobile
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class TableControllerStudent extends DatabaseHandler {
public TableControllerStudent(Context context) {
super(context);
}
40
Modul praktikum Pemrograman Mobile
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;
@Override
public void onClick(View view) {
final Context context = view.getContext();
LayoutInflater inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View formElementsView = inflater.inflate(R.layout.student_input_form, null,
false);
final EditText editTextStudentFirstname = (EditText)
formElementsView.findViewById(R.id.editTextStudentFirstname);
final EditText editTextStudentEmail = (EditText)
formElementsView.findViewById(R.id.editTextStudentEmail);
new AlertDialog.Builder(context)
.setView(formElementsView)
.setTitle("Create Student")
.setPositiveButton("Add",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
42
Modul praktikum Pemrograman Mobile
((MainActivity) context).countRecords();
((MainActivity) context).readRecords();
dialog.cancel();
}
}).show();
}
}
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.EditText;
import android.widget.Toast;
43
Modul praktikum Pemrograman Mobile
Context context;
String id;
@Override
public boolean onLongClick(View view) {
context = view.getContext();
id = view.getTag().toString();
final CharSequence[] items = { "Edit", "Delete" };
new AlertDialog.Builder(context).setTitle("Student Record")
.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
editRecord(Integer.parseInt(id));
}
else if (item == 1) {
boolean deleteSuccessful = new
TableControllerStudent(context).delete(id);
if (deleteSuccessful){
Toast.makeText(context, "Student record was deleted.",
Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "Unable to delete student record.",
Toast.LENGTH_SHORT).show();
}
((MainActivity) context).countRecords();
((MainActivity) context).readRecords();
}
dialog.dismiss();
}
}).show();
return false;
}
public void editRecord(final int studentId) {
final TableControllerStudent tableControllerStudent = new
TableControllerStudent(context);
ObjectStudent objectStudent =
tableControllerStudent.readSingleRecord(studentId);
44
Modul praktikum Pemrograman Mobile
editTextStudentFirstname.setText(objectStudent.firstname);
editTextStudentEmail.setText(objectStudent.email);
new AlertDialog.Builder(context)
.setView(formElementsView)
.setTitle("Edit Record")
.setPositiveButton("Save Changes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ObjectStudent objectStudent = new ObjectStudent();
objectStudent.id = studentId;
objectStudent.firstname = editTextStudentFirstname.getText().toString();
objectStudent.email = editTextStudentEmail.getText().toString();
boolean updateSuccessful = tableControllerStudent.update(objectStudent);
if(updateSuccessful){
Toast.makeText(context, "Student record was updated.",
Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "Unable to update student record.",
Toast.LENGTH_SHORT).show();
}
((MainActivity) context).countRecords();
((MainActivity) context).readRecords();
dialog.cancel();
}
}).show();
}
}
45
Modul praktikum Pemrograman Mobile
9. Setelah semua selesai dibuat, coba jalankan. apakah sesuai dengan gambar
dibawah ?
G
a
m
b
a
r
Gambar 5. Data berhasil diinsert Gambar 6. Pilihan Edit atau Delete data
Gambar 7. Saat berhasiil mengupdate/edit data Gambar 8 . Saat berhasil mendelete data
46
Modul praktikum Pemrograman Mobile
PERTEMUAN 6
2. Setelah database selesai dibuat, kemudia buat buat folder android_connect pada
C:\xampp\htdocs\android_connect setelah itu file db_connect.php untuk koneksi
kedatabase yang disimpan kedalam folder tersebut.
<?php
class DB_CONNECT {
function __construct() {
// connecting to database
$this->connect();
}
function __destruct() {
$this->close();
}
function connect() {
require_once __DIR__ . '/db_config.php';
$con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or
die(mysql_error());
$db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
47
Modul praktikum Pemrograman Mobile
return $con;
}
function close() {
// closing db connection
mysql_close();
}
?>
<?php
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "android_connect"); // database name
define('DB_SERVER', "localhost"); // db server
?>
<?php
$response = array();
$name = $_POST['name'];
$price = $_POST['price'];
$description = $_POST['description'];
48
Modul praktikum Pemrograman Mobile
if ($result) {
$response["success"] = 1;
$response["message"] = "Product successfully created.";
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
echo json_encode($response);
}
?>
<?php
$response = array();
$pid = $_POST['pid'];
$name = $_POST['name'];
$price = $_POST['price'];
$description = $_POST['description'];
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
49
Modul praktikum Pemrograman Mobile
if ($result) {
$response["success"] = 1;
$response["message"] = "Product successfully updated.";
echo json_encode($response);
} else {
}
} else {
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
echo json_encode($response);
}
?>
<?php
$response = array();
if (isset($_POST['pid'])) {
$pid = $_POST['pid'];
if (mysql_affected_rows() > 0) {
$response["success"] = 1;
$response["message"] = "Product successfully deleted";
50
Modul praktikum Pemrograman Mobile
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No product found";
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
echo json_encode($response);
}
?>
<?php
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = mysql_query("SELECT *FROM products") or die(mysql_error());
if (mysql_num_rows($result) > 0) {
$response["products"] = array();
51
Modul praktikum Pemrograman Mobile
array_push($response["products"], $product);
}
$response["success"] = 1;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No products found";
echo json_encode($response);
}
?>
8. Buat juga get_product_details.php
<?php
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
if (isset($_GET["pid"])) {
$pid = $_GET['pid'];
if (!empty($result)) {
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["pid"] = $result["pid"];
$product["name"] = $result["name"];
$product["price"] = $result["price"];
$product["description"] = $result["description"];
$product["created_at"] = $result["created_at"];
$product["updated_at"] = $result["updated_at"];
$response["success"] = 1;
$response["product"] = array();
array_push($response["product"], $product);
52
Modul praktikum Pemrograman Mobile
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No product found";
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "No product found";
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
echo json_encode($response);
}
?>
10. kemudian buat juga layout untuk tampilan add_product, all_products, edit-
product, dan list_item
54
Modul praktikum Pemrograman Mobile
11. Setelah layout selesai dibuat, kemudian lanjut buat file JSONParser.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
// constructor
public JSONParser() {
55
Modul praktikum Pemrograman Mobile
HttpResponse httpResponse =
httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
HttpResponse httpResponse =
httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
56
Modul praktikum Pemrograman Mobile
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new
InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
}
}
import java.util.ArrayList;
import java.util.List;
57
Modul praktikum Pemrograman Mobile
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.androidhive.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
// Progress Dialog
private ProgressDialog pDialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
58
Modul praktikum Pemrograman Mobile
setContentView(R.layout.add_product);
// Edit Text
inputName = (EditText) findViewById(R.id.inputName);
inputPrice = (EditText) findViewById(R.id.inputPrice);
inputDesc = (EditText) findViewById(R.id.inputDesc);
// Create button
Button btnCreateProduct = (Button)
findViewById(R.id.btnCreateProduct);
@Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
59
Modul praktikum Pemrograman Mobile
/**
* Creating product
* */
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String price = inputPrice.getText().toString();
String description = inputDesc.getText().toString();
// Building Parameters
List<NameValuePair> params = new
ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("price", price));
params.add(new BasicNameValuePair("description",
description));
if (success == 1) {
// successfully created product
Intent i = new
Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.androidhive.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
61
Modul praktikum Pemrograman Mobile
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
EditText txtName;
EditText txtPrice;
EditText txtDesc;
EditText txtCreatedAt;
Button btnSave;
Button btnDelete;
String pid;
// Progress Dialog
private ProgressDialog pDialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_product);
// save button
btnSave = (Button) findViewById(R.id.btnSave);
btnDelete = (Button) findViewById(R.id.btnDelete);
@Override
public void onClick(View arg0) {
// starting background task to update product
new SaveProductDetails().execute();
}
});
@Override
63
Modul praktikum Pemrograman Mobile
/**
* Background Async Task to Get complete product details
* */
class GetProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditProductActivity.this);
pDialog.setMessage("Loading product details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
/**
* After completing background task Dismiss the progress dialog
65
Modul praktikum Pemrograman Mobile
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
/**
* Background Async Task to Save product Details
* */
class SaveProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditProductActivity.this);
pDialog.setMessage("Saving product ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Saving product
* */
protected String doInBackground(String... args) {
// getting updated data from EditTexts
String name = txtName.getText().toString();
String price = txtPrice.getText().toString();
String description = txtDesc.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_PID, pid));
params.add(new BasicNameValuePair(TAG_NAME, name));
params.add(new BasicNameValuePair(TAG_PRICE, price));
params.add(new BasicNameValuePair(TAG_DESCRIPTION, description));
// sending modified data through http request
// Notice that update product url accepts POST method
66
Modul praktikum Pemrograman Mobile
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product uupdated
pDialog.dismiss();
}
}
/*****************************************************************
* Background Async Task to Delete Product
* */
class DeleteProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
67
Modul praktikum Pemrograman Mobile
super.onPreExecute();
pDialog = new ProgressDialog(EditProductActivity.this);
pDialog.setMessage("Deleting Product...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Deleting product
* */
protected String doInBackground(String... args) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", pid));
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
url_delete_product, "POST", params);
// check your log for json response
Log.d("Delete Product", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// product successfully deleted
// notify previous activity by sending code 100
Intent i = getIntent();
// send result code 100 to notify about product deletion
setResult(100, i);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
68
Modul praktikum Pemrograman Mobile
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
}
}
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.androidhive.R;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
69
Modul praktikum Pemrograman Mobile
// Progress Dialog
private ProgressDialog pDialog;
// products JSONArray
JSONArray products = null;
Button btnBack;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
// Get listview
ListView lv = getListView();
70
Modul praktikum Pemrograman Mobile
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
72
Modul praktikum Pemrograman Mobile
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String,
String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
73
Modul praktikum Pemrograman Mobile
import com.example.androidhive.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
74
Modul praktikum Pemrograman Mobile
G
a
m
b
a
r
6.7 Tampilan awal dan
Gambar 6.8 Tampilan insert data
75
Modul praktikum Pemrograman Mobile
PERTEMUAN 7
MEMBUAT APLIKASI DENGAN PHP MYSQL (RELASI TABEL) PART I
PERTEMUAN 8
MEMBUAT APLIKASI DENGAN PHP MYSQL (RELASI TABEL) PART II
76