Anda di halaman 1dari 25

Contoh Program Android Aplikasi Wisata

Program android tentang lokasi wisata sebuah daerah sepertinya begitu populer jadi topik
skripsi :D, disini saya akan bahas bagaimana cara membuatnya. Oke pertama-tama ada beberapa
hal yang mesti anda persiapkan

1. Untuk membuat aplikasi seperti ini dibutuhkan webserver


2. Webserver digunakan untuk menyimpan database lokasi, agar bisa diakses oleh androidnya
3. Kemampuan PHP, gak usah sampe expert, tau gimana bikin CRUD udah cukup :)
4. Mengerti gimana cara koneksikan antara android dan database online menggunakan perantara
JSON

Kemudian untuk fitur2 standart aplikasi seperti ini adalah..


- menampilkan lokasinya menggunakan listview
- menampilkan lokasi tersebut pada google maps
- membuat directions menuju lokasi tersebut
- pencarian lokasi berdasar nama
- rate lokasi (advance)
- comment system (advance)

beberapa fitur diatas yang mudah dikerjakan adalah menampilkan data lokasi dalam listview,
dan menampilkan lokasi pada google maps, kemudian fungsi directions :)

Oke sekarang kita siapkan dulu databasenya, kali ini apps akan kita coba di localhost dulu,
silahkan buat database, namanya terserah anda.. kemudian buat table dengan konstruksi seperti
berikut ini

Lalu isikan beberapa data seperti berikut

Langkah selanjutnya adalah membuat folder pada htdocs berupa root untuk webservice kita,
pada contoh ini saya menggunakan nama aplikasi_wisata, dan buatlah didalmnya sebuah file
php,, berinama webservice.php
pada file php ini, yang pertama kita buat adalah modul untuk koneksi ke database,, kemudian
fungsi untuk menampilkan data lokasi wisata yang kita simpan dalam mysql dalam bentuk
JSON

berikut hasil jadi dari file phpnya..

<?php

