Update instantly markers on a map in Android using JSON - android

Hi I found this code to Plot markers on a map in Android using data from a JSON web service and the Google Maps Android API v2
Can anyone help me how to proceed update instantly marker without refreshing view to track position on the map
package com.example.google.maps.demo;
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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* #author saxman
*/
public class MainActivity extends FragmentActivity {
private static final String LOG_TAG = "taxitag";
private static final String SERVICE_URL = "http://192.168.1.3/taxi.php";
protected GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (map == null) {
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
if (map != null) {
setUpMap();
}
}
}
private void setUpMap() {
// Retrieve the city data from the web service
// In a worker thread since it's a network operation.
new Thread(new Runnable() {
public void run() {
try {
retrieveAndAddCities();
} catch (IOException e) {
Log.e(LOG_TAG, "Cannot retrive cities", e);
return;
}
}
}).start();
}
protected void retrieveAndAddCities() throws IOException {
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
// Connect to the web service
URL url = new URL(SERVICE_URL);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Read the JSON data into the StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
json.append(buff, 0, read);
}
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to service", e);
throw new IOException("Error connecting to service", e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
// Create markers for the city data.
// Must run this on the UI thread since it's a UI operation.
runOnUiThread(new Runnable() {
public void run() {
try {
createMarkersFromJson(json.toString());
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON", e);
}
}
});
}
void createMarkersFromJson(String json) throws JSONException {
// De-serialize the JSON string into an array of city objects
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
// Create a marker for each city in the JSON data.
JSONObject jsonObj = jsonArray.getJSONObject(i);
map.addMarker(new MarkerOptions()
.title(jsonObj.getString("name"))
.snippet(Integer.toString(jsonObj.getInt("population")))
.position(new LatLng(
jsonObj.getJSONArray("latlng").getDouble(0),
jsonObj.getJSONArray("latlng").getDouble(1)
))
);
}
}
}
thanks

you can use this,her you will get solution for updating markers.
link

Related

MyLocation cannot be cast to com.example.mycoordinate.TaskLoadedCallback

