Advertisement
Guest User

Untitled

a guest
Jul 1st, 2016
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.75 KB | None | 0 0
  1. package com.acer.app_kampus;
  2.  
  3. import android.*;
  4. import android.app.ProgressDialog;
  5. import android.content.Context;
  6. import android.content.DialogInterface;
  7. import android.content.Intent;
  8. import android.content.pm.PackageManager;
  9. import android.graphics.Color;
  10. import android.net.ConnectivityManager;
  11. import android.net.NetworkInfo;
  12. import android.net.wifi.WifiManager;
  13. import android.provider.Settings;
  14. import android.support.annotation.Nullable;
  15. import android.support.v4.app.ActivityCompat;
  16. import android.support.v4.app.Fragment;
  17. import android.support.v4.app.FragmentTransaction;
  18. import android.support.v7.app.AlertDialog;
  19. import android.os.Bundle;
  20. import android.view.LayoutInflater;
  21. import android.view.View;
  22. import android.view.ViewGroup;
  23. import android.widget.AdapterView;
  24. import android.widget.AdapterView.OnItemSelectedListener;
  25. import android.widget.ArrayAdapter;
  26. import android.widget.Button;
  27. import android.widget.EditText;
  28. import android.widget.Spinner;
  29. import android.widget.TextView;
  30. import android.widget.Toast;
  31.  
  32. import com.acer.app_kampus.koneksi.config;
  33. import com.acer.app_kampus.modules.DirectionFinder;
  34. import com.acer.app_kampus.modules.DirectionFinderListener;
  35. import com.acer.app_kampus.modules.GPSTracker;
  36. import com.acer.app_kampus.modules.Route;
  37. import com.android.volley.RequestQueue;
  38. import com.android.volley.Response;
  39. import com.android.volley.VolleyError;
  40. import com.android.volley.toolbox.JsonArrayRequest;
  41. import com.android.volley.toolbox.JsonObjectRequest;
  42. import com.android.volley.toolbox.StringRequest;
  43. import com.android.volley.toolbox.Volley;
  44. import com.google.android.gms.common.ConnectionResult;
  45. import com.google.android.gms.common.api.GoogleApiClient;
  46. import com.google.android.gms.maps.CameraUpdateFactory;
  47. import com.google.android.gms.maps.GoogleMap;
  48. import com.google.android.gms.maps.MapFragment;
  49. import com.google.android.gms.maps.OnMapReadyCallback;
  50. import com.google.android.gms.maps.model.BitmapDescriptorFactory;
  51. import com.google.android.gms.maps.model.Marker;
  52. import com.google.android.gms.maps.model.MarkerOptions;
  53. import com.google.android.gms.maps.model.Polyline;
  54. import com.google.android.gms.maps.model.PolylineOptions;
  55.  
  56. import org.json.JSONArray;
  57. import org.json.JSONException;
  58. import org.json.JSONObject;
  59.  
  60. import java.io.UnsupportedEncodingException;
  61. import java.util.ArrayList;
  62. import java.util.List;
  63.  
  64. public class cari_kampus extends Fragment implements OnMapReadyCallback, DirectionFinderListener,GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks{
  65. private GoogleMap mMap;
  66. private Button btnFindPath;
  67. private EditText etOrigin;
  68. private Spinner etDestination;
  69. private List<Marker> originMarkers = new ArrayList<>();
  70. private List<Marker> destinationMarkers = new ArrayList<>();
  71. private List<Polyline> polylinePaths = new ArrayList<>();
  72. private ProgressDialog progressDialog;
  73. private ArrayList<String> kampus;
  74. private JSONArray result;
  75.  
  76. RequestQueue RequestQueue;
  77. GPSTracker gpsx;
  78. private WifiManager wfm;
  79. private ConnectivityManager cntm;
  80.  
  81. @Override
  82. public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  83. View v = inflater.inflate(R.layout.activity_cari_kampus,container,false);
  84. MapFragment mFragmentMap = MapFragment.newInstance();
  85. android.app.FragmentTransaction mTranscation = getActivity().getFragmentManager().beginTransaction();
  86. mTranscation.add(R.id.map,mFragmentMap);
  87. mTranscation.commit();
  88. mFragmentMap.getMapAsync(this);
  89.  
  90. kampus = new ArrayList<String>();
  91. String list[] = {"Universitas Negeri Malang (UM)","Universitas Islam Negeri Maulana Malik Ibrahim (UIN)",
  92. "Universitas Brawijaya (UB)","Universitas Muhammadiyah Malang (UMM)","Universitas Merdeka Malang (Unmer)",
  93. "UPBJJ Universitas Terbuka Malang","Universitas Gajayana (Uniga)","Universitas Islam Malang (Unisma)",
  94. "Universitas Kanjuruhan Malang (Unikama)","Universitas Wisnuwardhana (Unidha)","Universitas Widyagama (UWG)",
  95. "Universitas Ma Chung","Universitas Kristen Cipta Wacana (UKCW)","Universitas Katolik Widya Karya",
  96. "Universitas Tribhuwana Tunggadewi (Unitri)",};
  97.  
  98. RequestQueue = Volley.newRequestQueue(getActivity());
  99. btnFindPath = (Button) v.findViewById(R.id.btnFindPath);
  100. etOrigin = (EditText) v.findViewById(R.id.etOrigin);
  101. etDestination = (Spinner) v.findViewById(R.id.etDestination);
  102. ArrayAdapter<String> AdapterList = new ArrayAdapter<String>(getContext(),
  103. android.R.layout.simple_spinner_dropdown_item,list);
  104. etDestination.setAdapter(AdapterList);
  105.  
  106. if(!network()){
  107. createNetErrorDialog();
  108. }
  109. else{
  110. LocationToAddress();
  111. }
  112.  
  113. btnFindPath.setOnClickListener(new View.OnClickListener() {
  114. @Override
  115. public void onClick(View v) {
  116. sendRequest();
  117. }
  118. });
  119. //getData();
  120. return v;
  121. }
  122.  
  123. private void getData(){
  124. //Creating a string request
  125. StringRequest stringRequest = new StringRequest(config.SPINER,
  126. new Response.Listener<String>() {
  127. @Override
  128. public void onResponse(String response) {
  129. JSONObject j = null;
  130. try {
  131. //Parsing the fetched Json String to JSON Object
  132. j = new JSONObject(response);
  133.  
  134. //Storing the Array of JSON String to our JSON Array
  135. result = j.getJSONArray(config.JSON_ARRAY);
  136.  
  137. //Calling method getStudents to get the students from the JSON Array
  138. getStudents(result);
  139. } catch (JSONException e) {
  140. e.printStackTrace();
  141. }
  142. }
  143. },
  144. new Response.ErrorListener() {
  145. @Override
  146. public void onErrorResponse(VolleyError error) {
  147.  
  148. }
  149. });
  150.  
  151. //Creating a request queue
  152. RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
  153.  
  154. //Adding request to the queue
  155. requestQueue.add(stringRequest);
  156. }
  157.  
  158. private void getStudents(JSONArray j){
  159. //Traversing through all the items in the json array
  160. for(int i=0;i<j.length();i++){
  161. try {
  162. //Getting json object
  163. JSONObject json = j.getJSONObject(i);
  164.  
  165. //Adding the name of the student to array list
  166. kampus.add(json.getString(config.KEY_NAMA_KAMPUS));
  167. } catch (JSONException e) {
  168. e.printStackTrace();
  169. }
  170. }
  171.  
  172. //Setting adapter to show the items in the spinner
  173. etDestination.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, kampus));
  174. }
  175.  
  176. private void sendRequest() {
  177. String origin = etOrigin.getText().toString();
  178. String destination = etDestination.getSelectedItem().toString();
  179. if (origin.isEmpty()) {
  180. Toast.makeText(getActivity(), "Please enter origin address!", Toast.LENGTH_SHORT).show();
  181. return;
  182. }
  183. if (destination.isEmpty()) {
  184. Toast.makeText(getActivity(), "Please enter destination address!", Toast.LENGTH_SHORT).show();
  185. return;
  186. }
  187.  
  188. try {
  189. new DirectionFinder(this, origin, destination).execute();
  190. } catch (UnsupportedEncodingException e) {
  191. e.printStackTrace();
  192. }
  193. }
  194.  
  195. @Override
  196. public void onMapReady(GoogleMap googleMap) {
  197. mMap = googleMap;
  198.  
  199. if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  200. // TODO: Consider calling
  201. return;
  202. }
  203. mMap.setMyLocationEnabled(true);
  204. }
  205.  
  206.  
  207. @Override
  208. public void onDirectionFinderStart() {
  209. progressDialog = ProgressDialog.show(getActivity(), "Please wait.",
  210. "Finding direction..!", true);
  211.  
  212. if (originMarkers != null) {
  213. for (Marker marker : originMarkers) {
  214. marker.remove();
  215. }
  216. }
  217.  
  218. if (destinationMarkers != null) {
  219. for (Marker marker : destinationMarkers) {
  220. marker.remove();
  221. }
  222. }
  223.  
  224. if (polylinePaths != null) {
  225. for (Polyline polyline:polylinePaths ) {
  226. polyline.remove();
  227. }
  228. }
  229. }
  230.  
  231. @Override
  232. public void onDirectionFinderSuccess(List<Route> routes) {
  233. progressDialog.dismiss();
  234. polylinePaths = new ArrayList<>();
  235. originMarkers = new ArrayList<>();
  236. destinationMarkers = new ArrayList<>();
  237.  
  238. for (Route route : routes) {
  239. mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(route.startLocation, 16));
  240. ((TextView) getActivity().findViewById(R.id.tvDuration)).setText(route.duration.text);
  241. ((TextView) getActivity().findViewById(R.id.tvDistance)).setText(route.distance.text);
  242.  
  243. originMarkers.add(mMap.addMarker(new MarkerOptions()
  244. .icon(BitmapDescriptorFactory.fromResource(R.drawable.start_blue))
  245. .title(route.startAddress)
  246. .position(route.startLocation)));
  247. destinationMarkers.add(mMap.addMarker(new MarkerOptions()
  248. .icon(BitmapDescriptorFactory.fromResource(R.drawable.end_green))
  249. .title(route.endAddress)
  250. .position(route.endLocation)));
  251.  
  252. PolylineOptions polylineOptions = new PolylineOptions().
  253. geodesic(true).
  254. color(Color.BLUE).
  255. width(10);
  256.  
  257. for (int i = 0; i < route.points.size(); i++)
  258. polylineOptions.add(route.points.get(i));
  259.  
  260. polylinePaths.add(mMap.addPolyline(polylineOptions));
  261. }
  262. }
  263.  
  264. @Override
  265. public void onConnected(Bundle bundle) {
  266.  
  267. }
  268.  
  269. @Override
  270. public void onConnectionSuspended(int i) {
  271.  
  272. }
  273.  
  274. @Override
  275. public void onConnectionFailed(ConnectionResult connectionResult) {
  276.  
  277. }
  278.  
  279. public boolean network() {
  280.  
  281. //Get the wifi service of device
  282. wfm = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
  283. //Get the Mobile Dtata service of device
  284. cntm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
  285.  
  286. final NetworkInfo nInfo = cntm.getActiveNetworkInfo();
  287.  
  288. if ((wfm.isWifiEnabled()) || (nInfo != null && nInfo.isConnected())) {
  289. return true;
  290. }
  291.  
  292. else{
  293. return false;
  294. }
  295.  
  296. }
  297.  
  298. protected void createNetErrorDialog() {
  299.  
  300.  
  301. AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
  302. builder.setMessage("You need a network connection to use this application. Please turn on mobile network or Wi-Fi in Settings.")
  303. .setTitle("Unable to connect")
  304. .setCancelable(false)
  305. .setPositiveButton("Enable",
  306. new DialogInterface.OnClickListener() {
  307. public void onClick(DialogInterface dialog, int id) {
  308. Intent i = new Intent(Settings.ACTION_SETTINGS);
  309.  
  310. //startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
  311.  
  312. startActivity(i);
  313. //finish();
  314. }
  315. }
  316. ) .setNegativeButton("Cancel",
  317. new DialogInterface.OnClickListener() {
  318. public void onClick(DialogInterface dialog, int id) {
  319. getActivity().finish();
  320. }
  321. }
  322. )
  323.  
  324. ;
  325. AlertDialog alert = builder.create();
  326. alert.show();
  327. }
  328.  
  329. public void LocationToAddress(){
  330.  
  331. //
  332. gpsx = new GPSTracker(cari_kampus.this.getActivity());
  333.  
  334.  
  335. double lat = gpsx.getLatitude();
  336. double longt = gpsx.getLongitude();
  337.  
  338. final String lattadd = String.valueOf(lat);
  339. final String logtadd = String.valueOf(longt);
  340.  
  341.  
  342. // JsonObjectRequest request = new JsonObjectRequest("https://maps.googleapis.com/maps/api/geocode/json?latlng=23.781522,"90.3704991&key=AIzaSyBma_A78YGbZwGav3SR3vSGoAXka8FGFzQ", new Response.Listener<JSONObject>() {
  343.  
  344. JsonObjectRequest request = new JsonObjectRequest("https://maps.googleapis.com/maps/api/geocode/json?latlng="+lattadd+","+logtadd+"&key=AIzaSyBma_A78YGbZwGav3SR3vSGoAXka8FGFzQ", new Response.Listener<JSONObject>() {
  345. @Override
  346. public void onResponse(JSONObject response) {
  347.  
  348. try {
  349. String getaddress = response.getJSONArray("results").getJSONObject(0).getString("formatted_address");
  350. etOrigin.setText(getaddress);
  351. } catch (JSONException e) {
  352. e.printStackTrace();
  353. }
  354.  
  355. }
  356. }, new Response.ErrorListener() {
  357. @Override
  358. public void onErrorResponse(VolleyError error) {
  359.  
  360. }
  361. });
  362. RequestQueue.add(request);
  363. }
  364. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement