AndroidPHPMySQLdenganActionBar PDF
AndroidPHPMySQLdenganActionBar PDF
Berfungsi sebagai script untu membuat koneksi kedatabase sehingga untuk setiap php yang ingin
connect database cukup dengan mengincludekan file ini.
b. list_phone.php
<?php
include('connection.php');
$query = 'select id, phone_name nama, price harga from tbl_phone';
$result = mysql_query($query) or die(mysql_error());
$data = array();
while($row = mysql_fetch_object($result)){
$data['handphone'][]= $row;
}
echo json_encode($data);
?>
berfungsi untuk mendapatkan data dari table tbl_phone untuk ditampilkan dalam listview di android
c.submit_phone.php untuk menambha data baru datau mengupdate data
<?php
include('connection.php');
$id = (int)$_POST['id'];
$nama = $_POST['nama'];
$harga = $_POST['harga'];
$query = 'insert into tbl_phone (phone_name, price) values ("'.$nama.'", "'.$harga.'")';
if($id > 0){
$query = 'update tbl_phone set phone_name = "'.$nama.'", price = "'.$harga.'" where id = '.$id;
}
mysql_query($query) or die(mysql_error());
?>
Berfungsi untuk menyimpan data kedatabase termasuk memasukkan data abaru atau mengupdate
nilai dari data yang lama
d. delete_phone.php
<?php
include('connection.php');
$id = (int)$_POST['id'];
$query = 'delete from tbl_phone where id = '.$id;
$result = mysql_query($query) or die(mysql_error());
if(mysql_affected_rows() > 0){
echo 'Delete Data Success';
}else{
echo '';
}
?>
berfungsi untuk menghapus data yang ada pada tbl_phone
e. index.php
<html>
<head>
<title>Index Harga Handphone</title>
</head>
<body>
<h3>Selamat Datang di Webstite Harga HP</h3>
</body>
</html>
3. Kita sudah selesai mengerakan pada sisi server yaitu database dan phpnya untuk memastikan
bahwa dari emulator android bisa terhubung dengan server buka browser android lalu ketikan
address http://10.0.2.2/xphone.php
Klik Next sampai finish, hasilnya dipakage explorer akan ada project baru yang kita buat.
super();
}
public Handphone(Integer id, String nama, String harga
) {
super();
this.id = id;
this.nama = nama;
this.harga = harga;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
Class ini berfungsi sebagai objek yang bisa mewakili isi tbl_phone
3. Selanjutnya Buat Package net.agusharyanto.hargahponline.server didalam package kita buat
class AsyncInvokeURLTask.java, fungsi utama class ini adalah untuk mengurusi komunikasi
dengan server.
package net.agusharyanto.hargahponline;
import java.util.ArrayList;
import java.util.List;
import net.agusharyanto.hargahponline.adapter.ListAdapterHandphone;
import net.agusharyanto.hargahponline.model.Handphone;
import net.agusharyanto.hargahponline.server.AsyncInvokeURLTask;
import
import
import
import
org.apache.http.NameValuePair;
org.json.JSONArray;
org.json.JSONException;
org.json.JSONObject;
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
android.app.Activity;
android.app.AlertDialog;
android.app.SearchManager;
android.content.Context;
android.content.DialogInterface;
android.content.Intent;
android.os.Bundle;
android.util.Log;
android.view.ActionMode;
android.view.Menu;
android.view.MenuItem;
android.view.View;
android.widget.AdapterView;
android.widget.AdapterView.OnItemClickListener;
android.widget.AdapterView.OnItemLongClickListener;
android.widget.ListView;
android.widget.SearchView;
android.widget.SearchView.OnQueryTextListener;
android.widget.Toast;
case R.id.action_menu_delete:
delete();
break;
}
mode.finish();
return false;
}
};
listhp = new ArrayList<Handphone>();
loadDataHP();
}
private void showUpdateForm(){
Intent in = new Intent(getApplicationContext(), FormHandphone.class);
in.putExtra("id", selectedList.getId().toString());
in.putExtra("nama", selectedList.getNama());
in.putExtra("harga", selectedList.getHarga());
startActivity(in);
}
private void delete(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Delete "+selectedList.getNama()+" ?");
builder.setTitle("Delete");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
listhp.remove(listhp.indexOf(selectedList));
Toast.makeText(getApplicationContext(), "deleted",
Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.setIcon(android.R.drawable.ic_menu_delete);
alert.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
SearchManager searchManager = (SearchManager)
getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView)
menu.findItem(R.id.option_menu_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
searchView.setOnQueryTextListener(this);
searchView.setQueryHint("nama atau nim");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.option_menu_new:
in.putExtra("id", selectedList.getId().toString());
in.putExtra("nama", selectedList.getNama());
in.putExtra("harga", selectedList.getHarga());
startActivity(in);
}
});
}
processResponse(result);
populateListView();
}
}
});
task.showdialog=true;
task.message="Load Data HP Harap Tunggu..";
task.applicationContext =MainActivity.this;
task.mNoteItWebUrl = "/select_all.php";
task.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return true;
}
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
}
3. Selanjutnya kita pindah dulu kebagian layout, buka activity_main.xml lalu ketikan kode berikut
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ListView
android:id="@+id/listview_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:dividerHeight="1dp" >
</ListView>
</RelativeLayout>
4. Buat layout baru dengan nama list_row.xml lalu ketikan kode berikut
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
>
<TextView
android:id="@+id/text_nama"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="@string/app_name"
android:typeface="sans"
android:textColor="@android:color/background_dark"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/text_harga"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/text_nama"
android:layout_alignBottom="@+id/text_nama"
android:layout_alignParentRight="true"
android:text="harga"
android:textColor="@android:color/background_dark" />
</RelativeLayout>
layout ini digunakan untuk menggambar data yang akan ditampilkan di listview
5. Buat Package net.agusharyanto.hargahponline.adapter lalu pada package tersebut buat class
ListAdapaterHandphone.java
package net.agusharyanto.hargahponline.adapter;
import java.util.ArrayList;
import java.util.List;
import
import
import
import
import
import
import
import
import
import
net.agusharyanto.hargahponline.R;
net.agusharyanto.hargahponline.model.Handphone;
android.content.Context;
android.view.LayoutInflater;
android.view.View;
android.view.ViewGroup;
android.widget.BaseAdapter;
android.widget.Filter;
android.widget.Filterable;
android.widget.TextView;
return filterd.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
LayoutInflater inflater = LayoutInflater.from(this.context);
convertView = inflater.inflate(R.layout.list_row, null);
}
Handphone hp = filterd.get(position);
TextView textNama = (TextView) convertView.findViewById(R.id.text_nama);
textNama.setText(hp.getNama());
TextView textHarga = (TextView)
convertView.findViewById(R.id.text_harga);
textHarga.setText(hp.getHarga());
return convertView;
}
@Override
public Filter getFilter() {
HandphoneFilter filter = new HandphoneFilter();
return filter;
}
/** Class filter untuk melakukan filter (pencarian) */
private class HandphoneFilter extends Filter{
@Override
protected FilterResults performFiltering(CharSequence constraint) {
List<Handphone> filteredData = new ArrayList<Handphone>();
FilterResults result = new FilterResults();
String filterString = constraint.toString().toLowerCase();
for(Handphone hp: list){
if(hp.getNama().toLowerCase().contains(filterString)){
filteredData.add(hp);
}
}
result.count = filteredData.size();
result.values = filteredData;
return result;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults
results) {
filterd = (List<Handphone>) results.values;
notifyDataSetChanged();
}
}
}
name="app_name">Harga HP Online</string>
name="option_menu_search">Search</string>
name="option_menu_new">Add New</string>
name="option_menu_save">Save</string>
name="action_menu_edit">Edit</string>
name="action_menu_delete">Delete</string>
name="cad_edit">Edit</string>
name="cad_delete">Delete</string>
name="title_activity_add_new">Form Handphone</string>
name="action_settings">Settings</string>
name="title_activity_detail_handphone">Detail Handphone</string>
</resources>
b. activity_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/option_menu_search"
android:title="@string/option_menu_search"
android:icon="@android:drawable/ic_menu_search"
android:showAsAction="ifRoom|collapseActionView"
android:actionViewClass="android.widget.SearchView"
/>
<item
android:id="@+id/option_menu_new"
android:title="@string/option_menu_new"
android:icon="@android:drawable/ic_menu_add"
android:showAsAction="ifRoom|withText"
/>
</menu>
c. form_handphone.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/option_menu_save"
android:title="@string/option_menu_save"
android:icon="@android:drawable/ic_menu_save"
android:showAsAction="ifRoom|withText"
/>
</menu>
import org.json.JSONException;
import org.json.JSONObject;
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
android.app.Activity;
android.app.AlertDialog;
android.app.SearchManager;
android.content.Context;
android.content.DialogInterface;
android.content.Intent;
android.os.Bundle;
android.util.Log;
android.view.ActionMode;
android.view.Menu;
android.view.MenuItem;
android.view.View;
android.widget.AdapterView;
android.widget.AdapterView.OnItemClickListener;
android.widget.AdapterView.OnItemLongClickListener;
android.widget.ListView;
android.widget.SearchView;
android.widget.SearchView.OnQueryTextListener;
android.widget.Toast;
showUpdateForm();
break;
case R.id.action_menu_delete:
delete();
break;
}
mode.finish();
return false;
}
};
listhp = new ArrayList<Handphone>();
loadDataHP();
}
private void showUpdateForm(){
Intent in = new Intent(getApplicationContext(), FormHandphone.class);
in.putExtra("id", selectedList.getId().toString());
in.putExtra("nama", selectedList.getNama());
in.putExtra("harga", selectedList.getHarga());
startActivity(in);
}
private void delete(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Delete "+selectedList.getNama()+" ?");
builder.setTitle("Delete");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
listhp.remove(listhp.indexOf(selectedList));
Toast.makeText(getApplicationContext(), "deleted",
Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.setIcon(android.R.drawable.ic_menu_delete);
alert.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
SearchManager searchManager = (SearchManager)
getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView)
menu.findItem(R.id.option_menu_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
searchView.setOnQueryTextListener(this);
searchView.setQueryHint("nama atau nim");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.option_menu_new:
Intent in = new Intent(getApplicationContext(), FormHandphone.class);
startActivity(in);
break;
}
return super.onOptionsItemSelected(item);
}
private void processResponse(String response){
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray jsonArray = jsonObj.getJSONArray("handphone");
Log.d(TAG, "data length: "+jsonArray.length());
Handphone handphone = null;
for(int i = 0; i < jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
handphone = new Handphone();
handphone.setId(obj.getInt("id"));
handphone.setNama(obj.getString("nama"));
handphone.setHarga(obj.getString("harga"));
this.listhp.add(handphone);
}
} catch (JSONException e) {
Log.d(TAG, e.getMessage());
}
}
private void populateListView(){
adapter = new ListAdapterHandphone(getApplicationContext(), this.listhp);
listView.setAdapter(adapter);
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View v,
int pos, long id) {
if(actionMode != null){
return false;
}
actionMode = startActionMode(amCallback);
v.setSelected(true);
selectedList = (Handphone) adapter.getItem(pos);
return true;
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View v, int
pos,
long id) {
selectedList = (Handphone) adapter.getItem(pos);
android.app.ActionBar;
android.app.Activity;
android.app.AlertDialog;
android.content.DialogInterface;
android.content.Intent;
android.os.Bundle;
android.util.Log;
android.view.Menu;
android.view.MenuItem;
android.widget.EditText;
android.widget.Toast;
}
return super.onOptionsItemSelected(item);
}
private void goToMainActivity(){
Intent in = new Intent(getApplicationContext(), MainActivity.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
}
private void delete(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Delete "+handphone.getNama()+" ?");
builder.setTitle("Delete");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
deleteData();
Toast.makeText(getApplicationContext(), "deleted",
Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.setIcon(android.R.drawable.ic_menu_delete);
alert.show();
}
task.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
}
android.app.ActionBar;
android.app.Activity;
android.content.Intent;
android.os.Bundle;
android.util.Log;
android.view.Menu;
android.view.MenuItem;
android.widget.EditText;
android.widget.Toast;
}
private void initView(){
textNama = (EditText) findViewById(R.id.add_new_nama);
textHarga = (EditText) findViewById(R.id.add_new_harga);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.form_handphone, menu);
return true;
}
private void goToMainActivity(){
Intent in = new Intent(getApplicationContext(), MainActivity.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case android.R.id.home:
goToMainActivity();
break;
case R.id.option_menu_save:
if(textHarga.getText().toString().trim().isEmpty() ||
textNama.getText().toString().trim().isEmpty()){
Toast.makeText(getApplicationContext(), "Nama dan Harga
tidak boleh kosong", Toast.LENGTH_SHORT).show();
}else{
sendData();
}
break;
}
return super.onOptionsItemSelected(item);
}
</activity>
</application>
</manifest>
Untuk menambah data bisa sentuh tombol Add pada Action Bar.
Untuk Cari data sentuh tombol search pada Action Bar.
Untuk Edit / Delete data bisa sentuh salah satu baris daftar handphone.