MyLocation.Java
package com.example.mycoordinate;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.Polyline;
import com.google.maps.android.SphericalUtil;
public class MyLocation extends AppCompatActivity implements LocationListener {
private GoogleMap googleMap;
private SupportMapFragment supportMapFragment;
private MarkerOptions place1, place2;
//getLocation()
LocationManager locationManager;
String locationText = "";
String locationLatitude = "";
String locationLongitude = "";
private Handler mHandler ;
private int mInterval = 3000; // after the coordinate is found, refresh every 3 seconds.
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps_offline);
supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
//Alert Dialog
AlertDialog.Builder alertDialog2 = new AlertDialog.Builder(
MyLocation.this);
// Setting Dialog Title
alertDialog2.setTitle("Notification");
// Setting Dialog Message
String string1 = "Give it 10-15 seconds for your coordinates to update. Keep moving around and you will see coordinates update.";
alertDialog2.setMessage(string1);
// Setting Icon to Dialog
alertDialog2.setIcon(R.drawable.ic_launcher_background);
// Setting Positive "Yes" Btn
// alertDialog2.setPositiveButton("Continue",
// new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
//
// }
// });
// Showing Alert Dialog
alertDialog2.show();
Handler handler2 = new Handler();
handler2.postDelayed(new Runnable() {
public void run() {
mHandler = new Handler();
startRepeatingTask();
}
}, 1000); //5 seconds
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
}
}
#Override
public void onDestroy() {
super.onDestroy();
stopRepeatingTask();
}
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
final EditText yourlat = (EditText) findViewById(R.id.yourLat);
final EditText yourlong = (EditText) findViewById(R.id.yourLong);
try {
getLocation(); //this function can change value of mInterval.
if (locationText.toString() == "") {
Toast.makeText(getApplicationContext(), "Locating us...", Toast.LENGTH_LONG).show();
} else {
yourlat.setText(locationLatitude.toString());
yourlong.setText(locationLongitude.toString());
}
} finally {
mHandler.postDelayed(mStatusChecker, mInterval);
}
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}
void getLocation() {
try {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 5, (LocationListener) this);
}
catch(SecurityException e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
locationText = location.getLatitude() + "," + location.getLongitude();
locationLatitude = location.getLatitude() + "";
locationLongitude = location.getLongitude() + "";
final LatLng home = new LatLng(1.363451, 103.834337); //HOME
final LatLng current = new LatLng(location.getLatitude(), location.getLongitude()); //current position
supportMapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
// double zoomLevel = googleMap.getCameraPosition().zoom;
// if (zoomLevel < 8) {
// zoomLevel = 18.0;
// }
// googleMap.clear();
//googleMap.addMarker(new MarkerOptions().position(current_position).title("Current Location"));
//googleMap.moveCamera(CameraUpdateFactory.newLatLng(current_position) );
//googleMap.animateCamera( CameraUpdateFactory.zoomTo( (float) zoomLevel) );
//googleMap.addMarker(new MarkerOptions().position(home).title("Home"));
//googleMap.moveCamera(CameraUpdateFactory.newLatLng(place1.getPosition()) );
place1 = new MarkerOptions().position(current).title("Current");
place2 = new MarkerOptions().position(home).title("Home");
googleMap.addMarker(place1);
googleMap.addMarker(place2);
//Route between two points
new FetchURL(MyLocation.this).execute(getUrl(place1.getPosition(), place2.getPosition(), "driving"), "driving" );
//distance between two points in a Straight Line
Double distance = SphericalUtil.computeDistanceBetween(place1.getPosition(), place2.getPosition());
CameraPosition googlePlex = CameraPosition.builder()
.target(place1.getPosition())
.zoom(16)
.bearing(0)
//.tilt(45)
.build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(googlePlex), 10000, null);
Log.d("Location", "Distance: " + distance );
}
});
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(MyLocation.this, "Please Enable GPS", Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
private String getUrl(LatLng origin, LatLng dest, String directionMode) {
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Mode
String mode = "mode=" + directionMode;
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + mode;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters + "&key=" + getString(R.string.google_maps_key);
Log.d("TEST", "getUrl: " + url);
return url;
}
}
FetchURL.java
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class FetchURL extends AsyncTask<String, Void, String> {
Context mContext;
String directionMode = "driving";
public FetchURL(Context mContext) {
this.mContext = mContext;
}
#Override
protected String doInBackground(String... strings) {
// For storing data from web service
String data = "";
directionMode = strings[1];
try {
// Fetching the data from web service
data = downloadUrl(strings[0]);
Log.d("mylog", "Background task data " + data.toString());
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
PointsParser parserTask = new PointsParser(mContext, directionMode);
// Invokes the thread for parsing the JSON data
parserTask.execute(s);
}
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
Log.d("mylog", "Downloaded URL: " + data.toString());
br.close();
} catch (Exception e) {
Log.d("mylog", "Exception downloading URL: " + e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
}
PointsParser.java
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.util.Log;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PolylineOptions;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class PointsParser extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
TaskLoadedCallback taskCallback;
String directionMode = "driving";
public PointsParser(Context mContext, String directionMode) {
this.taskCallback = (TaskLoadedCallback) mContext; <---- this is the error
this.directionMode = directionMode;
}
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
Log.d("mylog", jsonData[0].toString());
DataParser parser = new DataParser();
Log.d("mylog", parser.toString());
// Starts parsing data
routes = parser.parse(jObject);
Log.d("mylog", "Executing routes");
Log.d("mylog", routes.toString());
} catch (Exception e) {
Log.d("mylog", e.toString());
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points;
PolylineOptions lineOptions = null;
// Traversing through all the routes
for (int i = 0; i < result.size(); i++) {
points = new ArrayList<>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
if (directionMode.equalsIgnoreCase("walking")) {
lineOptions.width(10);
lineOptions.color(Color.MAGENTA);
} else {
lineOptions.width(20);
lineOptions.color(Color.RED);
}
Log.d("mylog", "onPostExecute lineoptions decoded");
}
// Drawing polyline in the Google Map for the i-th route
if (lineOptions != null) {
//mMap.addPolyline(lineOptions);
taskCallback.onTaskDone(lineOptions);
} else {
Log.d("mylog", "without Polylines drawn");
}
taskCallback.onTaskDone();
}
}
TaskLoadedCallback.java
public interface TaskLoadedCallback {
void onTaskDone(Object... values);
}
It has been almost a week trying to understand and trying to fix this the error Below.
2019-08-12 14:29:01.822 14672-14672/? E/Zygote: isWhitelistProcess - Process is Whitelisted
2019-08-12 14:29:01.824 14672-14672/? E/Zygote: accessInfo : 1
2019-08-12 14:29:01.866 14672-14680/? E/le.mycoordinat: Unable to peek into adb socket due to error. Closing socket.: Connection reset by peer
2019-08-12 14:29:03.831 14672-14672/com.example.mycoordinate E/ViewRootImpl#c1f726b[MyLocation]: mStopped=false mHasWindowFocus=true mPausedForTransition=false
2019-08-12 14:29:03.859 14672-14672/com.example.mycoordinate E/ViewRootImpl: sendUserActionEvent() returned.
2019-08-12 14:29:07.662 14672-14672/com.example.mycoordinate E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mycoordinate, PID: 14672
java.lang.ClassCastException: com.example.mycoordinate.MyLocation cannot be cast to com.example.mycoordinate.TaskLoadedCallback
at com.example.mycoordinate.PointsParser.<init>(PointsParser.java:20)
at com.example.mycoordinate.FetchURL.onPostExecute(FetchURL.java:44)
at com.example.mycoordinate.FetchURL.onPostExecute(FetchURL.java:18)
at android.os.AsyncTask.finish(AsyncTask.java:695)
at android.os.AsyncTask.access$600(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:6986)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)
Any kindhearted individual who can help me with this? It has been almost a week since i started this journey. I already passed (MyLocation.this - as reference to the activity) but it still doesnt work... do note my Google API is working fine.
Please help.
This is because you are passing MyLocation to PointsParser and try to cast it to TaskLoadedCallback in this.taskCallback = (TaskLoadedCallback) mContext;, add TaskLoadedCallback to implements in MyLocation
public class MyLocation extends AppCompatActivity implements LocationListener, TaskLoadedCallback {
}