class Database {

private $host = "localhost";

private $user = "root";

private $pass = "root";

private $db = "wisata_jogja";

private $conn;

// constructor

function __construct() {

try{

$this->conn = new PDO( "mysql:host=".$this->host.";dbname=".$this->db, $this->user, $this-


>pass );

}catch( PDOException $e ) {

echo "error pdo $e";

}
}

public function showAllData( $table ) {

$sql ="SELECT * FROM $table";

$q = $this->conn->query( $sql ) or die( "Failed !!" );

while ( $r = $q->fetch( PDO::FETCH_ASSOC ) ) {

$data[] = $r;

return $data;

$database = new Database();

$response = array();

if ( isset( $_GET['get'] ) && $_GET['get']=='lokasi' ) {

$response['location'] = array();

foreach ( $database->showAllData( 'lokasi' ) as $value ) {

$kode = array();
extract( $value );

$kode['id'] = $id;

$kode['nama'] = $nama;

$kode['alamat'] = $alamat;

$kode['lat'] = $lat;

$kode['lng'] = $lng;

$kode['gambar'] = $gambar;

array_push( $response['location'], $kode );

echo json_encode( $response );

?>
view raw webservice.php hosted with by GitHub

file php diatas koneksinya ke mysql menggunakan PDO(PHP Data Object), bagi kalian yang
masih menggunakan old style seperti mysql_ saya sarankan segera move on.. bro.. 2013 broo..
:D

Jika dijalankan pada browser maka tampilannya akan menjadi seperti ini

Webservice untuk pertukaran datanya sudah selesai, sekarang tinggal pada bagian androidnya :)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:paddingBottom="@dimen/activity_vertical_margin"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

tools:context=".MainActivity" >

<ListView

android:id="@+id/lv_lokasi"

android:layout_width="match_parent"

android:layout_height="match_parent" >

</ListView>

</RelativeLayout>
view raw activity_main.xml hosted with by GitHub

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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.example.wisatajogja"

android:versionCode="1"

android:versionName="1.0" >
<uses-sdk

android:minSdkVersion="8"

android:targetSdkVersion="18" />

<application

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/Theme.AppCompat.Light.DarkActionBar" >

<activity

android:name="com.example.wisatajogja.MainActivity"

android:label="@string/app_name" >

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

</application>

</manifest>
view raw AndroidManifest.xml hosted with by GitHub

package com.example.wisatajogja;
public class E_Lokasi

private String nama;

private String alamat;

private String gambar;

private Double lat;

private Double lng;

public String getGambar()

return gambar;

public void setGambar(String gambar)

this.gambar = gambar;

public String getNama()

return nama;

}
public void setNama(String nama)

this.nama = nama;

public String getAlamat()

return alamat;

public void setAlamat(String alamat)

this.alamat = alamat;

public Double getLat()

return lat;

public void setLat(Double lat)


{

this.lat = lat;

public Double getLng()

return lng;

public void setLng(Double lng)

this.lng = lng;

}
view raw E_Lokasi.java hosted with by GitHub

package com.example.wisatajogja;

import java.io.File;

import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;

import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import com.nostra13.universalimageloader.utils.StorageUtils;

import android.content.Context;

import android.graphics.Bitmap.CompressFormat;

public class ImageUtils

public static ImageLoaderConfiguration imgLoaderConf;

public static DisplayImageOptions imgOptions;

private static File getCacheDir(Context ctx)

return StorageUtils.getCacheDirectory(ctx);

/**

* configurasi untuk imageloader

* @param ctx

* Context

* @return imgLoaderConfiguration

*/
public static ImageLoaderConfiguration getImgConfig(Context ctx)

imgLoaderConf = new ImageLoaderConfiguration.Builder(ctx)

.discCacheExtraOptions(480, 800, CompressFormat.JPEG, 75, null)

.denyCacheImageMultipleSizesInMemory()

.memoryCache(new LruMemoryCache(2 * 1024 * 1024))

.discCache(new UnlimitedDiscCache(getCacheDir(ctx)))

.writeDebugLogs().build();

return imgLoaderConf;

/**

* image options untuk imageloader

* @return imgOptions

*/

public static DisplayImageOptions getImgOpt()

imgOptions = new DisplayImageOptions.Builder()

.showStubImage(R.drawable.ic_launcher).cacheOnDisc(true)

.cacheInMemory(true).delayBeforeLoading(10).build();

return imgOptions;
}

}
view raw ImageUtils.java hosted with by GitHub

package com.example.wisatajogja;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.UnsupportedEncodingException;

import java.util.ArrayList;

import java.util.List;

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.DefaultHttpClient;

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;
public class JSONHelper

private static final String TAG = "JSONHelper";

private InputStream is = null;

private JSONObject jsonObject = null;

private String json = "";

private static final String TAG_LOCATION = "location";

private static final String TAG_NAMA = "nama";

private static final String TAG_GAMBAR = "gambar";

private static final String TAG_ALAMAT = "alamat";

private static final String TAG_LAT = "lat";

private static final String TAG_LNG = "lng";

public JSONObject getJSONFromURL(String url)

try

DefaultHttpClient httpClient = new DefaultHttpClient();

HttpGet httpGet = new HttpGet(url);


HttpResponse httpResponse = httpClient.execute(httpGet);

HttpEntity httpEntity = httpResponse.getEntity();

is = httpEntity.getContent();

} catch (UnsupportedEncodingException e)

e.printStackTrace();

} catch (ClientProtocolException e)

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)

Utils.TRACE(TAG, "error buffered reader");

try

Utils.TRACE("jsonadapter", "hasil json ->" + json);

jsonObject = new JSONObject(json);

} catch (JSONException e)

Utils.TRACE(TAG, "Error jsonObject");

return jsonObject;
}

public List<E_Lokasi> getAllLokasi(JSONObject obj)

List<E_Lokasi> listLokasi = new ArrayList<E_Lokasi>();

try

JSONArray jsonArray = obj.getJSONArray(TAG_LOCATION);

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

JSONObject jObj = jsonArray.getJSONObject(i);

E_Lokasi lokasi = new E_Lokasi();

lokasi.setNama(jObj.getString(TAG_NAMA));

lokasi.setAlamat(jObj.getString(TAG_ALAMAT));

lokasi.setGambar(jObj.getString(TAG_GAMBAR));

lokasi.setLat(jObj.getDouble(TAG_LAT));

lokasi.setLng(jObj.getDouble(TAG_LNG));

