LAMPIRAN A : LISTING PROGRAM
MainProgram.java
package com.rs.input;
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream;
import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL;
import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List;
import org.json.JSONObject; import org.w3c.dom.Document;
import android.app.AlertDialog; import android.content.Context;
import android.content.DialogInterface; import android.content.Intent;
import android.database.Cursor; import android.graphics.Color; import android.location.Address; import android.location.Geocoder; import android.location.Location;
import android.location.LocationListener; import android.net.Uri;
import android.os.AsyncTask; import android.os.Bundle;
import android.support.v4.app.FragmentActivity; import android.util.Log;
import android.view.LayoutInflater; import android.view.Menu;
import android.view.MenuItem; import android.view.View;
import android.view.View.OnClickListener; import android.view.animation.Animation; import android.widget.Button;
import android.widget.EditText; import android.widget.TextView; import android.widget.Toast;
import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener; import
com.google.android.gms.maps.GoogleMap.OnMyLocationChangeListener; import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.rs.R;
public class MainProgram extends FragmentActivity implements
LocationListener, OnMyLocationChangeListener,OnMapLongClickListener{ private RS_DBAdapter db;
GetMapData getmap;
private GoogleMap myMapView;
public static final int ADDRESS_GOT = 0;
public static final int UNSURE_POINT_TIMER = 1;
public static final int CANCEL_UNSURE_POINT_TIMER = 2; public static final int UNSURE_BALLOON_TAP = 3;
public static final int GREEN_BALLOON_TAP = 4;
public static final int GMAP_MODIFICATION_FINISH = 5; public static final int GMAP_GEOCODING_FINISH = 6; public static final int GMAP_ADD_POINT_FAIL = 7; public static final int RED_BALLOON_TAP = 8; public static final int JSON_GOT = 9;
public static final int DOUBLE_CLICK_ZOOM_IN = 10; public static final int GMAP_CHANGE_START_FAIL = 11; public static final int GMAP_OVER_QUERY_LIMIT = 12;
private static final int MENU_SEARCH = 0; private static final int MENU_CLEAR = 3; private static final int MENU_REFRESH = 4;
private static final int DIALOG_PLEASE_SET_START_POINT = 6; Marker MyLocation;
boolean update_location; float zoom;
LatLng[] LATLON; String[] NameRS; String[] AddresRS; String[] PhoneRS; Marker[] marker; Cursor record =null; int index;
int NumRow; LatLng MYPOS;
boolean run_process; int[] PATHID;
double[] OPTIMZATION; int[] RANGK;
LatLng DESTINATION; TextView Result=null; Button detail;
Document document;
GMapV2GetRouteDirection v2GetRouteDirection; boolean wide;
DirectionsJSONParser parser=null; String address_name=null;
String loc_name=null; String loc_phone; LatLng LL;
private RS_DBAdapter myDbHelper;
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.input);
int status =
GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext() );
db=new RS_DBAdapter(this); db.open();
record=db.fetchAllRecords(); index=record.getCount(); getmap=new GetMapData(); findViews();
myDbHelper = new RS_DBAdapter(this); try{
myDbHelper.open(); }catch (Exception e){ }
}
@Override
protected void onResume() { super.onResume();
}
protected void onClose(){ record.close();
}
private void reset_map(){ if(index>0){
while(record.moveToNext()){
myMapView.addMarker(new MarkerOptions() .position(new
LatLng((record.getDouble(record.getColumnIndex(RS_DBAdapter.KEY_LATIT UDE))),
(record.getDouble(record.getColumnIndex(RS_DBAdapter.KEY_LONGITUDE))) ))
.snippet(record.getString(record.getColumnIndex(RS_DBAdapter.KEY_ADDR ESS)))
.title(record.getString(record.getColumnIndex(RS_DBAdapter.KEY_NAME)) ).icon(BitmapDescriptorFactory.fromResource(R.drawable.pink)));
myMapView.moveCamera(CameraUpdateFactory.newLatLngZoom(new
LatLng((record.getDouble(record.getColumnIndex(RS_DBAdapter.KEY_LATIT UDE))),
(record.getDouble(record.getColumnIndex(RS_DBAdapter.KEY_LONGITUDE))) ), 12));
LatLng point=new
LatLng((record.getDouble(record.getColumnIndex(RS_DBAdapter.KEY_LATIT UDE))),
(record.getDouble(record.getColumnIndex(RS_DBAdapter.KEY_LONGITUDE))) );
NumRow++; }
record.close(); }
}
private void findViews() {
myMapView = ((SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.mapview)).getMap(); myMapView.setMapType(GoogleMap.MAP_TYPE_NORMAL);
myMapView.setMyLocationEnabled(true); myMapView.setOnMapLongClickListener(this); myMapView.isTrafficEnabled();
OPTIMZATION=new double[index]; RANGK=new int[index];
LATLON=new LatLng[index];
Result=(TextView)findViewById(R.id.direction); Result.setVerticalScrollBarEnabled(true);
Result.setOnClickListener(new OnClickListener(){ @Override
public void onClick(View arg0) { if(!wide){
wide=true; }else{ wide=false; }
} });
detail=(Button)findViewById(R.id.detail); detail.setEnabled(false);
detail.setOnClickListener(new OnClickListener(){ @Override
public void onClick(View view) {
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?saddr="+MYPOS.latitude+","+MYP OS.longitude+"&daddr="+DESTINATION.latitude+","+DESTINATION.longitude ));
startActivity(intent); }
});
if(index>0){
while(record.moveToNext()){
myMapView.addMarker(new MarkerOptions() .position(new
LatLng((record.getDouble(record.getColumnIndex(RS_DBAdapter.KEY_LATIT UDE))),
(record.getDouble(record.getColumnIndex(RS_DBAdapter.KEY_LONGITUDE))) ))
.snippet(record.getString(record.getColumnIndex(RS_DBAdapter.KEY_ADDR ESS)))
.title(record.getString(record.getColumnIndex(RS_DBAdapter.KEY_NAME)) ).icon(BitmapDescriptorFactory.fromResource(R.drawable.pink)));
myMapView.moveCamera(CameraUpdateFactory.newLatLngZoom(new
LatLng((record.getDouble(record.getColumnIndex(RS_DBAdapter.KEY_LATIT UDE))),
(record.getDouble(record.getColumnIndex(RS_DBAdapter.KEY_LONGITUDE))) ), 12));
LatLng point=new
LatLng((record.getDouble(record.getColumnIndex(RS_DBAdapter.KEY_LATIT UDE))),
(record.getDouble(record.getColumnIndex(RS_DBAdapter.KEY_LONGITUDE))) );
PATHID[NumRow]=record.getInt(record.getColumnIndex(RS_DBAdapter.KEY_R OWID));
LATLON[NumRow]=new
LatLng((record.getDouble(record.getColumnIndex(RS_DBAdapter.KEY_LATIT UDE))),
(record.getDouble(record.getColumnIndex(RS_DBAdapter.KEY_LONGITUDE))) );
record.close(); }
myMapView.setOnMyLocationChangeListener(this); }
@Override
public void onMyLocationChange(Location location) { double latitude = location.getLatitude();
double longitude = location.getLongitude(); LatLng latLng = new LatLng(latitude, longitude); MYPOS=new LatLng(latitude, longitude);
if(!run_process){
zoom=myMapView.getCameraPosition().zoom; if(update_location)MyLocation.remove();
MyLocation = myMapView.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("Lokasi
saya").icon(BitmapDescriptorFactory.fromResource(R.drawable.mark_gree n)));
myMapView.animateCamera(CameraUpdateFactory.zoomTo(zoom), 2000,
null);
update_location=true; }
}
@Override
protected void onDestroy() { super.onDestroy();
}
private void CalCulatePath(){ Result.setText("");
record=db.fetchAllRecords(); int x=0;
while(record.moveToNext()){ LatLng ENDPATH=new
LatLng((record.getDouble(record.getColumnIndex(RS_DBAdapter.KEY_LATIT UDE))),
(record.getDouble(record.getColumnIndex(RS_DBAdapter.KEY_LONGITUDE))) );
OPTIMZATION[x]=CalculationByDistance(MYPOS,ENDPATH); x++;
}
record.close(); CalShortestPath(); }
private void CalShortestPath(){
double minimum = Doubles.min(OPTIMZATION); for (int i = 0; i < OPTIMZATION.length; i++) {
if (minimum== OPTIMZATION[i]) {
DESTINATION=LATLON[i]; }
}
String url = getDirectionsUrl(MYPOS, DESTINATION); DownloadTask downloadTask = new DownloadTask(); downloadTask.execute(url);
}
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null; try{
URL url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.connect();
iStream = urlConnection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer(); String line = "";
while( ( line = br.readLine()) != null){ sb.append(line);
}
data = sb.toString(); br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString()); }finally{
iStream.close();
urlConnection.disconnect(); }
return data; }
private class DownloadTask extends AsyncTask<String, Void, String>{ @Override
protected String doInBackground(String... url) { String data = "";
try{
data = downloadUrl(url[0]); }catch(Exception e){
Log.d("Background Task",e.toString()); }
return data; }
@Override
protected void onPostExecute(String result) { super.onPostExecute(result);
ParserTask parserTask = new ParserTask(); parserTask.execute(result);
} }
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{
@Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null; try{
jObject = new JSONObject(jsonData[0]); parser = new DirectionsJSONParser(); routes = parser.parse(jObject); }catch(Exception e){
e.printStackTrace(); }
}
@Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null; PolylineOptions lineOptions = null; String distance = "";
String duration = ""; for(int i=0;i<result.size();i++){ points = new ArrayList<LatLng>(); lineOptions = new PolylineOptions();
List<HashMap<String, String>> path = result.get(i); for(int j=0;j<path.size();j++){
HashMap<String,String> point = path.get(j); if(j==0){
distance = (String)point.get("distance"); continue;
}else if(j==1){
duration = (String)point.get("duration"); continue;
}
double lat = Double.parseDouble(point.get("lat")); double lng = Double.parseDouble(point.get("lng")); LatLng position = new LatLng(lat, lng);
points.add(position); }
lineOptions.addAll(points); lineOptions.width(2);
lineOptions.color(Color.MAGENTA); }
Result.setText("");
Result.setText("Jarak total : "+distance+"\n");
List<List<HashMap<String, String>>> DATA = parser.GETALLDATA(); int u=DATA.size();
int y=0;
for(int i=0;i<u;i++){ y=DATA.get(i).size(); for(int h=0;h<y;h++){
if(DATA.get(i).get(h).get("html_instructions")!=null){
Result.append(DATA.get(i).get(h).get("html_instructions")+"->"); }
if(DATA.get(i).get(h).get("jarak")!=null){
Result.append(DATA.get(i).get(h).get("jarak")+"\n"); }
} }
myMapView.addPolyline(lineOptions); }
}
private String getDirectionsUrl(LatLng origin,LatLng dest){
String str_origin = "origin="+origin.latitude+","+origin.longitude; String str_dest = "destination="+dest.latitude+","+dest.longitude; String sensor = "sensor=false";
String parameters =
str_origin+"&"+str_dest+"&"+sensor+"&"+"mode=driving"; String output = "json";
String url =
return url; }
public double CalculationByDistance(LatLng StartP, LatLng EndP) { int Radius=6371;
double lat1 = StartP.latitude; double lat2 = EndP.latitude; double lon1 = StartP.longitude; double lon2 = EndP.longitude;
double dLat = Math.toRadians(lat2-lat1); double dLon = Math.toRadians(lon2-lon1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.sin(dLon/2) * Math.sin(dLon/2);
double c = 2 * Math.asin(Math.sqrt(a)); double valueResult= Radius*c;
double km=valueResult/1;
DecimalFormat newFormat = new DecimalFormat("####"); int kmInDec = Integer.valueOf(newFormat.format(km)); double meter=valueResult%1000;
int meterInDec= Integer.valueOf(newFormat.format(meter)); Log.i("Radius Value",""+valueResult+" KM "+kmInDec+" Meter "+meterInDec);
return valueResult; }
@Override
public void onLocationChanged(Location location) {} @Override
public void onProviderDisabled(String provider) {} @Override
public void onProviderEnabled(String provider) {} @Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
@Override
public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, MENU_SEARCH, 0, "Start
pencarian...").setIcon(android.R.drawable.ic_menu_search); menu.add(0, MENU_CLEAR, 0,
R.string.menu_clear).setIcon(android.R.drawable.ic_menu_revert); menu.add(0, MENU_REFRESH, 0, "Center
lokasi...").setIcon(android.R.drawable.ic_menu_directions); return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == MENU_SEARCH) {
run_process=true; CalCulatePath(); run_process=false; return true;
}else if(item.getItemId() == MENU_CLEAR){ Result.setText("");
myMapView.clear();
record=db.fetchAllRecords(); index=record.getCount(); reset_map();
}else if(item.getItemId() == MENU_REFRESH){
}
return false; }
@Override
public void onMapLongClick(LatLng latLng) { this.LL=latLng;
myMapView.animateCamera(CameraUpdateFactory.newLatLng(latLng new ReverseGeocodingTask(getBaseContext()).execute(latLng); }
private class ReverseGeocodingTask extends AsyncTask<LatLng, Void, String> {
Context mContext;
AlertDialog.Builder alertDialogBuilder=new AlertDialog.Builder(MainProgram.this);
LayoutInflater factory = LayoutInflater.from(MainProgram.this); final View view = factory.inflate(R.layout.dialog, null);
EditText namers=(EditText) view.findViewById(R.id.nama); EditText addressrs=(EditText) view.findViewById(R.id.alamat); EditText teleponrs=(EditText) view.findViewById(R.id.telepon); EditText latrs=(EditText) view.findViewById(R.id.longitude); EditText lonrs=(EditText) view.findViewById(R.id.latitude); public ReverseGeocodingTask(Context context) {
super();
mContext = context; }
@Override
protected String doInBackground(LatLng... params) { Geocoder geocoder = new Geocoder(mContext);
double latitude = params[0].latitude; double longitude = params[0].longitude; List<Address> addresses = null;
String addressText = ""; try {
addresses = geocoder.getFromLocation(latitude, longitude, 1); if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0); address_name="";
loc_name=""; loc_phone="";
addressText = String.format("%s, %s,
%s",address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getLocality(),address.getCountryName()); address_name=address.getAddressLine(0);
loc_name=address.getAdminArea(); loc_phone=address.getPhone(); }
} catch (IOException e) { e.printStackTrace();
System.out.print("Error get address!...."); }
return addressText; }
@Override
latrs.setText(String.valueOf(LL.latitude)); lonrs.setText(String.valueOf(LL.longitude)); alertDialogBuilder.setIcon(R.drawable.rsu48);
alertDialogBuilder.setTitle("Tambah data rumah sakit"); alertDialogBuilder.setCancelable(false)
.setView(view)
.setPositiveButton("Simpan",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) {
myMapView.addMarker(new MarkerOptions().position(new
LatLng(LL.latitude,LL.longitude)).snippet(selectedLocAddress)
.title(namers.getText().toString()).icon(BitmapDescriptorFactory.from Resource(R.drawable.pink)));
if(namers.getText().toString().equals("")){
Toast.makeText(mContext, "Nama rumah sakit kosong!...", Toast.LENGTH_SHORT).show();
}else if(addressrs.getText().toString().equals("")){ Toast.makeText(mContext, "Alamat kosong!...",
Toast.LENGTH_SHORT).show();
}else if(teleponrs.getText().toString().equals("")){ Toast.makeText(mContext, "Telepon kosong!...",
Toast.LENGTH_SHORT).show();
}else if(latrs.getText().toString().equals("")){ Toast.makeText(mContext, "Latitude kosong!...", Toast.LENGTH_SHORT).show();
}else if(lonrs.getText().toString().equals("")){ Toast.makeText(mContext, "Longitude kosong!...", Toast.LENGTH_SHORT).show();
}else{
long RowId=myDbHelper.createRecord(namers.getText().toString(),
addressrs.getText().toString(), teleponrs.getText().toString(), null, 0, String.valueOf(LL.latitude), String.valueOf(LL.longitude),null); alertDialogBuilder.setIcon(R.drawable.rsu48);
if(RowId>0)Toast.makeText(mContext, "Simpan sukses!...", Toast.LENGTH_SHORT).show();
} } })
.setNegativeButton("Batal",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) {
dialog.cancel(); }
});
AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show();
} } }
RS_DBAdapter.java
package com.rs.input;
import android.content.ContentValues; import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
public class RS_DBAdapter {
public static final String KEY_NAME = "name";
public static final String KEY_ADDRESS = "address"; public static final String KEY_PHONE = "phone"; public static final String KEY_NOTE = "note"; public static final String KEY_RATING = "rating"; public static final String KEY_LATITUDE = "latitude"; public static final String KEY_LONGITUDE = "longitude"; public static final String KEY_ROWID = "_id";
public static final String KEY_IMAGE="image"; private static final String TAG = "RSDBAdapter"; private DatabaseHelper myDbHelper;
SQLiteDatabase mDb;
private static final String DATABASE_CREATE = "create table records (_id integer primary key autoincrement, "
+ "name text, address text, phone text, " + "note text, rating float, "
+ "latitude text, longitude text,image BLOB);";
private static final String DATABASE_CREATE_NODE = "create table node (id_node integer primary key autoincrement, "+ "name text,latitude text, longitude text);";
private static final String DATABASE_CREATE_POINT = "create table point (id_point integer primary key autoincrement, "+ "name text, id_node integer,latitude text, longitude text);";
private static final String DATABASE_NAME = "rs";
private static final String DATABASE_TABLE = "records"; private static final String DATABASE_TABLE_NODE = "node"; private static final String DATABASE_TABLE_POINT = "point"; private static final int DATABASE_VERSION = 2;
private final Context myContext;
private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION); }
@Override
public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE);
db.execSQL(DATABASE_CREATE_NODE); db.execSQL(DATABASE_CREATE_POINT); insert(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS records"); onCreate(db);
} }
public RS_DBAdapter(Context context) { this.myContext = context;
}
public static void insert(SQLiteDatabase db) { String sql="";
sql="insert into
('1','Yos Sudarso, No. 91 KM 6','+62 61 6610910','1','Rumah Sakit (RS) Martha Friska','3.688855','98.665352','')";db.execSQL(sql); sql="insert into
records(_id,address,phone,rating,name,latitude,longitude,image)values ('2','Kapten Muslim, No. 79','+62 61845181','1','Rumah Sakit Umum (RSU) Sari Mutiara','3.603005','98.644992','')";db.execSQL(sql); sql="insert into
records(_id,address,phone,rating,name,latitude,longitude,image)values ('3','Jend Gatot Subroto KM. 4 20119','+62 61 4524875','1','Rumah Sakit Advent','3.593775','98.65016','')";db.execSQL(sql);
sql="insert into
records(_id,address,phone,rating,name,latitude,longitude,image)values ('4','Jl. HM Joni No.64','061 7366588','1','Bhakti
RS','3.569019','98.697703','')";db.execSQL(sql); sql="insert into
records(_id,address,phone,rating,name,latitude,longitude,image)values ('5','Jl. Sumatera Simpang Kantor No.6','061 6851396','1','Bina Sejahtera RS','3.569019','98.697703','')";db.execSQL(sql); sql="insert into
records(_id,address,phone,rating,name,latitude,longitude,image)values ('6','Jl. Syahbandar No. 5 - 7','061 535096','1','Chandra,
RSB','3.581317','98.682967','')";db.execSQL(sql); sql="insert into
records(_id,address,phone,rating,name,latitude,longitude,image)values ('7','Jl. Surakarta 2','061 574279','1','Dewi Maya,
RS','3.586296','98.685719','')";db.execSQL(sql); sql="insert into
records(_id,address,phone,rating,name,latitude,longitude,image)values ('8','PTP Nusantara II, Tanjung Merawa','(061)940055','1','Dr. GL Tobing, RS','3.524025','98.784661','')";db.execSQL(sql);
sql="insert into
records(_id,address,phone,rating,name,latitude,longitude,image)values ('9','Jl. Mojopahit No. 118 A','061 4510766','1','Herna,
RS','3.579489','98.666257','')";db.execSQL(sql); sql="insert into
records(_id,address,phone,rating,name,latitude,longitude,image)values ('10','Jl. Bilai No. 24 (d/h 103), Pulo Brayan Darat','061
6610072','1','Imelda Pekerja Indonesia,
RSU','3.623074','98.674897','')";db.execSQL(sql); sql="insert into
records(_id,address,phone,rating,name,latitude,longitude,image)values ('11','Jl. Timor No. 27 D','(061) 4560039','1','Melati ,
RSU','3.595968','98.68084','')";db.execSQL(sql); sql="insert into
records(_id,address,phone,rating,name,latitude,longitude,image)values ('12','Jl. W. Monginsidi No. 11','061 4512687','1','Monginsidi, RSU','3.571064','98.668674','')";db.execSQL(sql);
sql="insert into
records(_id,address,phone,rating,name,latitude,longitude,image)values ('13','Jl. Baja Raya No. 10','061 528744','1','Sarah Medan,
RSU','3.587568','98.663918','')";db.execSQL(sql); sql="insert into
records(_id,address,phone,rating,name,latitude,longitude,image)values ('14','JL. Djamin Ginting, No. 2','061 821387','1','Siti Hajar, RSU','3.571444','98.660445','')";db.execSQL(sql);
sql="insert into
records(_id,address,phone,rating,name,latitude,longitude,image)values ('15','Jl. Bahagia No.85','(061) 7360947','1','Bahagia,
sql="insert into
records(_id,address,phone,rating,name,latitude,longitude,image)values ('16','Jl. KH Wahid Hasyim 1','061 8215990','1','Bhayangkara,
RS','3.572617','98.658503','')";db.execSQL(sql); sql="insert into
records(_id,address,phone,rating,name,latitude,longitude,image)values ('17','Jl. Let. Jend. Simatupang No. 148','061 8475111','1','Bina Kasih, RSU','3.578576','98.612884','')";db.execSQL(sql);
sql="insert into
records(_id,address,phone,rating,name,latitude,longitude,image)values ('18','Jl. Djamin Ginting KM 9,8 No.166','(061) 830442','1','Bina Persada, RSU','3.546173','98.658337','')";db.execSQL(sql);
sql="insert into
records(_id,address,phone,rating,name,latitude,longitude,image)values ('19','Jl. Sei Batanghari 28-30, Babura','061 4553918','1','Bunda Thamrin, RS','3.585014','98.651376','')";db.execSQL(sql);
}
public RS_DBAdapter open() throws SQLException { myDbHelper = new DatabaseHelper(myContext); mDb = myDbHelper.getWritableDatabase(); return this;
}
public void close() { myDbHelper.close(); }
public long createRecord(String name, String address, String phone, String note, float rating, String latitude, String longitude,byte[] image) {
ContentValues initialValues = new ContentValues(); initialValues.put(KEY_NAME, name);
initialValues.put(KEY_ADDRESS, address); initialValues.put(KEY_PHONE, phone); initialValues.put(KEY_NOTE, note); initialValues.put(KEY_RATING, rating); initialValues.put(KEY_LATITUDE, latitude); initialValues.put(KEY_LONGITUDE, longitude); initialValues.put(KEY_IMAGE, image);
return mDb.insert(DATABASE_TABLE, null, initialValues); }
public boolean deleteRecord(long rowId) {
return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0; }
public Cursor fetchAllRecords() {
return mDb.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_NAME, KEY_ADDRESS, KEY_PHONE, KEY_NOTE, KEY_RATING, KEY_LATITUDE,
KEY_LONGITUDE,KEY_IMAGE }, null, null, null, null, null); }
public Cursor fetchRecord(long rowId) throws SQLException { Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[] { KEY_ROWID, KEY_NAME, KEY_ADDRESS, KEY_PHONE, KEY_NOTE,
KEY_RATING, KEY_LATITUDE, KEY_LONGITUDE,KEY_IMAGE }, KEY_ROWID + "=" + rowId, null, null, null, null, null);
if (mCursor != null) { mCursor.moveToFirst(); }
return mCursor; }
String longitude,byte[] image) {
ContentValues args = new ContentValues(); args.put(KEY_NAME, name);
args.put(KEY_ADDRESS, address); args.put(KEY_PHONE, phone); args.put(KEY_NOTE, note); args.put(KEY_RATING, rating); args.put(KEY_LATITUDE, latitude); args.put(KEY_LONGITUDE, longitude); args.put(KEY_IMAGE, image);
return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
public long createRecordNode(String name, String latitude, String longitude) {
ContentValues initialValues = new ContentValues(); initialValues.put(KEY_NAME, name);
initialValues.put(KEY_LATITUDE, latitude); initialValues.put(KEY_LONGITUDE, longitude);
return mDb.insert(DATABASE_TABLE_NODE, null, initialValues); }
public boolean updateRecordNode(Long mRowId, String name, String latitude,
String longitude) {
ContentValues args = new ContentValues(); args.put(KEY_NAME, name);
args.put(KEY_LATITUDE, latitude); args.put(KEY_LONGITUDE, longitude);
return mDb.update(DATABASE_TABLE_NODE, args, KEY_ROWID + "=" + mRowId, null) > 0;
} }
RsLauncher.java
package com.rs.input;
import android.app.Activity; import android.content.Intent; import android.os.Bundle;
public class RsLauncher extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
Intent intent = new Intent(this, MainProgram.class); startActivity(intent);
finish(); }
}
DirectionsJSONParser.java
package com.rs.input;
import org.json.JSONException; import org.json.JSONObject; import android.util.Log;
import com.google.android.gms.maps.model.LatLng;
public class DirectionsJSONParser {
List HTMLINST = new ArrayList<HashMap<String, String>>(); List<List<HashMap<String, String>>> DATA = new
ArrayList<List<HashMap<String,String>>>() ;
public List<List<HashMap<String,String>>> parse(JSONObject jObject){ List<List<HashMap<String, String>>> routes = new
ArrayList<List<HashMap<String,String>>>() ; JSONArray jRoutes = null;
JSONArray jLegs = null; JSONArray jSteps = null; JSONObject jDistance = null; JSONObject jDuration = null;
List<List<HashMap<String, String>>> DATA_T= new ArrayList<List<HashMap<String,String>>>() ; try {
jRoutes = jObject.getJSONArray("routes"); String formatted_address = "-NA-"; for(int i=0;i<jRoutes.length();i++){
jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs"); List path = new ArrayList<HashMap<String, String>>();
for(int j=0;j<jLegs.length();j++){
jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance"); HashMap<String, String> hmDistance = new HashMap<String, String>(); hmDistance.put("distance", jDistance.getString("text"));
jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration"); HashMap<String, String> hmDuration = new HashMap<String, String>();
hmDuration.put("duration", jDuration.getString("text")); path.add(hmDistance);
path.add(hmDuration);
jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
for(int k=0;k<jSteps.length();k++){
final JSONObject step = jSteps.getJSONObject(k); final JSONObject stepless =
((JSONObject)((JSONObject)jSteps.get(k))).getJSONObject("distance"); String polyline = "";
polyline =
(String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get ("points");
List<LatLng> list = decodePoly(polyline);
HashMap<String, String> html = new HashMap<String, String>(); HashMap<String, String> jarak = new HashMap<String, String>();
html.put("html_instructions",step.getString("html_instructions").repl aceAll("<(.*?)*>", ""));
jarak.put("jarak",stepless.getString("text")); for(int l=0;l<list.size();l++){
HashMap<String, String> hm = new HashMap<String, String>(); hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) ); hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) ); path.add(hm);
} HTMLINST.add(html);
Log.i("Jarak:",""+ jarak.get("jarak")); }
routes.add(path); DATA_T.add(HTMLINST); SET_DATA(DATA_T); }
}
} catch (JSONException e) { e.printStackTrace();
}catch (Exception e){ }
return routes; }
private void SET_DATA(List<List<HashMap<String, String>>> dATA_T) { this.DATA=dATA_T;
}
public List<List<HashMap<String, String>>> GETALLDATA(){ return DATA;
}
private List<LatLng> decodePoly(String encoded) { List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length(); int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0; do {
b = encoded.charAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5;//5
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lat += dlat;
shift = 0; result = 0; do {
b = encoded.charAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)), (((double) lng / 1E5)));
poly.add(p); }
return poly; }
}
GetMapData.java
package com.rs.input;
import java.io.IOException; import java.util.List; import java.util.Locale;
public class GetMapData {
public String getPhone(Double lat, Double lng){ String phone = null;
return phone; }
public String getAddress(Double lat, Double lng) {
String sb=null; try
{
Geocoder geocoder = new Geocoder(null, Locale.getDefault()); List<Address> addresses = geocoder.getFromLocation(lat, lng, 1); if (addresses.size() > 0)
{
Address address = addresses.get(0); }
String addressString = sb; return addressString; }
catch (IOException e) {
return "..."; }
} }
GMapV2GetRouteDirection.java
package com.rs.input;
import java.io.InputStream; import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.w3c.dom.Document;
import org.w3c.dom.Node; import org.w3c.dom.NodeList;
import com.google.android.gms.maps.model.LatLng; import android.util.Log;
public class GMapV2GetRouteDirection {
public final static String MODE_DRIVING = "driving"; public final static String MODE_WALKING = "walking"; public GMapV2GetRouteDirection() { }
public Document getDocument(LatLng start, LatLng end, String mode) { String url = "http://maps.googleapis.com/maps/api/directions/xml?" + "origin=" + start.latitude + "," + start.longitude
+ "&destination=" + end.latitude + "," + end.longitude + "&sensor=false&units=metric&mode=driving";
try {
HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpPost httpPost = new HttpPost(url);
InputStream in = response.getEntity().getContent(); DocumentBuilder builder =
DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(in);
return doc;
} catch (Exception e) { e.printStackTrace(); }
return null; }
public String getDurationText (Document doc) {
NodeList nl1 = doc.getElementsByTagName("duration"); Node node1 = nl1.item(0);
NodeList nl2 = node1.getChildNodes();
Node node2 = nl2.item(getNodeIndex(nl2, "text")); Log.i("DurationText", node2.getTextContent()); return node2.getTextContent();
}
public int getDurationValue (Document doc) {
NodeList nl1 = doc.getElementsByTagName("duration"); Node node1 = nl1.item(0);
NodeList nl2 = node1.getChildNodes();
Node node2 = nl2.item(getNodeIndex(nl2, "value")); Log.i("DurationValue", node2.getTextContent()); return Integer.parseInt(node2.getTextContent()); }
public String getDistanceText (Document doc) {
NodeList nl1 = doc.getElementsByTagName("distance"); Node node1 = nl1.item(0);
NodeList nl2 = node1.getChildNodes();
Node node2 = nl2.item(getNodeIndex(nl2, "text")); Log.i("DistanceText", node2.getTextContent()); return node2.getTextContent();
}
public int getDistanceValue (Document doc) {
NodeList nl1 = doc.getElementsByTagName("distance"); Node node1 = nl1.item(0);
NodeList nl2 = node1.getChildNodes();
Node node2 = nl2.item(getNodeIndex(nl2, "value")); Log.i("DistanceValue", node2.getTextContent()); return Integer.parseInt(node2.getTextContent()); }
public String getStartAddress (Document doc) {
NodeList nl1 = doc.getElementsByTagName("start_address"); Node node1 = nl1.item(0);
Log.i("StartAddress", node1.getTextContent()); return node1.getTextContent();
}
public String getEndAddress (Document doc) {
NodeList nl1 = doc.getElementsByTagName("end_address"); Node node1 = nl1.item(0);
Log.i("StartAddress", node1.getTextContent()); return node1.getTextContent();
}
public String getCopyRights (Document doc) {
NodeList nl1 = doc.getElementsByTagName("copyrights"); Node node1 = nl1.item(0);
Log.i("CopyRights", node1.getTextContent()); return node1.getTextContent();
public ArrayList<LatLng> getDirection (Document doc) { NodeList nl1, nl2, nl3;
ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>(); nl1 = doc.getElementsByTagName("step");
if (nl1.getLength() > 0) {
for (int i = 0; i < nl1.getLength(); i++) { Node node1 = nl1.item(i);
nl2 = node1.getChildNodes();
Node locationNode = nl2.item(getNodeIndex(nl2, "start_location")); nl3 = locationNode.getChildNodes();
Node latNode = nl3.item(getNodeIndex(nl3, "lat"));
double lat = Double.parseDouble(latNode.getTextContent()); Node lngNode = nl3.item(getNodeIndex(nl3, "lng"));
double lng = Double.parseDouble(lngNode.getTextContent()); listGeopoints.add(new LatLng(lat, lng));
locationNode = nl2.item(getNodeIndex(nl2, "polyline")); nl3 = locationNode.getChildNodes();
latNode = nl3.item(getNodeIndex(nl3, "points"));
ArrayList<LatLng> arr = decodePoly(latNode.getTextContent()); for(int j = 0 ; j < arr.size() ; j++) {
listGeopoints.add(new LatLng(arr.get(j).latitude, arr.get(j).longitude));
}
locationNode = nl2.item(getNodeIndex(nl2, "end_location")); nl3 = locationNode.getChildNodes();
latNode = nl3.item(getNodeIndex(nl3, "lat"));
lat = Double.parseDouble(latNode.getTextContent()); lngNode = nl3.item(getNodeIndex(nl3, "lng"));
lng = Double.parseDouble(lngNode.getTextContent()); listGeopoints.add(new LatLng(lat, lng));
} }
return listGeopoints; }
private int getNodeIndex(NodeList nl, String nodename) { for(int i = 0 ; i < nl.getLength() ; i++) {
if(nl.item(i).getNodeName().equals(nodename)) return i;
}
return -1; }
private ArrayList<LatLng> decodePoly(String encoded) { ArrayList<LatLng> poly = new ArrayList<LatLng>(); int index = 0, len = encoded.length();
int lat = 0, lng = 0; while (index < len) {
int b, shift = 0, result = 0; do {
b = encoded.charAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lat += dlat;
shift = 0; result = 0; do {
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lng += dlng;
LatLng position = new LatLng((double) lat / 1E5, (double) lng / 1E5); poly.add(position);
}
return poly; }
}
About.java
package com.rs;
import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView;
public class About extends Activity { ImageView back;
@Override
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.about);
ImageView back=(ImageView)findViewById(R.id.back); back.setOnClickListener( new View.OnClickListener() { @Override
public void onClick(View view) { finish();
} }); } }
Login.java
package com.rs;
import com.db.DBuser;
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast;
public class Login extends Activity { private EditText username,password;
DBuser db; @Override
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.login);
password = (EditText)findViewById(R.id.password); db=new DBuser(this);
db.delete_logout();
login.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View view) { if (username.getText().toString().equals("")){
Toast.makeText(Login.this, "Silahkan entry username !", Toast.LENGTH_SHORT).show();
}else if (password.getText().toString().equals("")){ Toast.makeText(Login.this, "Silahkan entry password !", Toast.LENGTH_SHORT).show();
}else{ LOG();
} } });
batal.setOnClickListener( new View.OnClickListener() { @Override
public void onClick(View view) { finish();
} }); }
protected void LOG() {
if(username.getText().toString().equals("admin")&& password.getText().toString().equals("admin")){ db.insert(username.getText().toString(),
password.getText().toString());
Intent intentDisplay = new Intent(this, RS_Start.class); startActivity(intentDisplay);
}else{
Toast.makeText(Login.this, "Maaf password atau username anda salah...!", Toast.LENGTH_SHORT).show();
} } }
Menu.java
package com.rs;
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View;
import android.widget.LinearLayout;
public class Menu extends Activity { @Override
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
LinearLayout login=(LinearLayout)findViewById(R.id.login); LinearLayout about=(LinearLayout)findViewById(R.id.about); LinearLayout map=(LinearLayout)findViewById(R.id.peta);
public void onClick(View view) {
Intent intentDisplay = new Intent(Menu.this, Login.class); startActivity(intentDisplay);
} });
about.setOnClickListener( new View.OnClickListener() { @Override
public void onClick(View view) {
Intent intentDisplay = new Intent(Menu.this, About.class); startActivity(intentDisplay);
} });
map.setOnClickListener( new View.OnClickListener() { @Override
public void onClick(View view) {
Intent intentDisplay = new Intent(Menu.this, RS_Start.class); startActivity(intentDisplay);
} }); } }
Peta.java
package com.rs;
import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions; import com.rs.input.RS_DBAdapter;
import android.database.Cursor;
import android.graphics.drawable.Drawable; import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class Peta extends FragmentActivity{ private RS_DBAdapter myDbHelper;
private Long mRowId;
private Drawable drawable; Cursor record =null;
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.map);
myDbHelper = new RS_DBAdapter(this); myDbHelper.open();
mRowId = (savedInstanceState == null) ? null
(Long) savedInstanceState.getSerializable(RS_DBAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(RS_DBAdapter.KEY_ROWID) : null;
}
String name = new
String((record.getString(record.getColumnIndex(RS_DBAdapter.KEY_NAME) )));
String address =
((record.getString(record.getColumnIndex(RS_DBAdapter.KEY_ADDRESS)))) ;
drawable = this.getResources().getDrawable(R.drawable.rsu);
GoogleMap map = ((SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.mapki)).getMap(); LatLng RS = new
LatLng((record.getDouble(record.getColumnIndex(RS_DBAdapter.KEY_LATIT UDE))),
(record.getDouble(record.getColumnIndex(RS_DBAdapter.KEY_LONGITUDE))) );
Marker rs = map.addMarker(new MarkerOptions().position(RS) .title(name)
.snippet(address)
.icon(BitmapDescriptorFactory .fromResource(R.drawable.rsu)));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(RS, 15)); map.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
} }
RS_DetailView.java
package com.rs;
import java.io.ByteArrayInputStream; import android.app.Activity;
import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap;
import android.graphics.BitmapFactory; import android.os.Bundle;
import android.view.Menu; import android.view.MenuItem; import android.view.View;
import android.widget.ImageButton; import android.widget.ImageView;
import android.widget.ImageView.ScaleType; import android.widget.RatingBar;
import android.widget.TextView; import com.db.DBuser;
import com.rs.input.RS_DBAdapter;
public class RS_DetailView extends Activity { DBuser db;
int LOG=0;
private TextView nameText; private TextView addressText; private TextView phoneText; private ImageButton image;
private RatingBar ratingbarValue; private Long mRowId;
private RS_DBAdapter myDbHelper; private ImageView back;
private static final int UPDATE_ID = Menu.FIRST;
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
myDbHelper = new RS_DBAdapter(this); myDbHelper.open();
setContentView(R.layout.record_detail); setTitle(R.string.detail_record);
db=new DBuser(this); LOG=db.query();
nameText = (TextView) findViewById(R.id.name);
addressText = (TextView) findViewById(R.id.address); phoneText = (TextView) findViewById(R.id.phone); image = (ImageButton) findViewById(R.id.image); back=(ImageView)findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View arg0) { finish();
} });
ratingbarValue = (RatingBar) findViewById(R.id.ratingbar); ratingbarValue.setNumStars(5);
mRowId = (savedInstanceState == null) ? null : (Long) savedInstanceState
.getSerializable(RS_DBAdapter.KEY_ROWID); if (mRowId == null) {
Bundle extras = getIntent().getExtras(); mRowId = extras != null ? extras
.getLong(RS_DBAdapter.KEY_ROWID) : null; }
populateFields(); }
public void showMap(View v) { long id = mRowId;
Intent intent = new Intent(this, Peta.class); intent.putExtra(RS_DBAdapter.KEY_ROWID, id); startActivity(intent);
}
private void populateFields() { if (mRowId != null) {
Cursor record = myDbHelper.fetchRecord(mRowId); startManagingCursor(record);
nameText.setText(record.getString(record.getColumnIndexOrThrow(RS_DBA dapter.KEY_NAME)));
addressText.setText(record.getString(record.getColumnIndexOrThrow(RS_ DBAdapter.KEY_ADDRESS)));
phoneText.setText(record.getString(record.getColumnIndexOrThrow(RS_DB Adapter.KEY_PHONE)));
ratingbarValue.setRating(record.getFloat(record.getColumnIndexOrThrow (RS_DBAdapter.KEY_RATING)));
try{
ByteArrayInputStream inputStream = new
ByteArrayInputStream(record.getBlob(record.getColumnIndex(RS_DBAdapte r.KEY_IMAGE)));
image.setImageResource(R.drawable.m120); }else{
image.setImageBitmap(bm);
image.setScaleType(ScaleType.FIT_XY); }
}catch (Exception e){ }
} }
@Override
public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu);
if(LOG>0){
menu.add(0, UPDATE_ID, 0, R.string.menu_update); }
return true; }
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) {
case UPDATE_ID:
updateRecord(mRowId); return true;
}
return super.onMenuItemSelected(featureId, item); }
private void updateRecord(long id) {
Intent i = new Intent(this, RS_EditRecord.class); i.putExtra("_id", id);
startActivityForResult(i, ACTIVITY_EDIT); }
@Override
protected void onResume() { super.onResume();
populateFields(); }
}
RS_EditRecord.java
package com.rs;
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import com.rs.input.RS_DBAdapter; import android.app.Activity; import android.app.AlertDialog;
import android.content.DialogInterface; import android.content.Intent;
import android.database.Cursor; import android.graphics.Bitmap;
import android.graphics.BitmapFactory; import android.graphics.Canvas;
import android.os.Bundle; import android.util.Log; import android.view.Display; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView;
import android.widget.ImageView.ScaleType; import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener; import android.widget.TextView;
import android.widget.Toast;
public class RS_EditRecord extends Activity { private EditText nameText;
private EditText addressText; private EditText phoneText;
private RatingBar ratingbarValue; private TextView latitudeText; private TextView longitudeText; private Long mRowId;
private RS_DBAdapter myDbHelper; private boolean cek=false;
private ImageButton image; private Bitmap bitmap; @Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
myDbHelper = new RS_DBAdapter(this); try{
myDbHelper.open(); }catch (Exception e){ }
setContentView(R.layout.record_edit); setTitle(R.string.edit_record);
nameText = (EditText) findViewById(R.id.name);
addressText = (EditText) findViewById(R.id.address); phoneText = (EditText) findViewById(R.id.phone); image=(ImageButton) findViewById(R.id.image);
image.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
Intent choosePictureIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(choosePictureIntent, 0);
} });
ratingbarValue = (RatingBar) findViewById(R.id.ratingbar); ratingbarValue.setNumStars(5);
ratingbarValue.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingbar, float rating, boolean fromUser)
{
ratingbar.getRating(); }
latitudeText = (EditText) findViewById(R.id.latitude); longitudeText = (EditText) findViewById(R.id.longitude); Button confirmButton = (Button) findViewById(R.id.confirm);
final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("").setCancelable(false)
.setNegativeButton("OK", new DialogInterface.OnClickListener() { @Override
public void onClick(DialogInterface dialog, int id) { dialog.cancel();
} });
mRowId = (savedInstanceState == null) ? null
: (Long) savedInstanceState.getSerializable(RS_DBAdapter.KEY_ROWID); if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(RS_DBAdapter.KEY_ROWID) : null;
}
populateFields();
confirmButton.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View view) { if (nameText.length() == 0) {
AlertDialog alertDialog = builder.create(); alertDialog.setTitle("ERROR!");
alertDialog.setMessage("Silahkan isi nama rumah sakit!"); alertDialog.show();
setResult(RESULT_CANCELED);
}else if(addressText.length()==0){
AlertDialog alertDialog = builder.create(); alertDialog.setTitle("ERROR!");
alertDialog.setMessage("Silahkan isi alamat rumah sakit!"); alertDialog.show();
setResult(RESULT_CANCELED); }else if(phoneText.length()==0){
AlertDialog alertDialog = builder.create(); alertDialog.setTitle("ERROR!");
alertDialog.setMessage("Silahkan isi telepon rumah sakit!"); alertDialog.show();
setResult(RESULT_CANCELED);
}else if(longitudeText.length()==0){
AlertDialog alertDialog = builder.create(); alertDialog.setTitle("ERROR!");
alertDialog.setMessage("Silahkan isi longitude rumah sakit!"); alertDialog.show();
setResult(RESULT_CANCELED);
}else if(latitudeText.length()==0){
AlertDialog alertDialog = builder.create(); alertDialog.setTitle("ERROR!");
alertDialog.setMessage("Silahkan isi latitude rumah sakit!"); alertDialog.show();
setResult(RESULT_CANCELED); } else {
cek=true;
setResult(RESULT_OK); finish();
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent); if (resultCode == RESULT_OK) {
Uri imageFileUri = intent.getData();
Bitmap bmp1 = loadBitmap(imageFileUri);
Toast.makeText(RS_EditRecord.this, "Load Image Sukses !", Toast.LENGTH_SHORT).show();
bitmap = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(), bmp1.getConfig());
Canvas canvas = new Canvas(bitmap); Paint paint = new Paint();
canvas.drawBitmap(bmp1, 0, 0, paint); image.setImageBitmap(bitmap);
image.setScaleType(ScaleType.FIT_XY); }
}
private Bitmap loadBitmap(Uri imageFileUri){
Display currentDisplay = getWindowManager().getDefaultDisplay(); float dw = currentDisplay.getWidth();
float dh = currentDisplay.getHeight();
Bitmap returnBmp = Bitmap.createBitmap((int)dw, (int)dh, Bitmap.Config.ARGB_4444);
try {
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
returnBmp = BitmapFactory.decodeStream(getContentResolver(). openInputStream(imageFileUri), null, bmpFactoryOptions);
int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/dh); int widthRatio = (int)Math.ceil(bmpFactoryOptions.outWidth/dw); Log.v("HEIGHTRATIO",""+heightRatio);
Log.v("WIDTHRATIO",""+widthRatio); if (heightRatio > 1 && widthRatio > 1){ if (heightRatio > widthRatio){ bmpFactoryOptions.inSampleSize = heightRatio; }
else{
bmpFactoryOptions.inSampleSize = widthRatio; }
}
bmpFactoryOptions.inJustDecodeBounds = false;
returnBmp = BitmapFactory.decodeStream(getContentResolver(). openInputStream(imageFileUri), null, bmpFactoryOptions); }
catch (FileNotFoundException e) { Log.v("ERROR",e.toString()); }
return returnBmp; }
private void populateFields() { if (mRowId != null) {
Toast.makeText(this, "no:"+ mRowId, 1000).show(); Cursor record = myDbHelper.fetchRecord(mRowId); startManagingCursor(record);
nameText.setText(record.getString(record
.getColumnIndexOrThrow(RS_DBAdapter.KEY_ADDRESS))); phoneText.setText(record.getString(record
.getColumnIndexOrThrow(RS_DBAdapter.KEY_PHONE))); ratingbarValue.setRating(record.getFloat(record .getColumnIndexOrThrow(RS_DBAdapter.KEY_RATING))); latitudeText.setText(record.getString(record
.getColumnIndexOrThrow(RS_DBAdapter.KEY_LATITUDE))); longitudeText.setText(record.getString(record
.getColumnIndexOrThrow(RS_DBAdapter.KEY_LONGITUDE)));
If
(record.getBlob(record.getColumnIndex(RS_DBAdapter.KEY_IMAGE)).toStri ng()==""){
bitmap=null; }else{
ByteArrayInputStream inputStream = new
ByteArrayInputStream(record.getBlob(record.getColumnIndex(RS_DBAdapte r.KEY_IMAGE)));
bitmap=(BitmapFactory.decodeStream(inputStream)); }
if(bitmap==null){
image.setImageResource(R.drawable.m120); }else{
image.setImageBitmap(bitmap); }
} }
@Override
protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(RS_DBAdapter.KEY_ROWID, mRowId); }
@Override
protected void onPause() { super.onPause();
saveState(); }
@Override
protected void onResume() { super.onResume();
}
private void saveState() {
String name = nameText.getText().toString();
String address = addressText.getText().toString(); String phone = phoneText.getText().toString();
String note = "Void"; // Removed to make room on EditRecord View float rating = ratingbarValue.getRating();
ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] photo=null;
if(bitmap!=null){
bitmap.compress(Bitmap.CompressFormat.PNG, 90, baos); photo = baos.toByteArray();
}
if (mRowId == null) {
long id = myDbHelper.createRecord(name, address, phone, note, rating, latitude, longitude,photo);
if (id > 0) { mRowId = id; }
} else {
myDbHelper.updateRecord(mRowId, name, address, phone, note, rating, latitude, longitude,photo);
} }
cek=false; }
}
RS_Start.java
package com.rs;
import java.io.PrintWriter; import java.io.StringWriter; import com.db.DBuser;
import com.rs.input.MainProgram; import com.rs.input.RS_DBAdapter; import android.app.ListActivity; import android.content.Intent; import android.database.Cursor; import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu;
import android.view.MenuItem; import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class RS_Start extends ListActivity { private static final int ACTIVITY_CREATE = 0; private static final int ACTIVITY_EDIT = 1; private static final int INSERT_ID = Menu.FIRST; private static final int DELETE_ID = Menu.FIRST + 1; private static final int MENU_RUTE = 5;
private RS_DBAdapter myDbHelper; DBuser db;
int LOG=0; @Override
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
db=new DBuser(this); LOG=db.query(); try {
setContentView(R.layout.records_list); myDbHelper = new RS_DBAdapter(this); myDbHelper.open();
fillData();
registerForContextMenu(getListView()); } catch (Exception e) {
} }
private void fillData() {
Cursor recordsCursor = myDbHelper.fetchAllRecords(); startManagingCursor(recordsCursor);
String[] from = new String[] { RS_DBAdapter.KEY_NAME }; int[] to = new int[] { R.id.text1 };
SimpleCursorAdapter records = new SimpleCursorAdapter(this, R.layout.records_row, recordsCursor, from, to);
setListAdapter(records); }
@Override
public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu);
menu.add(0, MENU_RUTE, 0, "Rute
pencarian").setIcon(android.R.drawable.ic_menu_search); if (LOG>0){
menu.add(0, INSERT_ID, 0, R.string.menu_insert); }
return true; }
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) {
case INSERT_ID: createRecord(); return true; case MENU_RUTE:
Intent intent = new Intent(this, com.rs.input.RsLauncher.class); startActivity(intent);
return true; }
return super.onMenuItemSelected(featureId, item); }
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
if(LOG>0){
super.onCreateContextMenu(menu, v, menuInfo); menu.add(0, DELETE_ID, 0, R.string.menu_delete); }
}
@Override
public boolean onContextItemSelected(MenuItem item) { switch (item.getItemId()) {
case DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo();
myDbHelper.deleteRecord(info.id); fillData();
return true; }
return super.onContextItemSelected(item); }
Intent i = new Intent(this, RS_EditRecord.class); startActivityForResult(i, ACTIVITY_CREATE);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this, RS_DetailView.class); i.putExtra(RS_DBAdapter.KEY_ROWID, id);
startActivityForResult(i, ACTIVITY_EDIT); }
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent); fillData();
} }
SplashScreen.java
package com.rs;
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import com.db.DBuser;
public class SplashScreen extends Activity { private boolean mIsBackButtonPressed;
private static final int SPLASH_DURATION = 3000; DBuser db;
@Override
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.splash); db=new DBuser(this);
db.delete_logout();
Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override
public void run() {
finish(); if (!mIsBackButtonPressed) {
Intent intent = new Intent(SplashScreen.this, Menu.class); SplashScreen.this.startActivity(intent);
} }
}, SPLASH_DURATION); }
@Override
public void onBackPressed() { mIsBackButtonPressed = true; super.onBackPressed();
Start.java
package com.rs;
import com.rs.input.MainProgram; import android.app.Activity; import android.content.Intent; import android.os.Bundle;
public class Start extends Activity{ @Override
public void onCreate(Bundle savedInstanceState) { Intent intent = new Intent(this, MainProgram.class); Start.this.startActivity(intent);
} }
DBHelper.java
package com.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
private static String DB_PATH = "/data/data/com.rs/databases/"; private static String DB_NAME = "map.db";
public DBHelper(Context c, String name, CursorFactory cf, int version) {
super(c, name, cf, version); }
private static final String sql_CREATE_TABLES = "CREATE TABLE " + DBConst.TABLE + " ( "
+ DBConst.ID + " integer PRIMARY KEY AUTOINCREMENT, " + DBConst.USER + " text, "
+ DBConst.PASSWORD + " text " + ");";
@Override
public void onCreate(SQLiteDatabase db) { db.execSQL(sql_CREATE_TABLES);
insert(db); }
private void insert(SQLiteDatabase db) { }
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public boolean checkDataBase(){ SQLiteDatabase checkDB = null; try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
if(checkDB != null){ checkDB.close(); }
return checkDB != null ? true : false; }
}
DBUser.java
package com.db;
import android.content.ContentValues; import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteException; import android.util.Log;
public class DBuser extends DB {
private static final String TAG = "com.db.DBuser"; public DBuser(Context c) {
super(c); }
public void insert(String user,String pass) { try {
open();
ContentValues cv = new ContentValues(); cv.put(DBConst.USER,user);
cv.put(DBConst.PASSWORD,pass); db.insert(DBConst.TABLE, null, cv); } catch (SQLiteException e) {
Log.w(TAG, e.getMessage()); }
}
public void delete_logout() { try {
open();
db.delete(DBConst.TABLE, null,null); } catch (SQLiteException e) {
Log.w(TAG, e.getMessage()); }
}
public void insert_log(String user,String pass) { try {
open();
ContentValues cv = new ContentValues(); cv.put(DBConst.USER,user);
cv.put(DBConst.PASSWORD,pass); db.insert(DBConst.TABLE, null, cv); } catch (SQLiteException e) {
Log.w(TAG, e.getMessage()); }
}
public int query() { int result=0;
Cursor cu=db.rawQuery("SELECT * FROM user",null); if (cu.moveToFirst()){
result=cu.getCount(); cu.close();
return result; }
}
About.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/abstract_dark_red_background_hd_mobile_ wallpaper"
android:orientation="vertical" > <RelativeLayout
android:id="@+id/linearLayout1" android:layout_width="match_parent" android:layout_height="wrap_content" >
<LinearLayout
android:id="@+id/about"
android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true"
android:gravity="center_vertical|center_horizontal" android:background="@drawable/redb">
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Tentang" android:textColor="#ffffff"
android:textSize="20sp" android:layout_marginRight="5px" android:shadowColor="#000000" android:shadowDx="0.5" android:shadowDy="0.5" android:shadowRadius="0.5" android:background="@drawable/red"
android:gravity="center_vertical|center_horizontal"
android:drawableLeft="@drawable/tentang" android:paddingLeft="5dp" android:paddingBottom="3dp"/>
</LinearLayout> </RelativeLayout>
<LinearLayout
android:id="@+id/linearLayout2" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_vertical"
android:orientation="horizontal" android:background="#50000000">
<ImageView
android:id="@+id/imageView1" android:layout_width="58dp" android:layout_height="58dp"
android:src="@drawable/logo_usu" android:layout_marginLeft="5dp" android:background="#55000000"/>
<TextView
android:id="@+id/textView2"
android:layout_height="wrap_content" android:layout_marginRight="2dp" android:shadowColor="#000000" android:shadowDx="0.1"
android:shadowDy="0.1" android:shadowRadius="0.1"
android:text="Penentuan rute terpendek pencarian rumah sakit dengan algoritma ant colony "
android:textColor="#ffffff"
android:textSize="18sp" android:layout_weight="1" android:layout_marginLeft="5dp"/>
</LinearLayout> <LinearLayout
android:id="@+id/LinearLayout01" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1"
android:gravity="bottom|center_horizontal" android:orientation="vertical" >
<LinearLayout
android:id="@+id/linearLayout4" android:layout_width="match_parent" android:layout_height="341dp"
android:gravity="center_horizontal" android:orientation="vertical" > <TextView
android:id="@+id/textView1"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="top|center_horizontal" android:gravity="top"
android:text="User Manual" android:textColor="#ffffff" android:textSize="16sp" /> <TextView
android:id="@+id/textView3"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:text="1. Untuk menggunakan aplikasi, tekan tombol Rute pada halaman utama."
android:textColor="#ffffff"/> <TextView
android:id="@+id/textView4"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:text="2. Pada halaman Daftar Rumah Sakit, tekan menu pada ponsel dan tekan tombol Rute Pencarian."
android:textColor="#ffffff"/> <TextView
android:id="@+id/textView5"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:text="3. Setelah muncul Peta Kota Medan, tekan menu pada ponsel sekali lagi."
android:textColor="#ffffff"/> <TextView
android:id="@+id/textView6"