Selasa, 15 Agustus 2017

Map Marker Database +Timertask

package com.secure.appanak;





import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class mapanak extends FragmentActivity{
String ip="";
JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
JSONArray myJSON = null;
LocationManager locationManager;
private static final String TAG_SUKSES = "sukses";
private static final String TAG_record = "record";

private static final String TAG_kd_anak = "kd_anak";
private static final String TAG_tgl = "tgl";
private static final String TAG_jam = "jam";
private static final String TAG_latitude = "latitude";
private static final String TAG_longitude = "longitude";
private static final String TAG_lokasi = "lokasi";
private static final String TAG_status= "status_monitoring";


int jd=1;
String[]arkd_anak;
String[]artgl;
String[]arjam;
String[]arlati;
String[]arlongi;
String[]arlokasi;
String[]arstatus;

private GoogleMap map;

Timer timer;
TimerTask timerTask;

final Handler handler = new Handler();
String myLati="-6.354167";
String myLongi="106.843761";
String myPosisi="Tugu, Cimanggis, Kota Depok, Jawa Barat(default)";
String kd_user,kd_anak;
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.maps);
ip=jParser.getIP();

   Intent i = getIntent();
kd_anak = i.getStringExtra("kd_anak");
kd_user= i.getStringExtra("kd_user");
// myLati= i.getStringExtra("myLati");
// myLongi= i.getStringExtra("myLongi");
// myPosisi= i.getStringExtra("myPosisi");





String context = Context.LOCATION_SERVICE;
     locationManager = (LocationManager)getSystemService(context);

     Criteria criteria = new Criteria();
     criteria.setAccuracy(Criteria.ACCURACY_FINE);
     criteria.setAltitudeRequired(false);
     criteria.setBearingRequired(false);
     criteria.setCostAllowed(true);
     criteria.setPowerRequirement(Criteria.POWER_LOW);
     String provider = locationManager.getBestProvider(criteria, true);

     Location location = locationManager.getLastKnownLocation(provider);
     updateWithNewLocation(location);

     locationManager.requestLocationUpdates(provider, 5000, 10,locationListener);
   
//     TextView  txtMarquee=(TextView)findViewById(R.id.txtMarquee);
//     txtMarquee.setSelected(true);
//     String kata="Posisi Anda :"+myLati+"/"+myLongi+" "+myPosisi+"#";
//     String kalimat=String.format("%1$s",TextUtils.htmlEncode(kata));
//     txtMarquee.setText(Html.fromHtml(kalimat+kalimat+kalimat));
  new load().execute();
   }


   private final LocationListener locationListener = new LocationListener() {
     @Override
public void onLocationChanged(Location location) {
       updateWithNewLocation(location);
     }
 
     @Override
public void onProviderDisabled(String provider){
       updateWithNewLocation(null);
     }

     @Override
public void onProviderEnabled(String provider){ }
     @Override
public void onStatusChanged(String provider, int status, Bundle extras){ }
   };

 
   private void updateWithNewLocation(Location location) {
     String latLongString;
     double latitude=Double.parseDouble(myLati);
     double longitude=Double.parseDouble(myLongi);
   
     String addressString = "default";

     if (location != null) {
         latitude = location.getLatitude();
         longitude = location.getLongitude();
      myLati=String.valueOf(latitude);
      myLongi=String.valueOf(longitude);
     
       latLongString = "Lat:" + latitude + "\nLong:" + longitude;
       Geocoder gc = new Geocoder(this, Locale.getDefault());
       try {
         List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
         StringBuilder sb = new StringBuilder();
         if (addresses.size() > 0) {
           Address address = addresses.get(0);

           for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
             sb.append(address.getAddressLine(i)).append("\n");
             sb.append(address.getLocality()).append("\n");
             sb.append(address.getPostalCode()).append("\n");
             sb.append(address.getCountryName());
         }
         addressString = sb.toString();
       } catch (IOException e) {}
     } else {
      myLati="-6.354167";
      myLongi="106.843761";
      latLongString="Default Address";
     }

     myPosisi=addressString;
     myLati=String.valueOf(latitude);
     myLongi=String.valueOf(longitude);
   
   
 
 }

 

    protected void onResume() {
        super.onResume();
        startTimer();
    }
    public void startTimer() {
        timer = new Timer();
        initializeTimerTask();
        timer.schedule(timerTask, 5000, 10000); //
    }
    public void stoptimertask() {//stoptimertask(View v)
        if (timer != null) {
            timer.cancel();
            timer = null;
timer.purge();
            try{
           
            }
            catch(Exception e){}

        }
    }

   
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
        stoptimertask();
        finish();
                return true;
        }
    return super.onKeyDown(keyCode, event);
}
   
   
    public void initializeTimerTask() {
        timerTask = new TimerTask() {
            public void run() {
                handler.post(new Runnable() {
                    public void run() {

                        Log.d("Simpan","Simpan data");
                         new save().execute();

                        Toast toast = Toast.makeText(getApplicationContext(), "Simpan data", 0);
                        toast.show();
                    }
                });
            }
        };
    }
   
   