java.lang.NullPointerException in JSONArray [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
in my applicationi want to show my locations from database and i find code do that but i get this error so please help me !!
'here is my MainnActivity '
package com.ry.rhcomptence.accessiblemaroc;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
public class MainnActivity extends FragmentActivity implements OnMapReadyCallback {
GoogleMap mGoogleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainn);
// Getting reference to SupportMapFragment
SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
// Creating GoogleMap from SupportMapFragment
//mGoogleMap = fragment.getMap();
fragment.getMapAsync(this);
// Setting OnClickEvent listener for the GoogleMap
/**mGoogleMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng latlng) {
addMarker(latlng);
sendToServer(latlng);
}
});*/
// Starting locations retrieve task
new RetrieveTask().execute();
}
// Adding marker on the GoogleMaps
private void addMarker(LatLng latlng) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latlng);
markerOptions.title(latlng.latitude + "," + latlng.longitude);
mGoogleMap.addMarker(markerOptions);
}
// Invoking background thread to store the touched location in Remove MySQL server
private void sendToServer(LatLng latlng) {
new SaveTask().execute(latlng);
}
#Override
public void onMapReady(GoogleMap googleMap) {
// Enabling MyLocation button for the Google Map
/**if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mGoogleMap.setMyLocationEnabled(true);*/
}
// Background thread to save the location in remove MySQL server
private class SaveTask extends AsyncTask<LatLng, Void, Void> {
#Override
protected Void doInBackground(LatLng... params) {
String lat = Double.toString(params[0].latitude);
String lng = Double.toString(params[0].longitude);
String strUrl = "https://accessiblemaroc.000webhostapp.com/save.php";
URL url = null;
try {
url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
connection.getOutputStream());
outputStreamWriter.write("lat=" + lat + "&lng="+lng);
outputStreamWriter.flush();
outputStreamWriter.close();
InputStream iStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new
InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( (line = reader.readLine()) != null){
sb.append(line);
}
reader.close();
iStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
// Background task to retrieve locations from remote mysql server
private class RetrieveTask extends AsyncTask<Void, Void, String>{
#Override
protected String doInBackground(Void... params) {
String strUrl = "https://accessiblemaroc.000webhostapp.com/retrieve.php";
URL url = null;
StringBuffer sb = new StringBuffer();
try {
url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream iStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
String line = "";
while( (line = reader.readLine()) != null){
sb.append(line);
}
reader.close();
iStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
new ParserTask().execute(result);
}
}
// Background thread to parse the JSON data retrieved from MySQL server
private class ParserTask extends AsyncTask<String, Void, List<HashMap<String, String>>>{
#Override
protected List<HashMap<String,String>> doInBackground(String... params) {
MarkerJSONParser markerParser = new MarkerJSONParser();
JSONObject json = null;
try {
json = new JSONObject(params[0]);
} catch (JSONException e) {
e.printStackTrace();
}
List<HashMap<String, String>> markersList = markerParser.parse(json);
return markersList;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
for(int i=0; i<result.size();i++){
HashMap<String, String> marker = result.get(i);
LatLng latlng = new LatLng(Double.parseDouble(marker.get("lat")), Double.parseDouble(marker.get("lng")));
addMarker(latlng);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
'here where is the problem MarkerJSONParser.JAVA :'
package com.ry.rhcomptence.accessiblemaroc;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MarkerJSONParser {
/** Receives a JSONObject and returns a list */
public List<HashMap<String,String>> parse(JSONObject jObject){
JSONArray jMarkers =null;
try {
/** Retrieves all the elements in the 'markers' array */
jMarkers = jObject.getJSONArray("markers");
} catch (JSONException e) {
e.printStackTrace();
}
/** Invoking getMarkers with the array of json object
* where each json object represent a marker
*/
return getMarkers(jMarkers);
}
private List<HashMap<String, String>> getMarkers(JSONArray jMarkers){
int markersCount = jMarkers.length();
List<HashMap<String, String>> markersList = new ArrayList<HashMap<String,String>>();
HashMap<String, String> marker = null;
/** Taking each marker, parses and adds to list object */
for(int i=0; i<markersCount;i++){
try {
/** Call getMarker with marker JSON object to parse the marker */
marker = getMarker((JSONObject)jMarkers.get(i));
markersList.add(marker);
}catch (JSONException e){
e.printStackTrace();
}
}
return markersList;
}
/** Parsing the Marker JSON object */
private HashMap<String, String> getMarker(JSONObject jMarker){
HashMap<String, String> marker = new HashMap<String, String>();
String lat = "-NA-";
String lng ="-NA-";
try {
// Extracting latitude, if available
if(!jMarker.isNull("lat")){
lat = jMarker.getString("lat");
}
// Extracting longitude, if available
if(!jMarker.isNull("lng")){
lng = jMarker.getString("lng");
}
marker.put("lat", lat);
marker.put("lng", lng);
} catch (JSONException e) {
e.printStackTrace();
}
return marker;
}
}
'and finally this is the ERROR'
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.NullPointerException
at com.ry.rhcomptence.accessiblemaroc.MarkerJSONParser.parse(MarkerJSONParser.java:19)
at com.ry.rhcomptence.accessiblemaroc.MainnActivity$ParserTask.doInBackground(MainnActivity.java:191)
at com.ry.rhcomptence.accessiblemaroc.MainnActivity$ParserTask.doInBackground(MainnActivity.java:181)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137) 
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) 
at java.lang.Thread.run(Thread.java:856) 
You are not trying to get data in your ParserTask
private class ParserTask extends AsyncTask<String, Void, List<HashMap<String, String>>>{
#Override
protected List<HashMap<String,String>> doInBackground(String... params) {
MarkerJSONParser markerParser = new MarkerJSONParser();
JSONObject json = null;
try {
json = new JSONObject(params[0]);
} catch (JSONException e) {
e.printStackTrace();
}
List<HashMap<String, String>> markersList = markerParser.parse(json);
return markersList;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
for(int i=0; i<result.size();i++){
HashMap<String, String> marker = result.get(i);
LatLng latlng = new LatLng(Double.parseDouble(marker.get("lat")), Double.parseDouble(marker.get("lng")));
addMarker(latlng);
}
}
}
You mentioned that this is a:
//Background thread to parse the JSON data retrieved from MySQL server
But you are not retrieving data from your MySQL Server which in return would give you nothing. And when you pass that nothing to your MarkerJSONParser and try to parse nothing. It would result to the NullPointerException.

map on android device showing only one marker from url but showing all the values when I use Toast

I have tried many changes researching on google but my problem isn't resolved. I have an URL which contains following data. On map it should show more than one marker as I have 9 coordinates. But it is showing one marker with coordinates of last values of response. Any help can be appreciated.
{
"status":200,
"response":[
{
"docId":"1",
"docName":"Madan",
"docMobileNumber":"9676499774",
"location":"S R Nagar",
"specialization":"ENT",
"avaliablity":"Available",
"lat":"17.4436",
"log":"78.4458"
},
{
"docId":"2",
"docName":"Kumar",
"docMobileNumber":"9052598855",
"location":"KPHB",
"specialization":"Pediatrician",
"avaliablity":"Available",
"lat":"17.4948",
"log":"78.3996"
},
{
"docId":"3",
"docName":"charan",
"docMobileNumber":"8080809089",
"location":"Ameerpet",
"specialization":"Dentist",
"avaliablity":"Available",
"lat":"17.4375",
"log":"78.4483"
},
{
"docId":"4",
"docName":"Vamsy",
"docMobileNumber":"7777778888",
"location":"Kukatpally",
"specialization":"Orthopedic",
"avaliablity":"Available",
"lat":"17.4948",
"log":"78.3996"
},
{
"docId":"5",
"docName":"Ganesh",
"docMobileNumber":"9878686544",
"location":"Dilsuk Nagar",
"specialization":"Dermatologist",
"avaliablity":"Available",
"lat":"17.3688",
"log":"78.5247"
},
{
"docId":"6",
"docName":"Savitri",
"docMobileNumber":"8786599452",
"location":" West Marredpally",
"specialization":"Physician",
"avaliablity":"Not Available",
"lat":"17.4500",
"log":"78.5006"
},
{
"docId":"7",
"docName":"Sandhya",
"docMobileNumber":"9873243687",
"location":"Bowenpally",
"specialization":"Eye Specialist",
"avaliablity":"Available",
"lat":"17.898",
"log":"78.5008"
},
{
"docId":"8",
"docName":"Padma",
"docMobileNumber":"9768832418",
"location":"Kompally",
"specialization":"Cardiologist",
"avaliablity":"Not Available",
"lat":"17.5600",
"log":"78.5343"
},
{
"docId":"9",
"docName":"Priya",
"docMobileNumber":"9898767654",
"location":"Tirumalgiri",
"specialization":"Nerphrologist",
"avaliablity":"Available",
"lat":"17.787",
"log":"78.9805"
}
]
}
package com.example.charan.markermap;
import android.app.ProgressDialog;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
public class Maps3 extends FragmentActivity {
private GoogleMap mMap;
ArrayList<HashMap<String, Double>> locationList = new ArrayList<HashMap<String, Double>>();
JSONArray locations = new JSONArray();
int json1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
new TaskRead().execute();
}
public class TaskRead extends AsyncTask<Void, Void, Void> implements OnMapReadyCallback {
ProgressDialog pg;
Double latitude, longitude;
protected void onPreExecute() {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
pg = ProgressDialog.show(Maps3.this, "Please Wait", "Conecting to Server");
pg.setCancelable(true);
}
protected Void doInBackground(Void... params) {
try {
String url = "http://192.168.1.33:8282/DocFinderServices/doctorService/doctorsList";
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = client.execute(httpget);
HttpEntity entity = response.getEntity();
InputStream inputStreamResponse = entity.getContent();
String str = convertStreamToString(inputStreamResponse);
if (str != null) {
try {
JSONObject jsonObj = new JSONObject(str);
// Getting JSON Array node
locations = jsonObj.getJSONArray("response");
json1 = jsonObj.getInt("status");
// looping through All records
for (int i = 0; i < locations.length(); i++) {
JSONObject c = locations.getJSONObject(i);
latitude = c.getDouble("lat");
longitude = c.getDouble("log");
// tmp hashmap for single contact
HashMap<String, Double> location = new HashMap<>();
// adding each child node to HashMap key => value
location.put("latitude", latitude);
location.put("longitude", longitude);
locationList.add(location);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void gmap) {
mMap.clear();
Marker[] allMarkers = new Marker[locationList.size()];
Toast.makeText(Maps3.this, "The list size is " + locationList.size(), Toast.LENGTH_SHORT).show();
for (int i = 0; i < locationList.size(); i++) {
if (mMap != null && json1 == 200) {
for (int j = 0; j < locationList.size(); j++) {
LatLng latLng = new LatLng(latitude, longitude);
allMarkers[i] = mMap.addMarker(new MarkerOptions()
.position(latLng)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ok)));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14.0f));
mMap.getUiSettings().isZoomGesturesEnabled();
}
} else {
Toast.makeText(Maps3.this, "Oops..their is no map........", Toast.LENGTH_SHORT).show();
}
}
pg.dismiss();
}
public String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
}
}
Try with execute TaskRead after you got callback onMapReady().
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Set Zoom Controls and Gestures on map
mMap.getUiSettings().setZoomControlsEnabled(true)
mMap.getUiSettings().setZoomGesturesEnabled(true)
new TaskRead().execute();
}
Implements OnMapReadyCallback inside FragmentActivity and initialize your SupportMapFragment in onCreate method like below.
public class Maps3 extends FragmentActivity implements OnMapReadyCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
Try to set zoom Controls and Gestures on map and try with zoom in or zoom out and see, is there other marker added on map or not ?
Check my updated onMapReady method.
I have just changed LatLng latLng = new LatLng(latitude, longitude); to new values of getting key pair values as
LatLng latLng = new LatLng(Double.valueOf(locationList.get(j).get("latitude")), Double.valueOf(locationList.get(j).get("longitude")));. Now it is working.

Using JSON and creating markers for Android Maps API load time

I m implementing google maps in my android project which retrieves JSON data from a URL to draw markers in the map,also it has a search option with autocomplete addresses of google places API here is my codes.
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class MapsActivity extends FragmentActivity implements AdapterView.OnItemClickListener {
LocationAddress add=new LocationAddress();
DashboardActivity dObj=new DashboardActivity();
public void onClickHome (View v)
{
final Intent intent = new Intent(getApplicationContext(), DashboardActivity.class);
startActivity(intent);
}
class MyInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {
private final View myContentsView;
MyInfoWindowAdapter(){
myContentsView = getLayoutInflater().inflate(R.layout.custom_info_contents, null);
}
#Override
public View getInfoContents(Marker arg0) {
displayView(arg0);
return myContentsView;
}
#Override
public View getInfoWindow(Marker arg0) {
return null;
}
public void displayView(Marker arg0) {
String[] contents=arg0.getTitle().split("#");
String title=contents[0];
String address=contents[1];
((TextView)myContentsView.findViewById(R.id.title)).setText(title);
((TextView)myContentsView.findViewById(R.id.snippet)).setText(address);
}
}
private static final String LOG_TAG = "myApp";
private static final String SERVICE_URL = "JSON_DATA_URL";
private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
private static final String OUT_JSON = "/json";
//------------ make your specific key ------------
private static final String API_KEY = "AIzaSyDKUpzHkox5q5-pcNYmRS-UT7izEvd6WtQ";
protected GoogleMap map;
private GoogleApiClient client;
TextView latlongLocation;
Marker marker;
Button clear;
AutoCompleteTextView autoCompView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
setTitleFromActivityLabel(R.id.title_text);
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
autoCompView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(this, R.layout.list_item));
autoCompView.setOnItemClickListener(this);
clear=(Button)findViewById(R.id.clear);
clear.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
autoCompView.setText("");
}
});
}
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String str = (String) adapterView.getItemAtPosition(position);
Geocoder geocoder = new Geocoder(getApplicationContext());
List<Address> addresses = null;
try
{
// removeSearchMarker();
addresses = geocoder.getFromLocationName(str, 3);
if (addresses != null && !addresses.equals(""))
search(addresses);
}
catch (Exception e) {
}
}
public static ArrayList<String> autocomplete(String input) {
ArrayList<String> resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
sb.append("?key=" + API_KEY);
sb.append("&language" + "fa");
sb.append("&components=country:af");
sb.append("&input=" + URLEncoder.encode(input, "utf8"));
URL url = new URL(sb.toString());
System.out.println("URL: "+url);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error processing Places API URL", e);
return resultList;
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to Places API", e);
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
resultList = new ArrayList<String>(predsJsonArray.length());
for (int i = 0; i < predsJsonArray.length(); i++) {
System.out.println(predsJsonArray.getJSONObject(i).getString("description"));
System.out.println("============================================================");
resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Cannot process JSON results", e);
}
return resultList;
}
class GooglePlacesAutocompleteAdapter extends ArrayAdapter<String> implements Filterable {
private ArrayList<String> resultList;
public GooglePlacesAutocompleteAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
#Override
public int getCount() {
return resultList.size();
}
#Override
public String getItem(int index) {
return resultList.get(index);
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
resultList = autocomplete(constraint.toString());
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return filter;
}
}
protected void search(List<Address> addresses) {
Address address = (Address) addresses.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
// String addressText = String.format("%s, %s", address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "", address.getCountryName());
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
map.animateCamera(CameraUpdateFactory.zoomTo(14));
latlongLocation.setText("Latitude:" + address.getLatitude() + ", Longitude:" + address.getLongitude());
// map.setInfoWindowAdapter(new MyInfoWindowAdapter());
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
#Override
protected void onPause() {
setUpMapIfNeeded();
super.onPause();
}
#Override
protected void onRestart() {
setUpMapIfNeeded();
super.onRestart();
}
#Override
protected void onDestroy() {
map=null;
super.onDestroy();
}
private void setUpMapIfNeeded() {
if (map == null) {
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
if (map != null) {
setUpMap();
}
}
}
private void setUpMap() {
LatLng origin = new LatLng(34.520299, 69.179912);
CameraUpdate panToOrigin = CameraUpdateFactory.newLatLng(origin);
map.moveCamera(panToOrigin);
map.animateCamera(CameraUpdateFactory.zoomTo(13), 400, null);
map.getUiSettings();
map.getUiSettings().setZoomControlsEnabled(true);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
map.setMyLocationEnabled(true);
map.setInfoWindowAdapter(new MyInfoWindowAdapter());
new Thread(new Runnable() {
public void run() {
try {
retrieveLocations();
} catch (IOException e) {
Log.e(LOG_TAG, "Cannot retrive locations", e);
return;
}
}
}).start();
}
protected void retrieveLocations() throws IOException {
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
URL url = new URL(SERVICE_URL);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
json.append(buff, 0, read);
}
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to service", e);
throw new IOException("Error connecting to service", e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
runOnUiThread(new Runnable() {
public void run() {
try {
createMarkersFromJson(json.toString());
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON", e);
}
}
});
}
void createMarkersFromJson(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
String address=add.getAddressFromLocation(jsonObj.getDouble("geolat"), jsonObj.getDouble("geolng"), getApplicationContext());
String date=jsonObj.getString("posted_date");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date testDate=null;
try{
testDate=sdf.parse(date);
}catch (Exception ex){
ex.printStackTrace();
}
sdf=new SimpleDateFormat("EEE, d MMM yyyy HH:mm aa");
date=sdf.format(testDate);
map.addMarker(new MarkerOptions()
.title(address.toString()+"#"+date)
.position(new LatLng(jsonObj.getDouble("geolat"), jsonObj.getDouble("geolng")
))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon3))
);
}
}
public void setTitleFromActivityLabel (int textViewId)
{
TextView tv = (TextView) findViewById (textViewId);
if (tv != null) tv.setText (getTitle ());
}
}
These codes are working properly to draw markers from json data in maps but the problem is that when I start this activity it takes too much time to display the map and markers and during this time everything is like frozen i can't go back or home and if i click many times on any screan components its crashing the application. the number of json records which createMarkersFromJson method is looping through for creating markers maybe like 40-50 records and there are possibilities to extend. So my question is what is the reason of this problem and is there any other way to display markers in the map fast without crashing the application?.
I should mention that i m new to android development, Any help would be much appreciated. thank you in advance!
As per the Android guidelines I believe you should use AsyncTask for "retrieveLocations" instead of creating a thread on your own to connect to a network..