listLokasi.add(lokasi);

}
} catch (JSONException e)

return listLokasi;

}
view raw JSONHelper.java hosted with by GitHub

package com.example.wisatajogja;

import java.util.List;

import org.json.JSONObject;

import com.nostra13.universalimageloader.core.ImageLoader;

import android.os.AsyncTask;

import android.os.Bundle;

import android.support.v7.app.ActionBarActivity;

import android.widget.ListView;

public class MainActivity extends ActionBarActivity

{
private static final String URL =
"http://10.0.2.2:8888/example/aplikasi_wisata/webservice.php?get=lokasi";

private JSONHelper json;

private ImageLoader imageLoader;

private MyAdapter adapter;

private ListView lv_lokasi;

@Override

protected void onCreate(Bundle savedInstanceState)

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

lv_lokasi = (ListView) findViewById(R.id.lv_lokasi);

imageLoader = ImageLoader.getInstance();

imageLoader.init(ImageUtils.getImgConfig(this));

json = new JSONHelper();

new AsyncData().execute(URL);

}
private class AsyncData extends AsyncTask<String, Void, List<E_Lokasi>>

@Override

protected List<E_Lokasi> doInBackground(String... params)

JSONObject obj = json.getJSONFromURL(params[0]);

return json.getAllLokasi(obj);

@Override

protected void onPostExecute(List<E_Lokasi> result)

super.onPostExecute(result);

adapter = new MyAdapter(MainActivity.this, result, imageLoader);

lv_lokasi.setAdapter(adapter);

@Override

protected void onPreExecute()

{
// TODO Auto-generated method stub

super.onPreExecute();

}
view raw MainActivity.java hosted with by GitHub

package com.example.wisatajogja;

import java.util.List;

import com.nostra13.universalimageloader.core.ImageLoader;

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;

public class MyAdapter extends BaseAdapter

{
static class Holder

TextView title, detail;

ImageView thumb;

private List<E_Lokasi> listLokasi;

private LayoutInflater inflater;

private ImageLoader imageLoader;

public MyAdapter(Context context, List<E_Lokasi> listLokasi,

ImageLoader imageLoader)

this.listLokasi = listLokasi;

this.imageLoader = imageLoader;

inflater = LayoutInflater.from(context);

@Override

public int getCount()

{
// TODO Auto-generated method stub

return listLokasi.size();

@Override

public Object getItem(int position)

// TODO Auto-generated method stub

return listLokasi.get(position);

@Override

public long getItemId(int position)

// TODO Auto-generated method stub

return 0;

@Override

public View getView(int position, View convertView, ViewGroup parent)

Holder holder;

if (convertView == null)
{

convertView = inflater.inflate(R.layout.single_row, null);

holder = new Holder();

holder.title = (TextView) convertView.findViewById(R.id.titleRow);

holder.detail = (TextView) convertView.findViewById(R.id.detailRow);

holder.thumb = (ImageView) convertView.findViewById(R.id.thumbRow);

convertView.setTag(holder);

} else

holder = (Holder) convertView.getTag();

holder.title.setText(listLokasi.get(position).getNama());

holder.detail.setText(listLokasi.get(position).getAlamat());

imageLoader.displayImage(listLokasi.get(position).getGambar(),

holder.thumb, ImageUtils.getImgOpt());

return convertView;

}
}
view raw MyAdapter.java hosted with by GitHub

<?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" >

<ImageView

android:id="@+id/thumbRow"

android:layout_width="40dp"

android:layout_height="40dp"

android:layout_alignParentTop="true" />

<TextView

android:id="@+id/titleRow"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_toRightOf="@id/thumbRow" />

<TextView

android:id="@+id/detailRow"

android:layout_width="wrap_content"

android:layout_height="wrap_content"
android:layout_below="@id/titleRow"

android:layout_toRightOf="@id/thumbRow" />

</RelativeLayout>
view raw single_row.xml hosted with by GitHub

package com.example.wisatajogja;

import android.util.Log;

public class Utils

public static void TRACE(String tag, String msg)

if (BuildConfig.DEBUG)

Log.d(tag, msg);

}
view raw Utils.java hosted with by GitHub

pada project ini saya menggunakan 2 buah library..

1. ActionBarCompat link

2. Universal Image Loader link