class save extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(mapanak.this);
pDialog.setMessage("Menyimpan data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("kd_anak", kd_anak));
params.add(new BasicNameValuePair("latitude", myLati));
params.add(new BasicNameValuePair("longitude", myLongi));
params.add(new BasicNameValuePair("lokasi", myPosisi));
params.add(new BasicNameValuePair("kd_user", kd_user));

String url=ip+"monitoring/monitoring_add2.php";
Log.v("add",url);
JSONObject json = jsonParser.makeHttpRequest(url,"POST", params);
Log.d("add", json.toString());
try {
int sukses = json.getInt(TAG_SUKSES);
if (sukses == 1) {
Intent i = getIntent();
setResult(100, i);
//finish();
} else {
// gagal update data
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}

protected void onPostExecute(String file_url) {pDialog.dismiss();}
}
   
   
private void setupMap(){
if (map == null){
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.maps)).getMap();
if (map != null){
double lat=-6.353868;
double lon=106.832845;
try{
for(int i=0;i<jd;i++){
lat=Double.parseDouble(arlati[i]);
lon=Double.parseDouble(arlongi[i]);
map.addMarker(new MarkerOptions().position(new LatLng(lat, lon)).title(artgl[i]+" "+arjam[i]).snippet(arlokasi[i]));

}
}
catch(Exception e){}

try{
lat=Double.parseDouble(myLati);
lon=Double.parseDouble(myLongi);
map.addMarker(new MarkerOptions().position(new LatLng(lat, lon)).title("Posisi Anda").snippet(myPosisi));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lon),13));
}
catch(Exception e){}
}
}}

class load extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// pDialog = new ProgressDialog(mapanak.this);
// pDialog.setMessage("Load data. Silahkan Tunggu...");
// pDialog.setIndeterminate(false);
// pDialog.setCancelable(false);
// pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("kd_anak", kd_anak));

JSONObject json = jParser.makeHttpRequest(ip+"monitoring/monitoring_show.php", "GET", params);
Log.d("show: ", json.toString());
try {
int sukses = json.getInt(TAG_SUKSES);
if (sukses == 1) {
jd=json.length();
arkd_anak=new String[jd];
artgl=new String[jd];
arjam=new String[jd];
arlati=new String[jd];
arlongi=new String[jd];
arlokasi=new String[jd];
arstatus=new String[jd];

myJSON = json.getJSONArray(TAG_record);
for (int i = 0; i < jd; i++) {
JSONObject c = myJSON.getJSONObject(i);
String kd_anak = c.getString(TAG_kd_anak);
String tgl= c.getString(TAG_tgl);
String jam = c.getString(TAG_jam);
String lati = c.getString(TAG_latitude);
String longi= c.getString(TAG_longitude);
String lok= c.getString(TAG_lokasi);
String stat= c.getString(TAG_status);
arkd_anak[i]=kd_anak;
artgl[i]=tgl;
arjam[i]=jam;
arlati[i]=lati;
arlongi[i]=longi;
arlokasi[i]=lok;
arstatus[i]=stat;

}
}
}
catch (JSONException e) {e.printStackTrace();}
return null;
}

protected void onPostExecute(String file_url) {
//pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
setupMap();
}
});}
}


}
+++++++
maps.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />
    <fragment
        android:id="@+id/maps"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment"/>

</RelativeLayout>

Tidak ada komentar:

Posting Komentar