Using JSON for Android Maps API to display markers

First of all I want to mention that I am a total beginner in programming in Android Studio.
I am trying to retrieve a JSON response from the server, parse it and add markers to my map. I have a working map, but the markers are not showing up.Any idea what should I do?
THIS IS MY CLASS
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MapsActivity extends FragmentActivity{
private GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
new MarkerTask().execute();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
new MarkerTask().execute();
}
private void setUpMapIfNeeded() {
if (map == null) {
// Try to obtain the map from the SupportMapFragment.
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
map.setMyLocationEnabled(true);
} else {
Toast.makeText(MapsActivity.this, "You have to accept to enjoy all app's services!", Toast.LENGTH_LONG).show();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
map.setMyLocationEnabled(true);
}
}
if (map != null) {
map.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(arg0.getLatitude(), arg0.getLongitude()));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(16);
map.moveCamera(center);
map.animateCamera(zoom);
}
});
}
}
}
//--------------------------------------------------------------
class MarkerTask extends AsyncTask<Void, Void, String> {
private static final String LOG_TAG = "ExampleApp";
private static final String SERVICE_URL = "http://(some IP address )/stations.php";
#Override
protected String doInBackground(Void... args) {
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
URL url = new URL(SERVICE_URL);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
json.append(buff, 0, read);
}
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to service", e);
//throw new IOException("Error connecting to service", e); //uncaught
} finally {
if (conn != null) {
conn.disconnect();
}
}
return json.toString();
}
#Override
protected void onPostExecute(String json) {
try {
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
LatLng latLng = new LatLng(jsonObj.getDouble("lat"),
jsonObj.getDouble("lng"));
map.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
.title(jsonObj.getString("nume"))
.position(latLng));
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON", e);
}
}
}}

Categories

Resources