-1

I'm having a question about how to do a project that I thought would be simple. Next I have an app that sends the location of the mobile phone by 10 seconds to MySql, so alright.

But I just need to now display in another app the current location these users on the mapped 10 seconds without having to open and close the Activity.

In this code below the mapping of the markers that come from the Mysql bank using json is displayed. Any tips?

   public class MainActivity extends FragmentActivity {

    // Google Map
    private GoogleMap googleMap;

    // Latitude & Longitude
    private Double Latitude = 0.00;
    private Double Longitude = 0.00;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //*** Permission StrictMode
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        ArrayList<HashMap<String, String>> location = null;
        String url = "http://192.168.1.202/android/getLatLon.php";
        try {

            JSONArray data = new JSONArray(getHttpGet(url));

            location = new ArrayList<HashMap<String, String>>();
            HashMap<String, String> map;

            for(int i = 0; i < data.length(); i++){
                JSONObject c = data.getJSONObject(i);

                map = new HashMap<String, String>();
                map.put("LocationID", c.getString("LocationID"));
                map.put("Latitude", c.getString("Latitude"));
                map.put("Longitude", c.getString("Longitude"));
                map.put("LocationName", c.getString("LocationName"));
                location.add(map);

            }           

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


        // *** Display Google Map
        googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap)).getMap();

        // *** Focus & Zoom
        Latitude = Double.parseDouble(location.get(0).get("Latitude").toString());
        Longitude = Double.parseDouble(location.get(0).get("Longitude").toString());
        LatLng coordinate = new LatLng(Latitude, Longitude);
        googleMap.setMapType(com.google.android.gms.maps.GoogleMap.MAP_TYPE_HYBRID);
        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 17));

        // *** Marker (Loop)
        for (int i = 0; i < location.size(); i++) {
            Latitude = Double.parseDouble(location.get(i).get("Latitude").toString());
            Longitude = Double.parseDouble(location.get(i).get("Longitude").toString());
            String name = location.get(i).get("LocationName").toString();
            MarkerOptions marker = new MarkerOptions().position(new LatLng(Latitude, Longitude)).title(name);
            googleMap.addMarker(marker);
        }

    }

    public static String getHttpGet(String url) {
        StringBuilder str = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) { // Download OK
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    str.append(line);
                }
            } else {
                Log.e("Log", "Failed to download result..");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str.toString();
    }

}

2 Answers2

1

You can use COUNTDOWN TIMER, COUNT DOWN TIMER EXAMPLE so that every 10 sec it makes network request and you will get response with the updated value. and you can update your marker with the new LATITUDE, LONGITUDE value. And keep in mind add marker only on the first network request after that don't need to add marker only you need to change your marker position. .how to change marker position

But i will recommend you its not a good idea to make network request every time(Every 10 sec). it may be possible that user is not changing there location since one hour.so its worthless API call. so it would be better if you use REAL TIME DATABASE(like Firebase real time db). and listen your data change whenever your db value will be updated it will notify you. Firebase Real time DB Doc reference

shahid17june
  • 1,441
  • 1
  • 10
  • 15
0

If you want to update your map on some interval of time without having to open and close thee activity. You should move your logic from onCreate() method.

Thread myLoopingThread = new Thread(new Runnable() {
    @Override
    public void run() {
        while(!Thread.currentThread().isInterrupted()){
            final String result = getHttpGet("http://192.168.1.202/android/getLatLon.php");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    UpdateMap(result);
                }
            });
            Thread.sleep(timeToSleep);
        }
    }
});

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //do other stuff..
    myLoopingThread.start();
}
//also we should stop the thread when its not needed anymore
@Override
 protected void onDestroy(){
    myLoopingThread.interrupt();
    super.onDestroy();
}  
void UpdateMap(String input){
    ArrayList<HashMap<String, String>> location = null;

    try {

        JSONArray data = new JSONArray(input);

        location = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> map;

        for(int i = 0; i < data.length(); i++){
            JSONObject c = data.getJSONObject(i);

            map = new HashMap<String, String>();
            map.put("LocationID", c.getString("LocationID"));
            map.put("Latitude", c.getString("Latitude"));
            map.put("Longitude", c.getString("Longitude"));
            map.put("LocationName", c.getString("LocationName"));
            location.add(map);

        }           

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


    // *** Display Google Map
    googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap)).getMap();

    // *** Focus & Zoom
    Latitude = Double.parseDouble(location.get(0).get("Latitude").toString());
    Longitude = Double.parseDouble(location.get(0).get("Longitude").toString());
    LatLng coordinate = new LatLng(Latitude, Longitude);
    googleMap.setMapType(com.google.android.gms.maps.GoogleMap.MAP_TYPE_HYBRID);
    googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 17));

    // *** Marker (Loop)
    for (int i = 0; i < location.size(); i++) {
        Latitude = Double.parseDouble(location.get(i).get("Latitude").toString());
        Longitude = Double.parseDouble(location.get(i).get("Longitude").toString());
        String name = location.get(i).get("LocationName").toString();
        MarkerOptions marker = new MarkerOptions().position(new LatLng(Latitude, Longitude)).title(name);
        googleMap.addMarker(marker);
    }
}
  • I'm not able to fit this GetMapData () and UpdateMap () into my code. – raio mobile Aug 23 '17 at 15:06
  • @raiomobile Those are methods you should create. I don't know why you can't fit them in. I've updated my answer by copying some of your logic. Hope it's more clear now. Also you should consider what shahid17june said about the network requests and real time databases. – Dani Ivanov Aug 23 '17 at 15:45