• Tidak ada hasil yang ditemukan

public void Count_Bobot_Tambah_Simpul(int index, int limit, JSONArray jarrcoordinates) throws JSONException{

N/A
N/A
Protected

Academic year: 2021

Membagikan "public void Count_Bobot_Tambah_Simpul(int index, int limit, JSONArray jarrcoordinates) throws JSONException{"

Copied!
78
0
0

Teks penuh

(1)
(2)

package com.app.dijkstra;

import org.json.JSONArray; import org.json.JSONException;

import android.location.Location;

public class Count_Bobot_Tambah_Simpul{

double bobot = 0;

public void Count_Bobot_Tambah_Simpul(int index, int limit, JSONArray jArrCoordinates) throws JSONException{

// cuma dijalanin sekali, kalo limit 1, maka 1-0 = 0 // 0 == 0 (limit)

if(index == limit){

// get JSON coordinate

JSONArray latlngs = jArrCoordinates.getJSONArray(index);

double lat_0 = latlngs.getDouble(0); double lng_0 = latlngs.getDouble(1);

Location simpulAwal = new Location(""); simpulAwal.setLatitude(lat_0);

(3)

// get coordinate again

JSONArray latlngs1 = jArrCoordinates.getJSONArray(++index);

double lat_1 = latlngs1.getDouble(0); double lng_1 = latlngs1.getDouble(1);

Location simpulTengah = new Location("");

simpulTengah.setLatitude(lat_1); simpulTengah.setLongitude(lng_1); //simpan jarak bobot += simpulAwal.distanceTo(simpulTengah); }else{ for(int i = 0; i < 1; i++){

// get JSON coordinate

JSONArray latlngs = jArrCoordinates.getJSONArray(index);

double lat_0 = latlngs.getDouble(0); double lng_0 = latlngs.getDouble(1);

Location simpulAwal = new Location(""); simpulAwal.setLatitude(lat_0);

(4)

simpulAwal.setLongitude(lng_0);

// get coordinate again

JSONArray latlngs1 = jArrCoordinates.getJSONArray(++index);

double lat_1 = latlngs1.getDouble(0); double lng_1 = latlngs1.getDouble(1);

Location simpulTengah = new Location("");

simpulTengah.setLatitude(lat_1); simpulTengah.setLongitude(lng_1);

//simpan jarak

bobot += simpulAwal.distanceTo(simpulTengah);

if(index == limit) break; //jika dah smpe ke tengah, break; misal 0-72 else --i; } } } } package com.app.dijkstra; import java.util.ArrayList;

(5)

import java.util.Collections; import java.util.List; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.widget.Toast;

public class dijkstra {

SQLHelper dbHelper; Cursor cursor;

String[][] graph = new String[100][100]; String jalur_terpendek1 = "";

String status = "none";

void jalurTerpendek(String[][] arg_graph, int simpulAwal, int simpulTujuan){

System.out.println("sa : " + simpulAwal + " & st : " + simpulTujuan); if(simpulAwal == simpulTujuan){

status = "die"; return;

//System.exit(0); }

(6)

graph = arg_graph; int simpul_awal = simpulAwal; int simpul_maju = simpulAwal; int simpul_tujuan = simpulTujuan;

if(simpul_maju != simpul_tujuan){ //HITUNG JUMLAH SIMPUL int jml_simpul = 0;

for(String[] array : graph){ if(array[0] != null){ jml_simpul += 1; }

}

//System.out.println("Jumlah Simpul : "+jml_simpul);

//System.out.println("=============================================="); //System.out.println();

//TANDAI SIMPUL YANG AKAN DIKERJAKAN

List<Integer> simpulYangDikerjakan = new ArrayList<Integer>();

//UNTUK MENYIMPAN NILAI-NILAI * YANG DITANDAI

(7)

double nilaiSimpulYgDitandai = 0; double nilaiSimpulFixYgDitandai = 0;

//PERULANGAN HANDLE

for(int perulangan = 0; perulangan < 1; perulangan++){

//UNTUK MNDAPATKAN 1 BOBOT PALING MINIMUM DARI SETIAP SIMPUL List<Double> perbandinganSemuaBobot = new ArrayList<Double>();

//DAFTARKAN SIMPUL pertama YANG AKAN DIKERJAKAN KE DALAM ARRAY if(!simpulYangDikerjakan.contains(simpul_maju)){

simpulYangDikerjakan.add(simpul_maju); }

//PERULANGAN SIMPUL SIMPUL YANG DITANDAI

for(int perulanganSimpul = 0; perulanganSimpul < simpulYangDikerjakan.size(); perulanganSimpul++){

//HITUNG JUMLAH BARIS PER KOLOM SIMPUL int jml_baris_fix = 0;

for(int min_batas_bris = 0; min_batas_bris < 100; min_batas_bris++){

if(graph[simpulYangDikerjakan.get(perulanganSimpul)][min_batas_bris] != null){ jml_baris_fix += 1;

} }

//CARI BOBOT MINIMUM di 1 simpul berdasarkan baris scr urut[0][0],[0][1] dst List<Double> bobot = new ArrayList<Double>();

(8)

int status_baris = 0;

//perulangan CARI BOBOT2 DI 1 SIMPUL

for(int min_batas_bris_fix = 0; min_batas_bris_fix < jml_baris_fix; min_batas_bris_fix++){ String bobot_dan_ruas =

graph[simpulYangDikerjakan.get(perulanganSimpul)][min_batas_bris_fix];//pasti berurutan [0][0],[0][1] dst

//print isi dr baris[0][0],[0][1],[0][2] dst

//System.out.println("bobot_dan_ruas : "+bobot_dan_ruas); String[] explode;

explode = bobot_dan_ruas.split("->");

//System.out.println("bobot_ : "+explode[0]);

//cari bobot yg belum dikerjakan (yg tidak ada tanda ->y) if(explode.length == 2){

status_baris += 1; // masih ada yg belum ->y

//Cek simpul apakah sudah ditandai apa blom, klo udh berarti nilai * tidak ditambah lagi / 0

//kalo blm ditandai, berarti nilai * bernilai nilaiSimpulYgditandai if(!simpulYangSudahDikerjakan_bawah.isEmpty()){ if(simpulYangSudahDikerjakan_bawah.contains(simpulYangDikerjakan.get(perulanganSimpul))){ nilaiSimpulYgDitandai = 0; }else{ nilaiSimpulYgDitandai = nilaiSimpulFixYgDitandai; } }

(9)

bobot.add((Double.parseDouble(explode[1])+nilaiSimpulYgDitandai));//bs acak bobot[0],bobot[2]// 0 dan 2 berdasarkan baris yg akan dikerjakan

graph[simpulYangDikerjakan.get(perulanganSimpul)][min_batas_bris_fix] =

String.valueOf(explode[0]+"->"+(Double.parseDouble(explode[1])+nilaiSimpulYgDitandai)); }

}

//jika baris di kolom belum ->y semua, maka lakukan if di bawah ini : if(status_baris > 0){

//DAPATKAN BOBOT MINIMUM

for(int index_bobot = 0; index_bobot < bobot.size(); index_bobot++){ if(bobot.get(index_bobot) <= bobot.get(0)){

bobot.set(0, bobot.get(index_bobot)); }

}

perbandinganSemuaBobot.add(bobot.get(0)); }//end if jika ->y atau ->t belum semua dikerjakan

else{//Jika baris di kolom sudah ->y semua, maka lakukan else di bawah ini //System.out.println("=======||Baris sudah ->y semua||======="); }

(10)

if(!simpulYangSudahDikerjakan_bawah.contains(simpulYangDikerjakan.get(perulanganSimpul))){ simpulYangSudahDikerjakan_bawah.add(simpulYangDikerjakan.get(perulanganSimpul)); }

}//end for perulanganSimpul

//DAPATKAN 1 BOBOT PALING MINIMUM DARI SIMPUL YG DITANDAI

for(int min_indexAntarBobotYgDitandai = 0; min_indexAntarBobotYgDitandai < perbandinganSemuaBobot.size(); min_indexAntarBobotYgDitandai++){ if(perbandinganSemuaBobot.get(min_indexAntarBobotYgDitandai) <= perbandinganSemuaBobot.get(0)){ perbandinganSemuaBobot.set(0, perbandinganSemuaBobot.get(min_indexAntarBobotYgDitandai)); } }

//DAPATKAN INDEX SIMPUL+BOBOTNYA YG ASLI DARI SIMPUL YG DITANDAI int indexAwalAsli = 0; //index simpulnya

int status_baris1 = 0; int dapat_indexAsliBobot = 0; int simpul_lama = 0;

for(Integer indexAsli_bobot : simpulYangDikerjakan){ for(int baris1 = 0; baris1 < 100; baris1++){

if(graph[simpulYangDikerjakan.get(indexAwalAsli)][baris1] != null){

String bobot_dan_ruas1 = graph[simpulYangDikerjakan.get(indexAwalAsli)][baris1]; //System.out.println(bobot_dan_ruas1);

(11)

explode1 = bobot_dan_ruas1.split("->"); if(explode1.length == 2){ // System.out.println("---;"+explode1[1]); if(perbandinganSemuaBobot.get(0) == Double.parseDouble(explode1[1])){ dapat_indexAsliBobot = baris1; simpul_lama = simpulYangDikerjakan.get(indexAwalAsli); simpul_maju = Integer.parseInt(explode1[0]); status_baris1 += 1; }

}//end if cek ->y atau ->t }//end if cek baris != null }//end for limit baris = 100

indexAwalAsli++; //index simpul di tambah 1 }//end for simpul yang dikerjakan

//BULETIN BOBOT MINIMUM YANG UDH DIDAPAT dan HAPUS RUAS YANG BERHUBUNGAN if(status_baris1 > 0){

graph[simpul_lama][dapat_indexAsliBobot] = graph[simpul_lama][dapat_indexAsliBobot]+"->y";

//HAPUS RUAS LAIN

for(int min_kolom = 0; min_kolom < jml_simpul; min_kolom++){ for(int min_baris = 0; min_baris < 100; min_baris++){

if(graph[min_kolom][min_baris] != null){

(12)

String[] explode3 = ruasYgAkanDihapus.split("->"); if(explode3.length == 2){

if(explode3[0].equals(String.valueOf(simpul_maju))){

graph[min_kolom][min_baris] = graph[min_kolom][min_baris]+"->t"; }

}//end if cek ->y atau ->t }//end if cek baris != null }//end for baris

}//end for kolom

}//end if cek status_baris sudah ->y atau ->t semua apa belum

//Nilai * yg ditandai

nilaiSimpulFixYgDitandai = perbandinganSemuaBobot.get(0); //System.out.println("nilaiSimpulFixYgDitandai : "+nilaiSimpulFixYgDitandai);

//System.out.println("perbandingan simpul? : "+simpul_maju+" = "+simpul_tujuan+" ..?"); if(simpul_maju != simpul_tujuan){

--perulangan; }

else{

break; //akhiri perulangan }

}//end for handle perulangan //System.out.println("--SELESAI--");

(13)

List<String> gabungSimpulPilihan = new ArrayList<String>(); for(int h = 0; h < jml_simpul; h++){

for(int n = 0; n < 100; n++){ if(graph[h][n] != null){

String str_graph = graph[h][n];

if(str_graph.substring(str_graph.length()-1, str_graph.length()).equals("y")){ String[] explode4 = graph[h][n].split("->");

String simpulGabung = h+"-"+explode4[0];

gabungSimpulPilihan.add(simpulGabung); }

}//end if cek isi graph != null }//end for looping baris }//end looping kolom (simpul)

//masukkan simpul yg sudah diurutkan (dari simpul tujuan ke simpul awal). (nanti direverse arraynya)

List<Integer> simpulFix_finish = new ArrayList<Integer>();

//masukkan pertama kali simpul tujuan (simpul akhir) ke array dgn index 0. (nanti dibalik(reverse) arraynya)

simpulFix_finish.add(simpul_tujuan);

int simpul_explode = simpul_tujuan;

for(int v = 0; v < 1; v++){

(14)

String explode_simpul = gabungSimpulPilihan.get(w); String[] explode5 = explode_simpul.split("-");

if(simpul_explode == Integer.parseInt(explode5[1])){ simpulFix_finish.add(Integer.parseInt(explode5[0])); simpul_explode = Integer.parseInt(explode5[0]); } if(simpul_explode == simpul_awal){ break; } } if(simpul_awal != simpul_explode){ --v; }else{ break; }

}//end for cari simpul yang dibuletin lalu dibandingkan dgn simpul_tujuan

//array di balik indexnya; jadi simpul tujuan di pindah posisi ke akhir index array Collections.reverse(simpulFix_finish); String jalur_terpendek = ""; for(int x = 0; x < simpulFix_finish.size(); x++){ if(x == simpulFix_finish.size()-1){ jalur_terpendek += simpulFix_finish.get(x); }else{

(15)

jalur_terpendek += simpulFix_finish.get(x)+"->"; }

}

//System.out.println("... "+jalur_terpendek);

//Toast.makeText(getBaseContext(), "... "+jalur_terpendek, Toast.LENGTH_LONG).show(); jalur_terpendek1 = jalur_terpendek;

}//end if start != finish } } package com.app.dijkstra; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.location.Location;

(16)

import android.widget.Toast;

public class Get_koordinat_awal_akhir extends Activity{

// DB

Cursor cursor;

int fix_simpul_awal = 0; String explode_lat_only = "";

Location posisiUser = new Location("");

ArrayList<String> a_tmp_graph = new ArrayList<String>();

// return JSON

JSONObject jadi_json = new JSONObject();

// AMBIL NODE DARI FIELD SIMPUL_AWAL DAN TUJUAN DI TABEL GRAPH, TRS DIGABUNG; contoh 1,0 DAN MASUKKAN KE ARRAY

List<String> barisDobel = new ArrayList<String>();

List<String> indexBarisYgDikerjakan = new ArrayList<String>();

/*

* @fungsi

(17)

* jika ada simpul 1-0 dan 0-1 maka yg dikerjakan hanya 1-0 ( karena koordinat 1-0 sama dengan 0-1 (koordinat hanya dibalik) )

* @parameter

* latx : latitude user atau SMK

* lngx : longitude user atau destination * context : MainActivity context * @return

* JSON (index coordinates, nodes0, nodes1) */

public JSONObject Get_simpul(double latx, double lngx, Context context) throws JSONException {

// TODO Auto-generated constructor stub

// your coordinate

posisiUser.setLatitude(latx); posisiUser.setLongitude(lngx);

// TAMPUNG NODE DARI FIELD SIMPUL_AWAL DAN TUJUAN DI TABEL GRAPH, TRS DIGABUNG; contoh 1,0 DAN MASUKKAN KE ARRAY

List<String> barisDobel = new ArrayList<String>();

List<String> indexBarisYgDikerjakan = new ArrayList<String>();

SQLHelper dbHelper = new SQLHelper(context); SQLiteDatabase db = dbHelper.getReadableDatabase();

(18)

cursor = db.rawQuery("SELECT * FROM graph where simpul_awal != '' and simpul_tujuan != '' and jalur != '' and bobot != ''", null);

cursor.moveToFirst();

// AMBIL NODE DARI FIELD SIMPUL_AWAL DAN SIMPUL_TUJUAN DI TABEL GRAPH, TRS DIGABUNG; contoh 1,0 DAN MASUKKAN KE ARRAY

// looping di bawah ini untuk MEMERIKSA BARIS DOBEL {simpulnya yg dobel} 1,0 -> 0,1 {1,0 dihitung tapi 0,1 gak dihitung}

for (int i = 0; i < cursor.getCount(); i++){

cursor.moveToPosition(i);

// node dari field simpul_awal

String fieldSimpulAwal = cursor.getString(1).toString();

// node dari field simpul_akhir

String fieldSimpulTujuan = cursor.getString(2).toString();

String gabungSimpul = fieldSimpulAwal+","+fieldSimpulTujuan; String gabung_balikSimpul = fieldSimpulTujuan+","+fieldSimpulAwal;

// seleksi ruas yang dobel; contoh : 1,0 == 0,1 // pilih salah satu, misal : 1,0

if(barisDobel.isEmpty()){

(19)

// field id pada tabel graph

indexBarisYgDikerjakan.add(cursor.getString(0).toString()); }else{

if(!barisDobel.contains(gabungSimpul)){ barisDobel.add(gabung_balikSimpul);

// field id pada tabel graph

indexBarisYgDikerjakan.add(cursor.getString(0).toString()); }

} }

// list simpul yg dikerjakan

StringBuilder indexBarisYgDikerjakan1 = new StringBuilder(); for(int j = 0; j < indexBarisYgDikerjakan.size(); j++){

if(indexBarisYgDikerjakan1.length() == 0){

// field id lagi pada tabel graph (khusus utk stringbuilder) indexBarisYgDikerjakan1.append(indexBarisYgDikerjakan.get(j)); }else{

indexBarisYgDikerjakan1.append(","+indexBarisYgDikerjakan.get(j)); // untuk where in ('0,1')

(20)

} }

// Query baris yang gak dobel

cursor = db.rawQuery("SELECT * FROM graph where id in("+indexBarisYgDikerjakan1+")",null);

cursor.moveToFirst();

JSONObject obj = new JSONObject();

// @@@@@@=========== Cari JARAK // looping semua record

for(int k = 0; k < cursor.getCount(); k++){

// VARIABEL BUAT CARI 1 JARAK DALAM 1 RECORD (1 record isinya banyak koordinat)

// simpan jarak user ke koordinat simpul dalam meter

List<Double> jarakUserKeKoordinatSimpul = new ArrayList<Double>();

cursor.moveToPosition(k);

// dapatkan koordinat Lat,Lng dari field koordinat (3) String json = cursor.getString(3).toString();

(21)

JSONObject jObject = new JSONObject(json);

JSONArray jArrCoordinates = jObject.getJSONArray("coordinates"); JSONArray jArrNodes = jObject.getJSONArray("nodes");

// get coordinate

for(int w = 0; w < jArrCoordinates.length(); w++){

JSONArray latlngs = jArrCoordinates.getJSONArray(w); Double lats = latlngs.getDouble(0);

Double lngs = latlngs.getDouble(1);

//SET LAT,LNG

Location koordinatSimpul = new Location(""); koordinatSimpul.setLatitude(lats);

koordinatSimpul.setLongitude(lngs);

//CARI JARAK DARI POSISI USER KE koordinate sekitar SIMPUL (dalam meter)

double jarak = posisiUser.distanceTo(koordinatSimpul);

jarakUserKeKoordinatSimpul.add(jarak);

}

// CARI bobot yg paling kecil int index_koordinatSimpul = 0;

(22)

for(int m = 0; m < jarakUserKeKoordinatSimpul.size(); m++){

if(jarakUserKeKoordinatSimpul.get(m) <= jarakUserKeKoordinatSimpul.get(0)){

jarakUserKeKoordinatSimpul.set(0, jarakUserKeKoordinatSimpul.get(m));

// index array dari value yg terkecil index_koordinatSimpul = m; }

}

// field id dari table graph int row_id = cursor.getInt(0);

JSONObject list = new JSONObject();

// masukkan index koordinat array, bobot terkecil dan jumlah koordinat ke JSON list.put("row_id", row_id);

list.put("index", index_koordinatSimpul);

list.put("bobot", jarakUserKeKoordinatSimpul.get(0)); list.put("nodes", jArrNodes.getString(0));

list.put("count_koordinat", (jArrCoordinates.length() - 1));

(23)

ja.put(list);

// Create json // example output :

// {"0" : [{"row_id":17, "index":"7", "bobot":"427.66", "count_koordinat":"15", "nodes":"0-1"}]}

obj.put("" + k, ja);

}//end looping baris DB

double x = 0; double y = 0; int rowId_json = 0; int indexCoordinate_json = 0; int countCoordinate_json = 0; String nodes_json = "";

// cari bobot terkecil dari JSON for(int s = 0; s < obj.length(); s++){

if(s == 0){ // first

JSONArray a = obj.getJSONArray("0"); JSONObject b = a.getJSONObject(0);

(24)

x = Double.parseDouble(b.getString("bobot"));

// ========== // row id field

rowId_json = Integer.parseInt(b.getString("row_id")); // index coordinate sekitar simpul

indexCoordinate_json = Integer.parseInt(b.getString("index")); // jumlah coordinate countCoordinate_json = Integer.parseInt(b.getString("count_koordinat")); // nodes nodes_json = b.getString("nodes").toString(); // ========== }else{ // second, dst JSONArray c = obj.getJSONArray("" + s); JSONObject d = c.getJSONObject(0); y = Double.parseDouble(d.getString("bobot"));

// dapatkan value terkecil (bobot) if(y <= x){

// bobot x = y;

(25)

// row id field

rowId_json = Integer.parseInt(d.getString("row_id")); // index coordinate sekitar simpul

indexCoordinate_json = Integer.parseInt(d.getString("index")); // jumlah coordinate countCoordinate_json = Integer.parseInt(d.getString("count_koordinat")); // nodes nodes_json = d.getString("nodes").toString(); // ========== } } } // nodes : 0-1

String[] exp_nodes = nodes_json.split("-");

int field_simpul_awal = Integer.parseInt(exp_nodes[0]); int field_simpul_tujuan = Integer.parseInt(exp_nodes[1]);

// Koordinat yg didapat di awal atau diakhir, maka gak perlu nambah simpul if(indexCoordinate_json == 0 || indexCoordinate_json == countCoordinate_json){

(26)

//tentukan simpul awal atau akhir yg dekat dgn posisi user if(indexCoordinate_json == 0){

// nodes di field simpul_awal

fix_simpul_awal = field_simpul_awal;

}else if(indexCoordinate_json == countCoordinate_json){

// nodes di field simpul_akhir

fix_simpul_awal = field_simpul_tujuan; }

jadi_json.put("status", "jalur_none");

}

//Koordinat yang didapat berada ditengah2 simpul 0 - 1 (misal) else{

// cari simpul dobel, simpulnya dibalik

cursor = db.rawQuery("SELECT id FROM graph where simpul_awal = "+ field_simpul_tujuan + " and simpul_tujuan = " + field_simpul_awal, null);

cursor.moveToFirst(); cursor.moveToPosition(0);

int dobel = cursor.getCount();

//ada simpul yg dobel (1,0) dan (0,1) if(dobel == 1){

(27)

jadi_json.put("status", "jalur_double");

}

//gak dobel, hanya (1,0) else if(dobel == 0){ jadi_json.put("status", "jalur_single"); } } // JSON jadi_json.put("node_simpul_awal0", field_simpul_awal); jadi_json.put("node_simpul_awal1", field_simpul_tujuan); jadi_json.put("index_coordinate_json", indexCoordinate_json); //jadi_json.put("destination_simpul", judulTabel_simpulTujuan); jadi_json.put("explode_lat_only", explode_lat_only); return jadi_json; }//public }

(28)

package com.app.dijkstra; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.app.dijkstra.SQLHelper; /*

* CONVERT GRAPH FROM DB TO ARRAY */

public class GraphToArray {

// DB

SQLHelper dbHelper; SQLiteDatabase db; protected Cursor cursor;

// Array Graph

String[][] graph = new String[100][100];

/* Convert Graph from DB to Array

* parameter mainContext : context MainActivity * return array String[][]

(29)

*/

public String[][] convertToArray(Context mainContext){

dbHelper = new SQLHelper(mainContext); db = dbHelper.getReadableDatabase();

// PINDAHKAN GRAPH DARI DB KE GRAPH ARRAY

cursor = db.rawQuery("SELECT * FROM graph order by simpul_awal,simpul_tujuan asc", null);

cursor.moveToFirst();

String temp_index_baris = ""; int index_kolom = 0;

int jml_baris = cursor.getCount();

for(int i = 0; i < jml_baris; i++){

// baris

cursor.moveToPosition(i);

// Cari index kolom

int simpulAwalDB = Integer.parseInt(cursor.getString(1)); // simpul_tujuan

if(temp_index_baris == ""){

temp_index_baris = String.valueOf(simpulAwalDB); }else{

(30)

// simpul_awal berikutnya tidak sama dgn sebelumnya, reset index_kolom = 0 if(Integer.parseInt(temp_index_baris) != simpulAwalDB){ index_kolom = 0; temp_index_baris = String.valueOf(simpulAwalDB); } }

// masukkan ke graph array

String simpulTujuan_dan_Bobot = "";

if(cursor.getString(2).equals("") && cursor.getString(3).equals("") && cursor.getString(4).equals("")){ //tidak ada derajat keluar

simpulTujuan_dan_Bobot = ";"; }

// ada derajat keluar else{

// example output : 2->789.98

simpulTujuan_dan_Bobot = cursor.getString(2).toString()+"->"+cursor.getString(4).toString(); //simpul_tujuan dan bobot

}

graph[simpulAwalDB][index_kolom] = simpulTujuan_dan_Bobot; index_kolom++;

(31)

return graph; } } package com.app.dijkstra; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.app.dijkstra.SQLHelper; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.OnMapClickListener; import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener; import com.google.android.gms.maps.SupportMapFragment; import android.support.v4.app.FragmentActivity; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.PolylineOptions; import com.app.dijkstra.dijkstra; import com.app.dijkstra.Tambah_simpul; import com.app.dijkstra.MainActivity; import android.os.Bundle; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Color; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.Toast;

public class MainActivity extends FragmentActivity implements OnMapClickListener, OnMapLongClickListener {

// DB

(32)

Cursor cursor; // Google Maps GoogleMap googleMap;

public String __global_endposition = null; public String __global_startposition = null; public int __global_simpul_awal;

public int __global_simpul_akhir;

public String __global_old_simpul_awal = ""; public String __global_old_simpul_akhir = ""; public int __global_maxRow0;

public int __global_maxRow1;

private String[][] __global_graphArray;

private LatLng __global_yourCoordinate_exist = null; @Override

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main); // create DB

dbHelper = new SQLHelper(this); try {

dbHelper.createDataBase(); }

catch (Exception ioe) {

Toast.makeText(getApplicationContext(), "Gagal", Toast.LENGTH_LONG).show(); } // BUAT MAP if(googleMap == null){ googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.peta)).getMap(); googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-2.987696, 104.732480), 12.0f)); if(googleMap != null){ googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.peta)).getMap(); } } // event map googleMap.setOnMapClickListener(this); googleMap.setOnMapLongClickListener(this);

// Query DB to show all SPBU dbHelper = new SQLHelper(this);

final SQLiteDatabase db = dbHelper.getReadableDatabase(); cursor = db.rawQuery("SELECT * FROM SPBU", null);

cursor.moveToFirst(); // tampung nama SPBU

(33)

ArrayList<String> spinner_list_smk = new ArrayList<String>(); // Adapter spinner SPBU

ArrayAdapter<String> adapter_spinner_smk; // nama-nama SPBU dimasukkan ke array spinner_list_smk.add("-- Pilih SPBU --"); for(int i = 0; i < cursor.getCount(); i++){

cursor.moveToPosition(i);

spinner_list_smk.add(cursor.getString(1).toString()); }

// masukkan list SPBU ke spinner (dropdown)

Spinner spinner = (Spinner) findViewById(R.id.spinner_list_smk); adapter_spinner_smk = new ArrayAdapter<String>(this,

android.R.layout.simple_spinner_item, spinner_list_smk); adapter_spinner_smk.setDropDownViewResource(android.R.layout.simple_spinner_dr opdown_item); spinner.setAdapter(adapter_spinner_smk); spinner.setBackgroundColor(Color.WHITE); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override

public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

// TODO Auto-generated method stub

if(arg0.getItemAtPosition(arg2).toString() != "-- Pilih SPBU --"){

String pilih_smk =

arg0.getItemAtPosition(arg2).toString();

cursor = db.rawQuery("SELECT koordinat FROM SPBU

where spbu = '" + pilih_smk + "'", null);

cursor.moveToFirst();

cursor.moveToPosition(0);

// get coordinate SPBU from field koordinat

__global_endposition =

cursor.getString(0).toString();

// user men-tap peta

if(__global_yourCoordinate_exist != null){ // your coordinate double latUser = __global_yourCoordinate_exist.latitude; double lngUser = __global_yourCoordinate_exist.longitude;

(34)

String[] exp_endCoordinate = __global_endposition.split(","); double lat_endposition = Double.parseDouble(exp_endCoordinate[0]); double lng_endposition = Double.parseDouble(exp_endCoordinate[1]); // ======================================================================== // CORE SCRIPT

// fungsi cari simpul awal dan tujuan, buat

graph sampai algoritma dijkstra

// ======================================================================== try { startingScript(latUser, lngUser, lat_endposition, lng_endposition); } catch (JSONException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}else{

Toast.makeText(getApplicationContext(), "Tap pada peta untuk menentukan posisi Anda", Toast.LENGTH_LONG).show();

}

}// if -- pilih SPBU -- }

@Override

public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub

}

});//setOnItemSelectedListener }

@Override

public void onMapLongClick(LatLng arg0) { // TODO Auto-generated method stub }

@Override

public void onMapClick(LatLng arg0) { // TODO Auto-generated method stub // your coordinate position

(35)

double latUser = arg0.latitude; double lngUser = arg0.longitude; __global_yourCoordinate_exist = arg0; // destination coordinate position

String endposition = __global_endposition; if(endposition != null){

// dipecah coordinate SPBU

String[] exp_endposition = endposition.split(",");

double lat_endposition = Double.parseDouble(exp_endposition[0]); double lng_endposition = Double.parseDouble(exp_endposition[1]); //

======================================================================== // CORE SCRIPT

// fungsi cari simpul awal dan tujuan, buat graph sampai algoritma dijkstra

//

======================================================================== try {

startingScript(latUser, lngUser, lat_endposition, lng_endposition);

} catch (JSONException e) {

// TODO Auto-generated catch block e.printStackTrace();

} }else{

Toast.makeText(getApplicationContext(), "pilih SPBU dulu", Toast.LENGTH_LONG).show(); } } /* * =========== * CORE SCRIPT * =========== * * @fungsi utama

* (1) mendapatkan koordinat awal dan akhir di sekitar jalur *

* (2) koordinat awal kemudian di konversi menjadi simpul awal * dan koordinat akhir di konversi menjadi simpul akhir *

* (3) simpul awal dan akhir kemudian dijadikan 'inputan' untuk perhitungan algoritma dijsktra

*

* (4) setelah dilakukan perhitungan, didapatkan jalur terpendek lalu digambar jalurnya menggunakan polyline

(36)

* @parameter

* latUser dan lngUser : koordinat posisi user

* lat_endposition dan lng_endposition : koordinat posisi SPBU *

* @return * no return */

public void startingScript(double latUser, double lngUser, double lat_endposition, double lng_endposition) throws JSONException{

// delete temporary record DB deleteTemporaryRecord(); // reset google map googleMap.clear();

// convert graph from DB to Array; graph[][] GraphToArray DBGraph = new GraphToArray();

__global_graphArray = DBGraph.convertToArray(this); // return graph[][] Array

// get max++ row temporary DB maxRowDB();

// GET COORDINATE AWAL DI SEKITAR SIMPUL

// coordinate awal lalu di konversi ke simpul awal // return __global_simpul_awal, __global_graphArray[][] // ==========================================

Get_koordinat_awal_akhir start_coordinate_jalur = new Get_koordinat_awal_akhir();

getSimpulAwalAkhirJalur(start_coordinate_jalur, latUser, lngUser, "awal");

// GET COORDINATE AKHIR DI SEKITAR SIMPUL

// coordinate akhir lalu di konversi ke simpul akhir // return __global_simpul_akhir, __global_graphArray[][] // ==========================================

Get_koordinat_awal_akhir destination_coordinate_jalur = new Get_koordinat_awal_akhir();

getSimpulAwalAkhirJalur(destination_coordinate_jalur, lat_endposition, lng_endposition, "akhir");

// ALGORITMA DIJKSTRA

// ========================================== dijkstra algo = new dijkstra();

algo.jalurTerpendek(__global_graphArray, __global_simpul_awal, __global_simpul_akhir);

// no result for algoritma dijkstra if(algo.status == "die"){

Toast.makeText(getApplicationContext(), "Lokasi Anda sudah dekat dengan lokasi tujuan", Toast.LENGTH_LONG).show();

(37)

// return jalur terpendek; example 1->5->6->7 String[] exp = algo.jalur_terpendek1.split("->");

// DRAW JALUR // ========================================= drawJalur(algo.jalur_terpendek1, exp); } } /* * @fungsi * menggambar jalur

* membuat marker untuk your position dan destination position * @parameter

* exp[] : jalur terpendek; example 1->5->6->7 * @return

* no return */

public void drawJalur(String alg, String[] exp) throws JSONException{ int start = 0;

// GAMBAR JALURNYA

// ======================

dbHelper = new SQLHelper(this);

SQLiteDatabase db = dbHelper.getReadableDatabase(); for(int i = 0; i < exp.length-1; i++){

ArrayList<LatLng> lat_lng = new ArrayList<LatLng>();

cursor = db.rawQuery("SELECT jalur FROM graph where simpul_awal ="+exp[start]+" and simpul_tujuan ="+exp[(++start)], null);

cursor.moveToFirst();

// dapatkan koordinat Lat,Lng dari field koordinat (3) String json = cursor.getString(0).toString();

// get JSON

JSONObject jObject = new JSONObject(json);

JSONArray jArrCoordinates = jObject.getJSONArray("coordinates"); // get coordinate JSON

for(int w = 0; w < jArrCoordinates.length(); w++){

JSONArray latlngs = jArrCoordinates.getJSONArray(w); Double lats = latlngs.getDouble(0);

Double lngs = latlngs.getDouble(1);

(38)

}

// buat rute

PolylineOptions jalurBiasa = new PolylineOptions(); jalurBiasa.addAll(lat_lng).width(5).color(0xff4b9efa).geodesic(true);

googleMap.addPolyline(jalurBiasa); }

// BUAT MARKER UNTUK YOUR POSITION AND DESTINATION POSITION // ====================== // your position googleMap.addMarker(new MarkerOptions() .position(__global_yourCoordinate_exist) .title("Your position") .snippet("Your position") .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));

String[] exp_endCoordinate = __global_endposition.split(","); double lat_endPosition = Double.parseDouble(exp_endCoordinate[0]); double lng_endPosition = Double.parseDouble(exp_endCoordinate[1]); LatLng endx = new LatLng(lat_endPosition, lng_endPosition);

// destination position googleMap.addMarker(new MarkerOptions() .position(endx) .title("Destination position") .snippet("Destination position") .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))); // TENTUKAN // ========================================================== // misal exp[] = 1->5->6->7 int m = 0;

String[] awal = __global_old_simpul_awal.split("-"); // misal 4-5 String[] akhir = __global_old_simpul_akhir.split("-"); // misal 8-7 int ganti_a = 0;

int ganti_b = 0;

int simpulAwalDijkstra = Integer.parseInt(exp[0]); String gabungSimpul_all = "";

Map<String, ArrayList> listAngkutanUmum = new HashMap<String, ArrayList>(); ArrayList<Integer> listSimpulAngkot = new ArrayList<Integer>();

(39)

// misal 4-5 dipecah menjadi 4-6-5, berarti simpul_old awal = 5, simpul_old akhir = 4

for(int e = 0; e < (exp.length - 1); e++){

if(e == 0){ // awal

// dijalankan jika hasil algo hanya 2 simpul, example : 4->5 if(exp.length == 2 /* 2 simpul (4-5)*/){

// ada simpul baru di awal (10) dan di akhir (11), example 10->11

if( exp[0].equals(String.valueOf(__global_maxRow0)) && exp[1].equals(String.valueOf(__global_maxRow1)) ){ if(String.valueOf(__global_maxRow0).equals(akhir[0])){ ganti_b = Integer.parseInt(akhir[1]); }else{ ganti_b = Integer.parseInt(akhir[0]); } if(String.valueOf(ganti_b).equals(awal[0])){ ganti_a = Integer.parseInt(awal[1]); }else{ ganti_a = Integer.parseInt(awal[0]); } } else{

// ada simpul baru di awal (10), example 10->5 // maka cari simpul awal yg oldnya

if( exp[0].equals(String.valueOf(__global_maxRow0)) ){ if(exp[1].equals(awal[1])){ ganti_a = Integer.parseInt(awal[0]); }else{ ganti_a = Integer.parseInt(awal[1]); } ganti_b = Integer.parseInt(exp[1]); }

// ada simpul baru di akhir (10), example 5->10 // maka cari simpul akhir yg oldnya

else if( exp[1].equals(String.valueOf(__global_maxRow0)) ){ if(exp[0].equals(akhir[0])){ ganti_b = Integer.parseInt(akhir[1]); }else{ ganti_b = Integer.parseInt(akhir[0]); } ganti_a = Integer.parseInt(exp[0]); }

// tidak ada penambahan simpul sama sekali

(40)

ganti_a = Integer.parseInt(exp[0]); ganti_b = Integer.parseInt(exp[1]); } } /* // 4 == 4 if(exp[0].equals(awal[0])){ ganti_a = Integer.parseInt(awal[0]); //ganti_b = Integer.parseInt(awal[1]); }else{ ganti_a = Integer.parseInt(awal[1]); //ganti_b = Integer.parseInt(awal[0]); } if(String.valueOf(ganti_a).equals(akhir[0])){ ganti_b = Integer.parseInt(akhir[1]); //ganti_b = Integer.parseInt(awal[1]); }else{ ganti_b = Integer.parseInt(akhir[0]); //ganti_b = Integer.parseInt(awal[0]); } */ /* * // 4 == 4 if(exp[0].equals(awal[0])){ ganti_a = Integer.parseInt(akhir[0]); ganti_b = Integer.parseInt(awal[1]); }else{ ganti_a = Integer.parseInt(awal[1]); ganti_b = Integer.parseInt(akhir[0]); } */ }

// hasil algo lebih dr 2 : 4->5->8->7-> etc .. else{

if(exp[1].equals(awal[1])){ // 5 == 5

ganti_a = Integer.parseInt(awal[0]); // hasil 4 }else{

ganti_a = Integer.parseInt(awal[1]); // hasil 5 }

ganti_b = Integer.parseInt( exp[++m] );

}

}

else if(e == (exp.length - 2)){ // akhir

(41)

if(exp[ (exp.length - 2) ].equals(akhir[1])){ // 7 == 7 ganti_b = Integer.parseInt(akhir[0]); // hasil 8 }else{

ganti_b = Integer.parseInt(akhir[1]); // hasil 7

}

ganti_a = Integer.parseInt( exp[m] );

}else{ // tengah tengah

ganti_a = Integer.parseInt( exp[m] ); ganti_b = Integer.parseInt( exp[++m] ); }

gabungSimpul_all += "," + ganti_a + "-" + ganti_b + ","; // ,1-5, String gabungSimpul = "," + ganti_a + "-" + ganti_b + ","; // ,1-5,

cursor = db.rawQuery("SELECT * FROM angkutan where simpul like '%" + gabungSimpul + "%'", null);

cursor.moveToFirst();

ArrayList<String> listAngkutan = new ArrayList<String>(); for(int ae = 0; ae < cursor.getCount(); ae++){

cursor.moveToPosition(ae); listAngkutan.add( cursor.getString(1).toString() ); } listAngkutanUmum.put("angkutan" + e, listAngkutan); // add simpul listSimpulAngkot.add( Integer.parseInt(exp[e]) ); }

String replace_jalur = gabungSimpul_all.replace(",,", ","); // ,1-5,,5-6,,6-7, => ,1-5,5-6,6-,1-5,,5-6,,6-7,

cursor = db.rawQuery("SELECT * FROM angkutan where simpul like '%" + replace_jalur + "%'", null);

cursor.moveToFirst(); cursor.moveToPosition(0); // ada

if(cursor.getCount() > 0){

String siAngkot = cursor.getString(1).toString(); // get coordinate

cursor = db.rawQuery("SELECT jalur FROM graph where simpul_awal = '" + simpulAwalDijkstra + "'", null);

cursor.moveToFirst();

(42)

// manipulating JSON

JSONObject jObject = new JSONObject(json_coordinate);

JSONArray jArrCoordinates = jObject.getJSONArray("coordinates"); JSONArray latlngs = jArrCoordinates.getJSONArray(0);

// first latlng

Double lats = latlngs.getDouble(0); Double lngs = latlngs.getDouble(1); googleMap.addMarker(new MarkerOptions() .position(new LatLng(lats, lngs)) .title("Angkutan") .snippet(siAngkot) .icon(BitmapDescriptorFactory.fromResource(R.drawable.car))).showInfoWindow(); // die() return; } // ada int banyakAngkot = 0; int indexUrut = 0; int indexSimpulAngkot = 1;

int lengthAngkutan = listAngkutanUmum.size();

Map<String, ArrayList> angkotFix = new HashMap<String, ArrayList>(); for(int en = 0; en < lengthAngkutan; en++ ){

// temporary sementara sebelum di retainAll() ArrayList<String> temps = new ArrayList<String>();

for(int u = 0; u < listAngkutanUmum.get("angkutan0").size(); u++){ temps.add( listAngkutanUmum.get("angkutan0").get(u).toString() ); }

if(en > 0 ){

ArrayList listSekarang1 = listAngkutanUmum.get("angkutan0"); ArrayList listSelanjutnya1 = listAngkutanUmum.get("angkutan" + en); // intersection listSekarang1.retainAll(listSelanjutnya1); if(listSekarang1.size() > 0){ listSimpulAngkot.remove(indexSimpulAngkot); --indexSimpulAngkot; listAngkutanUmum.remove("angkutan" + en); if(en == (lengthAngkutan - 1)){

ArrayList<String> tempDalam = new ArrayList<String>(); for(int es = 0; es < listSekarang1.size(); es++){

(43)

}

angkotFix.put("angkutanFix" + indexUrut, tempDalam); ++indexUrut;

}

}

else if(listSekarang1.size() == 0){

angkotFix.put("angkutanFix" + indexUrut, temps);

ArrayList<String> tempDalam = new ArrayList<String>(); for(int es = 0; es < listSelanjutnya1.size(); es++){

tempDalam.add( listSelanjutnya1.get(es).toString() ); } //if(en == 1) break; listAngkutanUmum.get("angkutan0").clear(); listAngkutanUmum.put("angkutan0", tempDalam); //if(en != (listAngkutanUmum.size() - 1)){ listAngkutanUmum.remove("angkutan" + en); //} ++indexUrut; if(en == (lengthAngkutan - 1)){

ArrayList<String> tempDalam2 = new ArrayList<String>(); for(int es = 0; es < listSelanjutnya1.size(); es++){ tempDalam2.add( listSelanjutnya1.get(es).toString() );

}

angkotFix.put("angkutanFix" + indexUrut, tempDalam2); ++indexUrut; } } ++indexSimpulAngkot; } } for(int r = 0; r < listSimpulAngkot.size(); r++){

String simpulx = listSimpulAngkot.get(r).toString(); // get coordinate simpulAngkutan

cursor = db.rawQuery("SELECT jalur FROM graph where simpul_awal = '" + simpulx + "'", null);

cursor.moveToPosition(0);

// dapatkan koordinat Lat,Lng dari field koordinat (3) String json = cursor.getString(0).toString();

// get JSON

JSONObject jObject = new JSONObject(json);

(44)

// get first coordinate JSON

JSONArray latlngs = jArrCoordinates.getJSONArray(0); Double lats = latlngs.getDouble(0);

Double lngs = latlngs.getDouble(1);

LatLng simpulAngkot = new LatLng(lats, lngs);

String siAngkot = angkotFix.get("angkutanFix" + r).toString(); if(r == 0){ googleMap.addMarker(new MarkerOptions() .position(simpulAngkot) .title("Angkot") .snippet(siAngkot) .icon(BitmapDescriptorFactory.fromResource(R.drawable.car))).showInfoWindow(); }else{ googleMap.addMarker(new MarkerOptions() .position(simpulAngkot) .title("Angkot") .snippet(siAngkot) .icon(BitmapDescriptorFactory.fromResource(R.drawable.car))); } } }

public void getSimpulAwalAkhirJalur(Get_koordinat_awal_akhir objects, double latx, double lngx, String statusObject) throws JSONException{

// return JSON index posisi koordinat, nodes0, nodes1 JSONObject jStart = objects.Get_simpul(latx, lngx, this); // index JSON

String status = jStart.getString("status");

int node_simpul_awal0 = jStart.getInt("node_simpul_awal0"); int node_simpul_awal1 = jStart.getInt("node_simpul_awal1");

int index_coordinate_json = jStart.getInt("index_coordinate_json");

int fix_simpul_awal = 0;

// jika koordinat tepat di atas posisi simpul/node // maka tidak perlu menambahkan simpul baru

if(status.equals("jalur_none")){

//tentukan simpul awal atau akhir yg dekat dgn posisi user if(index_coordinate_json == 0){ // awal fix_simpul_awal = node_simpul_awal0; }else{ // akhir fix_simpul_awal = node_simpul_awal1; } if(statusObject == "awal"){

(45)

// return

__global_old_simpul_awal = node_simpul_awal0 + "-" + node_simpul_awal1;

__global_simpul_awal = fix_simpul_awal; // misal 0 }else{

// return

__global_old_simpul_akhir = node_simpul_awal0 + "-" + node_simpul_awal1;

__global_simpul_akhir = fix_simpul_awal; // misal 0 }

}

// jika koordinat berada diantara simpul 5 dan simpul 4 atau simpul 4 dan simpul 5

// maka perlu menambahkan simpul baru else if(status.equals("jalur_double")){

// return

if(statusObject == "awal"){

// cari simpul (5,4) dan (4-5) di Tambah_simpul.java Tambah_simpul obj_tambah = new Tambah_simpul(); obj_tambah.dobelSimpul(node_simpul_awal0, node_simpul_awal1, index_coordinate_json, this, __global_graphArray, 401 ); // 401 : row id yg baru // return __global_old_simpul_awal = obj_tambah.simpul_lama;

__global_simpul_awal = obj_tambah.simpul_baru; // misal 6 __global_graphArray = obj_tambah.modif_graph; // graph[][] }else{

// cari simpul (5,4) dan (4-5) di Tambah_simpul.java Tambah_simpul obj_tambah = new Tambah_simpul(); obj_tambah.dobelSimpul(node_simpul_awal0, node_simpul_awal1, index_coordinate_json, this, __global_graphArray, 501 ); // 501 : row id yg baru // return __global_old_simpul_akhir = obj_tambah.simpul_lama;

__global_simpul_akhir = obj_tambah.simpul_baru; // misal 4 __global_graphArray = obj_tambah.modif_graph; // graph[][]

(46)

} }

// jika koordinat hanya berada diantara simpul 5 dan simpul 4 // maka perlu menambahkan simpul baru

else if(status.equals("jalur_single")){ if(statusObject == "awal"){

// cari simpul (5,4) di Tambah_simpul.java Tambah_simpul obj_tambah1 = new Tambah_simpul(); obj_tambah1.singleSimpul(node_simpul_awal0, node_simpul_awal1, index_coordinate_json, this, __global_graphArray, 401 ); // 401 : row id yg baru // return __global_old_simpul_awal = obj_tambah1.simpul_lama;

__global_simpul_awal = obj_tambah1.simpul_baru; // misal 6 __global_graphArray = obj_tambah1.modif_graph; //

graph[][]

}else{

// cari simpul (5,4) di Tambah_simpul.java Tambah_simpul obj_tambah1 = new Tambah_simpul(); obj_tambah1.singleSimpul(node_simpul_awal0, node_simpul_awal1, index_coordinate_json, this, __global_graphArray, 501 ); // 501 : row id yg baru // return __global_old_simpul_akhir = obj_tambah1.simpul_lama; __global_simpul_akhir = obj_tambah1.simpul_baru; // misal 4 __global_graphArray = obj_tambah1.modif_graph; // graph[][] } } } /* * @fungsi

* delete temporary record DB

* (temporary ini digunakan untuk menampung sementara simpul baru) * @parameter

* no parameter * @return * no returen */

(47)

public void deleteTemporaryRecord(){ // delete DB

final SQLiteDatabase dbDelete = dbHelper.getWritableDatabase(); // delete temporary record DB

for(int i = 0; i < 4; i++){

//hapus simpul awal tambahan, mulai dr id 401,402,403,404 String deleteQuery_ = "DELETE FROM graph where id ='"+ (401+i) +"'";

dbDelete.execSQL(deleteQuery_);

//hapus simpul tujuan tambahan, mulai dr id 501,502,503,504 String deleteQuery = "DELETE FROM graph where id ='"+ (501+i) +"'";

dbDelete.execSQL(deleteQuery); }

}

public void maxRowDB(){

dbHelper = new SQLHelper(this);

SQLiteDatabase dbRead = dbHelper.getReadableDatabase();

cursor = dbRead.rawQuery("SELECT max(simpul_awal), max(simpul_tujuan) FROM graph", null);

cursor.moveToFirst(); int max_simpul_db = 0; int max_simpulAwal_db = Integer.parseInt(cursor.getString(0).toString()); int max_simpulTujuan_db = Integer.parseInt(cursor.getString(1).toString()); if(max_simpulAwal_db >= max_simpulTujuan_db){ max_simpul_db = max_simpulAwal_db; }else{ max_simpul_db = max_simpulTujuan_db; } // return __global_maxRow0 = (max_simpul_db+1); __global_maxRow1 = (max_simpul_db+2); } } package com.app.dijkstra; import java.io.FileOutputStream;

(48)

import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import android.widget.Toast; //http://cariprogram.blogspot.com

public class SQLHelper extends SQLiteOpenHelper{

private static final String DATABASE_NAME = "schoolnav.sqlite"; private static final int DATABASE_VERSION = 1;

private static String DB_PATH = "/data/data/com.app.dijkstra/databases/"; private Context myContext;

public SQLHelper(Context context) {

super(context, DATABASE_NAME, null, DATABASE_VERSION); // TODO Auto-generated constructor stub

myContext=context; }

(49)

public void createDataBase() throws IOException{ if(DataBaseisExist()){

//do nothing - database already exist

Toast.makeText(myContext, "Database Sudah Ada", Toast.LENGTH_LONG).show();

}

else{

//By calling this method and empty database will be created into the default system path

//of your application so we are gonna be able to overwrite that database with our database. this.getReadableDatabase();

try {

copyDataBase();

Toast.makeText(myContext, "Database Berhasil Diimport Dari Assets", Toast.LENGTH_LONG).show();

} catch (IOException e) {

throw new Error("Error copying database"); }

}

}

private boolean DataBaseisExist(){ SQLiteDatabase checkDB = null; try{

(50)

String myPath = DB_PATH + DATABASE_NAME;

checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

}catch(SQLiteException e){

//database does't exist yet. }

if(checkDB != null){

checkDB.close();

}

if(checkDB != null )return true ;else return false; }

private void copyDataBase() throws IOException{ //Open your local db as the input stream

InputStream myInput = myContext.getAssets().open(DATABASE_NAME); // Path to the just created empty db

String outFileName = DB_PATH + DATABASE_NAME; //Open the empty db as the output stream

OutputStream myOutput = new FileOutputStream(outFileName); //transfer bytes from the inputfile to the outputfile

byte[] buffer = new byte[1024]; int length;

while ((length = myInput.read(buffer))>0){ myOutput.write(buffer, 0, length); }

(51)

//Close the streams myOutput.flush(); myOutput.close(); myInput.close(); } @Override

public void onCreate(SQLiteDatabase db) {

}

@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub

} } package com.app.dijkstra; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;

(52)

import android.content.ContentValues; import android.content.Context; import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase; import android.location.Location;

public class Tambah_simpul{

protected Cursor cursor; SQLHelper dbHelper;

String[][] modif_graph = new String[100][100]; String simpul_lama = "";

int simpul_baru;

String simpul_tujuan_ = "";

/*

* @fungsi

* meyisipkan simpul baru

* misal simpul 5-4, disisipkan menjadi 5-6-4 * dan simpul 4-5, disisipkan menjadi 4-6-5 * @parameter

(53)

* nodes0 : misal {"nodes": "5-4"} maka nodes_awal0 = 5 * nodes1 : misal {"nodes": "5-4"} maka nodes_awal1 = 4 * index_koordinat_json : index array koordinat di JSON * context : MainActivity.context

* graph[][] : array untuk menampung graph dari DB

* example output : graph[5][0] = 4->439.281

* graph[6][0] = 1->216.281

* increase_row_id : row id DB yg baru * @return

* simpul_lama = nodes0 + "-" + nodes1 * simpul_baru = simpul awal

* graph[][] */

public void dobelSimpul(int nodes0, int nodes1,

int index_koordinat_json, Context context, String[][] graph, int increase_row_id ) throws JSONException{

// read DB

SQLHelper dbHelper = new SQLHelper(context);

SQLiteDatabase dbRead = dbHelper.getReadableDatabase();

//buat insert ke DB

(54)

// HITUNG SIMPUL YANG ASLI DULU (5-4), BUKAN YANG DOBEL (4-5)

//============================================================== String index_kolom_graph = "";

// cari index kolomnya nodes1 (4) dari graph[baris][index kolom] for(int l = 0; l < 100; l++){

if(graph[nodes0][l] != null){

String simpulAwal = graph[nodes0][l]; // [5][0] = 4->721.666

// 4->721.666

String [] explode = simpulAwal.split("->");

simpul_tujuan_ = explode[0]; // 4

// jika 4 == 4 (node1)

if(simpul_tujuan_.trim().equals( String.valueOf(nodes1).trim()) ){

// index kolom; example graph[baris][kolom] index_kolom_graph = String.valueOf(l); }

(55)

}// for

// index dari graph[baris][kolom] yang akan di edit int baris = nodes0;

int kolom = Integer.parseInt(index_kolom_graph);

// ambil koordinatnya dari simpul 5-4

cursor = dbInsert.rawQuery("SELECT jalur FROM graph where simpul_awal = "+ nodes0 +" and simpul_tujuan = "+ nodes1, null);

cursor.moveToFirst(); cursor.moveToPosition(0);

// --

// get coordinates JSON

String json_coordinates = cursor.getString(0).toString(); JSONObject jObject = new JSONObject(json_coordinates);

JSONArray jArrCoordinates = jObject.getJSONArray("coordinates"); // --

// cari maksimal simpul, (buat penomoran simpul baru)

cursor = dbRead.rawQuery("SELECT max(simpul_awal), max(simpul_tujuan) FROM graph", null);

cursor.moveToFirst();

int max_simpul_db = 0;

(56)

int max_simpulTujuan_db = Integer.parseInt(cursor.getString(1).toString()); if(max_simpulAwal_db >= max_simpulTujuan_db){ max_simpul_db = max_simpulAwal_db; }else{ max_simpul_db = max_simpulTujuan_db; }

// pecah koordinat dari AWAL->TENGAH int limit = index_koordinat_json;

Count_Bobot_Tambah_Simpul ct = new Count_Bobot_Tambah_Simpul();

ct.Count_Bobot_Tambah_Simpul(0, limit, jArrCoordinates); // 0, koordinat tengah, jSON coordinates

//replace array graph[5][0] = 6->888.6

graph[baris][kolom] = (max_simpul_db+1)+"->"+ct.bobot;

int start_loop = 0;

// buat dan simpan (new record) json koordinat yang baru ke DB

createAndSave_NewJsonCoordinate(start_loop, limit, jArrCoordinates, increase_row_id, baris, (max_simpul_db + 1), ct.bobot,

dbInsert, dbRead); // 501 : index record baru

// reset bobot ct.bobot = 0;

(57)

// pecah koordinat dari TENGAH->AKHIR int start_loop1 = index_koordinat_json;

int limit1 = (jArrCoordinates.length() - 1); // - 1 karena array mulai dari 0

ct.Count_Bobot_Tambah_Simpul(index_koordinat_json, limit1, jArrCoordinates); // coordinate tengah sampai akhir

// new array graph[6][0] = 4->777.4

graph[(max_simpul_db+1)][0] = nodes1 + "->" + ct.bobot; //didefinisikan [0] karena index baru di graph[][]

// buat dan simpan (new record) json koordinate yang baru ke DB createAndSave_NewJsonCoordinate(start_loop1, limit1, jArrCoordinates, ++increase_row_id, (max_simpul_db + 1), nodes1, ct.bobot,

dbInsert, dbRead); // 502 : index record baru

// reset bobot ct.bobot = 0;

// HITUNG SIMPUL YANG DOBEL (4-5), BUKAN YANG ASLI (5-4)

(58)

String index_kolom_graph1 = ""; String nodes_inside_kolom = "";

// dibalik, nodes0 jadi nodes1; example (5-4) jadi (4-5) int t_nodes0 = nodes1; // 4

int t_nodes1 = nodes0; // 5

// cari index kolomnya dari graph[4][index kolomnya] for(int l = 0; l < 100; l++){

if(graph[t_nodes0][l] != null){

// == dapatkan simpul tujuan, example : 5->9585.340 String simpulAwal = graph[t_nodes0][l];

String [] explode1 = simpulAwal.split("->");

nodes_inside_kolom = explode1[0]; if(nodes_inside_kolom.trim().equals( String.valueOf(t_nodes1)) ){ index_kolom_graph1 = String.valueOf(l); } }else break; }//for

(59)

// index dari graph[baris1][kolom1] yang akan di edit int baris1 = t_nodes0;

int kolom1 = Integer.parseInt(index_kolom_graph1);

// ambil koordinatnya dari simpul 4-5

cursor = dbRead.rawQuery("SELECT jalur FROM graph where simpul_awal = "+t_nodes0+" and simpul_tujuan = "+t_nodes1, null);

cursor.moveToFirst(); cursor.moveToPosition(0);

// --

// get coordinates JSON from DB

String json1 = cursor.getString(0).toString(); JSONObject jObject1 = new JSONObject(json1);

JSONArray jArrCoordinates1 = jObject1.getJSONArray("coordinates"); // --

// pecah koordinat dari AWAL->TENGAH

int index_dobel_koordinat_json = ( (jArrCoordinates1.length()-1) - index_koordinat_json );

ct.Count_Bobot_Tambah_Simpul(0, index_dobel_koordinat_json, jArrCoordinates1); // 0, koordinat awal ke tengah, JSONArray coordinate

//replace array graph[4][0] = 6->777.4

(60)

// buat dan simpan (new record) json koordinate yang baru ke DB int start_loop2 = 0;

createAndSave_NewJsonCoordinate(start_loop2, index_dobel_koordinat_json, jArrCoordinates1, ++increase_row_id, baris1, (max_simpul_db + 1), ct.bobot,

dbInsert, dbRead); // 503 : index record baru

// reset bobot ct.bobot = 0;

// pecah koordinat dari TENGAH->AKHIR

int limit2 = (jArrCoordinates1.length() - 1); // - 1 karena array mulai dari 0 ct.Count_Bobot_Tambah_Simpul(index_dobel_koordinat_json, limit2, jArrCoordinates1); // koordinat tengah sampai akhir

//replace array graph[6][1] = 5->888.6

graph[(max_simpul_db+1)][1] = t_nodes1+"->"+ct.bobot; // didefinisikan [1] karena sdh ada index 0 di graph[][]

// buat dan simpan (new record) json koordinate yang baru ke DB createAndSave_NewJsonCoordinate(index_dobel_koordinat_json, limit2, jArrCoordinates1, ++increase_row_id, (max_simpul_db + 1), t_nodes1, ct.bobot,

dbInsert, dbRead); // 503 : index record baru

(61)

// return

simpul_lama = nodes0 + "-" + nodes1; simpul_baru = (max_simpul_db + 1); modif_graph = graph; // graph[][]

}// public void dobelSimpul

/*

* @fungsi

* meyisipkan simpul baru

* misal simpul 5-4, disisipkan menjadi 5-6-4 * @parameter

* nodes_awal0 : misal {"nodes": "5-4"} maka nodes_awal0 = 5 * nodes_awal1 : misal {"nodes": "5-4"} maka nodes_awal1 = 4 * index_koordinat_json : index array koordinat di JSON * context : MainActivity.context

* graph[][] : array untuk menampung graph dari DB

* example output : graph[5][0] = 4->439.281

* graph[6][0] = 1->216.281

* increase_row_id : row id DB yg baru * @return

(62)

* simpul_baru : simpul akhir * graph[][]

*/

public void singleSimpul(int nodes0, int nodes1, int index_koordinat_json,

Context context, String[][] graph, int increase_row_id) throws JSONException{

// read DB

SQLHelper dbHelper = new SQLHelper(context);

SQLiteDatabase dbRead = dbHelper.getReadableDatabase();

//buat insert ke DB

SQLiteDatabase dbInsert = dbHelper.getWritableDatabase();

// HITUNG SIMPUL YANG ASLI (5-4)

//==============================================================

String index_kolom_graph = "";

// cari index kolomnya nodes_akhir1 (4) dari graph[baris][kolom] for(int l = 0; l < 100; l++){

if(graph[nodes0][l] != null){

(63)

String [] explode = simpulAwal.split("->");

// 6->721.666

String value_node_array = explode[0];

// jika 4 == 4 (node_akhir1)

if( value_node_array.trim().equals(String.valueOf(nodes1).trim()) ){

// index kolom; example graph[baris][kolom] index_kolom_graph = String.valueOf(l); }

}else break; }//for

// index dari graph[baris][kolom] yang akan di edit int baris = nodes0;

int kolom = Integer.parseInt(index_kolom_graph);

//ambil koordinatnya dari simpul 3-6

cursor = dbRead.rawQuery("SELECT jalur FROM graph where simpul_awal = "+nodes0+" and simpul_tujuan = "+nodes1, null);

cursor.moveToFirst(); cursor.moveToPosition(0);

(64)

// --

// get coordinates JSON

String json_coordinates = cursor.getString(0).toString(); JSONObject jObject = new JSONObject(json_coordinates);

JSONArray jArrCoordinates = jObject.getJSONArray("coordinates"); // --

// cari maksimal simpul, (buat penomoran simpul baru)

cursor = dbRead.rawQuery("SELECT max(simpul_awal) FROM graph", null); cursor.moveToFirst();

int max_simpul_db = Integer.parseInt(cursor.getString(0).toString());

// pecah koordinat dari AWAL->TENGAH System.out.println("single awal->tengah"); int limit = index_koordinat_json;

Count_Bobot_Tambah_Simpul ct = new Count_Bobot_Tambah_Simpul();

ct.Count_Bobot_Tambah_Simpul(0, limit, jArrCoordinates); // 0, koordinat tengah, jSON coordinates

//replace array graph[5][0] = 6->888.6

graph[baris][kolom] = (max_simpul_db+1)+"->"+ct.bobot;

(65)

// buat dan simpan (new record) json koordinat yang baru ke DB

createAndSave_NewJsonCoordinate(start_loop, limit, jArrCoordinates, increase_row_id, baris, (max_simpul_db + 1), ct.bobot,

dbInsert, dbRead); // 501 : index record baru

// reset bobot ct.bobot = 0;

// pecah koordinat dari TENGAH->AKHIR

int start_loop1 = index_koordinat_json; // - 1 karena array mulai dari 0 int limit1 = (jArrCoordinates.length() - 1); // - 1 karena array mulai dari 0

ct.Count_Bobot_Tambah_Simpul(index_koordinat_json, limit1, jArrCoordinates); // coordinate tengah sampai akhir

// new array graph[6][0] = 4->777.4

graph[(max_simpul_db+1)][0] = nodes1 + "->" + ct.bobot; //didefinisikan [0] karena index baru di graph[][]

// buat dan simpan (new record) json koordinate yang baru ke DB createAndSave_NewJsonCoordinate(start_loop1, limit1, jArrCoordinates, ++increase_row_id, (max_simpul_db + 1), nodes1, ct.bobot,

dbInsert, dbRead); // 502 : index record baru

(66)

// return

simpul_lama = nodes0 + "-" + nodes1; simpul_baru = (max_simpul_db + 1); modif_graph = graph; // graph[][] }

/* @fungsi

* Membuat dan menyimpan coordinates baru dalam bentuk JSON ke DB * @parameter

* mulai : mulai looping, misal 0

* limit : index array koordinat, misal i[7] maka limit = 7 * jArrCoordinates : Koordinat dari DB dalam bentuk JSONArray * new_id : id record baru

* //baris : baris multidimensi array, misal i[baris][kolom] * //max_simpul_db : jumlah max record pada tabel graph * new_bobot : bobot baru dari pemecahan koordinat jalur * dbInsert : insert ke database

* dbRead : baca record database * @return

* no return */

public void createAndSave_NewJsonCoordinate(int mulai, int limit, JSONArray jArrCoordinates,

(67)

SQLiteDatabase dbInsert, SQLiteDatabase dbRead) throws JSONException{

// JSON for save new coordinate

JSONObject json_baru = new JSONObject();

JSONArray new_root_coordinates = new JSONArray();

// looping dari coordinate awal sampai ke coordinate tengah // atau

// looping dari coordinate tengah sampai ke coordinate akhir // then, move old coordinate to new coordinate

for(int ne = mulai; ne <= limit; ne++){

JSONArray latlng = jArrCoordinates.getJSONArray(ne); double new_lat = latlng.getDouble(0);

double new_lng = latlng.getDouble(1);

JSONArray new_list_coordinates = new JSONArray(); new_list_coordinates.put(new_lat);

new_list_coordinates.put(new_lng);

// coordinates

new_root_coordinates.put(new_list_coordinates); }

(68)

// nodes

JSONArray nodes = new JSONArray();

String gabung_nodes = String.valueOf(field_simpul_awal) + '-' + String.valueOf(field_simpul_akhir);

nodes.put(gabung_nodes);

// distance_metres

JSONArray distance_metres = new JSONArray(); distance_metres.put(new_bobot);

// create new JSON

json_baru.put("nodes", nodes);

json_baru.put("coordinates", new_root_coordinates); json_baru.put("distance_metres", distance_metres);

String jalur_baru = json_baru.toString(); System.out.println(jalur_baru);

// INSERT SIMPUUUUUULL BARU

ContentValues newCon = new ContentValues(); newCon.put("id", new_id);

newCon.put("simpul_awal", field_simpul_awal); newCon.put("simpul_tujuan", field_simpul_akhir); newCon.put("jalur", jalur_baru);

(69)

dbInsert.insert("graph", null, newCon);

} }

(70)
(71)

Referensi

Dokumen terkait