I am trying to get my JSON object from specific url and when I hit .execute(); I got null pointer exception pointing to my JSONarray. Where should be the problem ? I have tried to put .execute() method somewhere else but still doesnt work. And I know for sure that url is 100% correct
My JSONParser class:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
My JSON:
{
"current_ts": 1425907330,
"username": "guri",
"events": [
{
"id": 16591481,
"ts": 1425907325,
"lat": 48.17,
"lon": 17.13,
"likes": 5,
"text": "Poziar na hlavnej stanici",
"tags": "#poziar #stanica #hori",
"img": "2002-06-19.jpg"
},
{
"id": 47067411,
"ts": 1425907100,
"lat": 48.81,
"lon": 17.22,
"likes": 0,
"text": "V Bille je velky vypredaj",
"tags": [
{
"tag1": "#akcia",
"tag2": "#akcia"
}
],
"img": "DSC04934.jpg"
}
]
}
Here is my code:
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
double lon = 0;
double lat = 0;
private static final String TAG_EVENT = "events";
private static final String TAG_LAT = "lat";
private static final String TAG_LON = "lon";
private static final String TAG_TEXT = "text";
JSONArray event = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//requestWindowFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.activity_main);
setUpMapIfNeeded();
//new JSONParse().execute();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
// Setting Dialog Title
alertDialog.setTitle("GPS settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
private void setUpMapIfNeeded() {
LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
/*if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
showSettingsAlert();
}
else{*/
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
// Getting reference to the SupportMapFragment of activity_menu.xml
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting mMap object from the fragment
mMap = fm.getMap();
// Enabling MyLocation Layer of Google Map
mMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
/*if(networkEnabled){*/
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!=null){
lon = location.getLongitude();
lat = location.getLatitude();
LatLng latLng = new LatLng(lat, lon);
// Showing the current location in Google Map
//mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
//mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
/*}*/
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 2000, 0, this);
/*}*/}
}
#Override
public void onLocationChanged(Location location) {
/*double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));*/
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_menu, menu);
super.onCreateOptionsMenu(menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
// Handle action buttons
switch(item.getItemId()) {
case R.id.something:
// create intent to perform web search for this planet
/*Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
//intent.putExtra(SearchManager.QUERY, getSupportActionBar().getTitle());
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, "app not available", Toast.LENGTH_LONG).show();
}*/
new JSONParse().execute();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
//uid = (TextView)findViewById(R.id.uid);
//name1 = (TextView)findViewById(R.id.name);
//email1 = (TextView)findViewById(R.id.email);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
return jParser.getJSONFromUrl("http://guri.sk/mapped/mapped.json");
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array
event = json.getJSONArray(TAG_EVENT);
JSONObject c = event.getJSONObject(3);
// Storing JSON item in a Variable
double lat2 = c.getDouble(TAG_LAT);
double lon2 = c.getDouble(TAG_LON);
String text = c.getString(TAG_TEXT);
//Set JSON Data in TextView
//uid.setText(id);
//name1.setText(name);
//email1.setText(email);
mMap.addMarker(new MarkerOptions().position(new LatLng(lat2, lon2)).title(text));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
My logcat:
Process: com.digitale.mapped, PID: 23552
java.lang.NullPointerException
at com.digitale.mapped.MainActivity$JSONParse.onPostExecute(MainActivity.java:231)
at com.digitale.mapped.MainActivity$JSONParse.onPostExecute(MainActivity.java:206)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:212)
at android.app.ActivityThread.main(ActivityThread.java:5135)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:877)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
at dalvik.system.NativeStart.main(Native Method)
Line 231 is event = json.getJSONArray(TAG_EVENT);
Should be
sb.append(line).append("\n");
you have
sb.append(line).append("n");
jParser.getJSONFromUrl("http://guri.sk/mapped/mapped.json") is returning null value.
So you are getting a null reference in onPostExecute(). So when you are invoking
event = json.getJSONArray(TAG_EVENT); // here json is a null referrence
that is the cause of your NPE
The error looks in the method onPostExecute()
I tested the url you are using to get the JSONObject.
The url is returning the only 2 objects in the JSONArray So you cannot get a Index 3.
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array
event = json.getJSONArray(TAG_EVENT);
**JSONObject c = event.getJSONObject(3);**//The index is 3, It should be less than 2
// Storing JSON item in a Variable
double lat2 = c.getDouble(TAG_LAT);
double lon2 = c.getDouble(TAG_LON);
String text = c.getString(TAG_TEXT);
//Set JSON Data in TextView
//uid.setText(id);
//name1.setText(name);
//email1.setText(email);
mMap.addMarker(new MarkerOptions().position(new LatLng(lat2, lon2)).title(text));
} catch (JSONException e) {
e.printStackTrace();
}
}
Wrap your AsyncTask in a function like this:
private void parseJSON()
{
new AsyncTask<String, String, JSONObject>(){
// Your code here...
}.execute();
}
Or, save your AsyncTask to a variable and call execute on that.
Related
Currently I am working with a project to get current latitude and longitude, I got that. Now I want the latitude and longitude send to MySQL database using Android. HTTP part of this program is not working.
LocationManager locationManager;
String mprovider;
String lat="", lon="";
private String Tag="MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postData(lat, lon);
}
});
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
mprovider = locationManager.getBestProvider(criteria, false);
if (mprovider != null && !mprovider.equals("")) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = locationManager.getLastKnownLocation(mprovider);
locationManager.requestLocationUpdates(mprovider, 0, 0, this);
if (location != null) {
onLocationChanged(location);
} else
Toast.makeText(getBaseContext(), "No Location Provider Found Check Your Code", Toast.LENGTH_SHORT).show();
}
}
private void postData(String la, String lo) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost htget = new HttpPost("http://192.168.1.2/yy.php/"+la+"/"+lo);
try {
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(htget);
String resp = response.getStatusLine().toString();
Toast.makeText(this, resp, Toast.LENGTH_SHORT).show();
} catch (ClientProtocolException e) {
Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onLocationChanged(Location location) {
lat = Double.toString(location.getLatitude());
lon = Double.toString(location.getLongitude());
TextView tv = (TextView) findViewById(R.id.textView2);
tv.setText("Your Location is:" + lat + "--" + lon);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
you can send data form android to server over http. here is more details
Use mysql's spatial extensions.
For making tables and using it with Google Maps api refer this:
Using MySQL and PHP with Google Maps
Before you start, I have few questions:
Which version of gmaps API are you working with?
How are you parsing the map marker (lat. long.) data?
How are you triggering the save (lat long/ map marker data event).
Workable method: create a JSON parser for parsing the Marker data (which is the JSON Object here).
public class MarkerJSONParser {
/** gets a JSONObject and returns a list */
public List<HashMap<String,String>> parse(JSONObject jObject){
JSONArray jMarkers = null;
try {
/** gets all the elements in the 'markers' array */
jMarkers = jObject.getJSONArray("markers");
} catch (JSONException e) {
e.printStackTrace();
}
/** enjoining getMarkers with the array of json object
* here each JSON object is 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;
/** Parsing and adding each marker to the 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 {
// Latitude extraction
if(!jMarker.isNull("lat")){
lat = jMarker.getString("lat");
}
// Longitude extraction
if(!jMarker.isNull("lng")){
lng = jMarker.getString("lng");
}
marker.put("lat", lat);
marker.put("lng", lng);
} catch (JSONException e) {
e.printStackTrace();
}
return marker;
}
}
Paste this in your MySQL's MainActivity.java:
// enjoining OnClick Event listener for the GoogleMap
mGoogleMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng latlng) {
addMarker(latlng);
sendToServer(latlng);
}
});
// enjoining location retrieval
new RetrieveTask().execute();
}
// Marking lat. long. on the GoogleMaps
private void addMarker(LatLng latlng) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latlng);
markerOptions.title(latlng.latitude + "," + latlng.longitude);
mGoogleMap.addMarker(markerOptions);
}
// Enjoining bg thread to save marker inMySQL server
private void sendToServer(LatLng latlng) {
new SaveTask().execute(latlng);
}
// bg thread to save the marker in 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 = "http://www.yourserverurllocation.com";
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;
}
}
In my app I want to show the multiple marker using latitude and longitude from JSON but when I run the application it only shows one marker, other markers are not shown. Please help - here is my code:
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog progressDialog; // class variable
private void showProgressDialog(String title, String message)
{
progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle(title); // set title
progressDialog.setMessage(message); // set message
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgressDialog("Loading...", "Please wait for few seconds");
// dialog = new ProgressDialog(getActivity().this);
// dialog.setMessage("Loading, please wait");
// dialog.setTitle("Connecting server");
// dialog.show();
// dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
// Date a = new Date();
// a.setTime(System.currentTimeMillis()-(60*60*1000));
// Log.e("onehourback",""+a);*/
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("SingleIMEs");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
// Log.e("object",""+object);
/*try {
array.add(jarray.getJSONObject(i));
Log.e("array",""+array);
} catch (JSONException e)
{
e.printStackTrace();
}*/
for(int j=0; j < 1;j++)
{
latvalue=object.getString("Latitude");
longvalue=object.getString("Longitude");
latt=Double.parseDouble(latvalue);
lng=Double.parseDouble(longvalue);
Log.e("lat",""+latt);
Log.e("lon",""+lng);
}
}
}
//}
return true;
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
//dialog.cancel();
if(progressDialog != null && progressDialog.isShowing())
{
progressDialog.dismiss();
}
/* adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getActivity().getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
*/
}
}
private void setUpMapIfNeeded(View inflatedView) {
mMap = ((MapView) inflatedView.findViewById(R.id.mapView)).getMap();
mMap.clear();
mMap.addMarker(new MarkerOptions().position(new LatLng(latt,lng)).title("eee"));
Log.e("lat",""+latt);
Log.e("lon",""+lng);
mMap.setMyLocationEnabled(true);
if (mMap != null) {
//setUpMap();
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
LatLng latLng = new LatLng(arg0.getLatitude(), arg0.getLongitude());
mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("WePOP"));
// mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)).position( new LatLng(Double.parseDouble(datas.get("Lat")), Double.parseDouble(datas.get("Long")))));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
});
}
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
}
It looks like you're overwriting your latt and lng variables multiple times in this code:
for(int j=0; j < 1;j++)
{
latvalue=object.getString("Latitude");
longvalue=object.getString("Longitude");
latt=Double.parseDouble(latvalue);
lng=Double.parseDouble(longvalue);
Log.e("lat",""+latt);
Log.e("lon",""+lng);
}
I would suggest you create a List that holds some sort of object containing latt and lng information (something like List positions).
Then modify your code in setUpMapIfNeeded to cycle through all your LatLngs. Something like this:
for(LatLng latlng: positions) {
mMap.addMarker(new MarkerOptions().position(new LatLng(latlng.getLat(),latlng.getLng())).title("eee"));
Log.e("Added marker at lat: " + latlng.getLat() + ", lng: " + latlng.getLng());
}
Notice: It's been quite some time since i've used android and google maps, so the code i've written here probably isn't perfect - but the idea should be good :-)
Following is my code:
public class DetailDescription extends FragmentActivity implements LocationListener{
private static String TAG="DetailDescription";
GoogleMap mGoogleMap;
ArrayList<LatLng> mMarkerPoints;
double mLatitude=0;
double mLongitude=0;
private final static int DETAILS_TRUE=1;
private final static int DETAILS_FALSE=2;
private final static int DETAILS_ERROR=3;int position;
ConnectionDetector cd;GPSTracker gps;Boolean isInternetPresent = false;
protected void onCreate(Bundle savedInstanceState) {
cd = new ConnectionDetector(getApplicationContext());
ImageView imageview;
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
setContentView(R.layout.detaildescription);
}
else
{
// Internet connection is not present
// Ask user to connect to Internet
showAlertDialog(DetailDescription.this, "No Internet Connection",
"You don't have internet connection.", false);
}
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.header);
position=getIntent().getIntExtra("position", 0);
SharedData.pos1=position;
TextView txtHeader=(TextView)findViewById(R.id.txtHeader);
txtHeader.setText(SharedData.mAtm[position].name);
TextView adress=(TextView)findViewById(R.id.adress);
adress.setText(SharedData.mAtm[position].address);
Button btnBack=(Button)findViewById(R.id.btnBack);
btnBack.setVisibility(View.VISIBLE);
btnBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(DetailDescription.this,PlacesList.class);
//i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}
});
ImageButton btnNext=(ImageButton)findViewById(R.id.btnNext);
btnNext.setVisibility(View.VISIBLE);
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(DetailDescription.this,PlaceFinder.class);
//i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}
});
locationn();
}
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.ic_launcher: R.drawable.fail);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
private void locationn() {
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
// Initializing
mMarkerPoints = new ArrayList<LatLng>();
// Getting reference to SupportMapFragment of the activity_main
SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
// Getting Map for the SupportMapFragment
mGoogleMap = fm.getMap();
// Enable MyLocation Button in the Map
mGoogleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
else
{
Toast.makeText(DetailDescription.this, "Location can't be retrieved", 5000).show();
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
LatLng startPoint = new LatLng(mLatitude, mLongitude);
drawMarker(startPoint);
LatLng origin = mMarkerPoints.get(0);
LatLng dest = new LatLng(SharedData.mAtm[SharedData.pos1].lat, SharedData.mAtm[SharedData.pos1].lon);
// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
Marker marker= mGoogleMap.addMarker(new MarkerOptions().position(dest).title(SharedData.mAtm[position].address).icon(BitmapDescriptorFactory.fromResource(R.drawable.marker1)));
marker.showInfoWindow();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
// TODO Auto-generated method stub
}
private String getDirectionsUrl(LatLng origin,LatLng dest){
// Origin of route
String str_origin = "origin="+origin.latitude+","+origin.longitude;
// Destination of route
String str_dest = "destination="+SharedData.mAtm[SharedData.pos1].lat+","+SharedData.mAtm[SharedData.pos1].lon;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin+"&"+str_dest+"&"+sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
return url;
}
/** A method to download json data from url */
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();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
/** A class to download data from Google Directions URL */
private class DownloadTask extends AsyncTask<String, Void, String>{
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try{
// Fetching the data from web service
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
/** A class to parse the Google Directions in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{
// 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]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
}catch(Exception e){
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 = null;
PolylineOptions lineOptions = null;
// Traversing through all the routes
for(int i=0;i<result.size();i++){
points = new ArrayList<LatLng>();
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);
lineOptions.width(2);
lineOptions.color(Color.RED);
}
// Drawing polyline in the Google Map for the i-th route
mGoogleMap.addPolyline(lineOptions);
}
}
private void drawMarker(LatLng point){
mMarkerPoints.add(point);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
/**
* For the start location, the color of marker is GREEN and
* for the end location, the color of marker is RED.
*/
if(mMarkerPoints.size()==1){
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
}else if(mMarkerPoints.size()==2){
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
// Add new marker to the Google Map Android API V2
mGoogleMap.addMarker(options);
}
#Override
public void onLocationChanged(Location location) {
// Draw the marker, if destination location is not set
if(mMarkerPoints.size() < 2){
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
LatLng point = new LatLng(mLatitude, mLongitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(point));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
drawMarker(point);
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
Change your condition flow this way,
public class DetailDescription extends FragmentActivity implements LocationListener
{
private static String TAG="DetailDescription";
GoogleMap mGoogleMap;
ArrayList<LatLng> mMarkerPoints;
double mLatitude=0;
double mLongitude=0;
private final static int DETAILS_TRUE=1;
private final static int DETAILS_FALSE=2;
private final static int DETAILS_ERROR=3;int position;
ConnectionDetector cd;GPSTracker gps;Boolean isInternetPresent = false;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
cd = new ConnectionDetector(getApplicationContext());
ImageView imageview;
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
isInternetPresent = cd.isConnectingToInternet();
if ( !isInternetPresent)
{
showAlertDialog(DetailDescription.this, "No Internet Connection",
"You don't have internet connection.", false);
}
else
{
setContentView(R.layout.detaildescription);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.header);
position=getIntent().getIntExtra("position", 0);
SharedData.pos1=position;
TextView txtHeader=(TextView)findViewById(R.id.txtHeader);
txtHeader.setText(SharedData.mAtm[position].name);
TextView adress=(TextView)findViewById(R.id.adress);
adress.setText(SharedData.mAtm[position].address);
Button btnBack=(Button)findViewById(R.id.btnBack);
btnBack.setVisibility(View.VISIBLE);
btnBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(DetailDescription.this,PlacesList.class);
//i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}
});
ImageButton btnNext=(ImageButton)findViewById(R.id.btnNext);
btnNext.setVisibility(View.VISIBLE);
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(DetailDescription.this,PlaceFinder.class);
//i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}
});
locationn();
}
}
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.ic_launcher: R.drawable.fail);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
private void locationn() {
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
// Initializing
mMarkerPoints = new ArrayList<LatLng>();
// Getting reference to SupportMapFragment of the activity_main
SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
// Getting Map for the SupportMapFragment
mGoogleMap = fm.getMap();
// Enable MyLocation Button in the Map
mGoogleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
else
{
Toast.makeText(DetailDescription.this, "Location can't be retrieved", 5000).show();
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
LatLng startPoint = new LatLng(mLatitude, mLongitude);
drawMarker(startPoint);
LatLng origin = mMarkerPoints.get(0);
LatLng dest = new LatLng(SharedData.mAtm[SharedData.pos1].lat, SharedData.mAtm[SharedData.pos1].lon);
// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
Marker marker= mGoogleMap.addMarker(new MarkerOptions().position(dest).title(SharedData.mAtm[position].address).icon(BitmapDescriptorFactory.fromResource(R.drawable.marker1)));
marker.showInfoWindow();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
// TODO Auto-generated method stub
}
private String getDirectionsUrl(LatLng origin,LatLng dest){
// Origin of route
String str_origin = "origin="+origin.latitude+","+origin.longitude;
// Destination of route
String str_dest = "destination="+SharedData.mAtm[SharedData.pos1].lat+","+SharedData.mAtm[SharedData.pos1].lon;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin+"&"+str_dest+"&"+sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
return url;
}
/** A method to download json data from url */
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();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
/** A class to download data from Google Directions URL */
private class DownloadTask extends AsyncTask<String, Void, String>{
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try{
// Fetching the data from web service
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
/** A class to parse the Google Directions in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{
// 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]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
}catch(Exception e){
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 = null;
PolylineOptions lineOptions = null;
// Traversing through all the routes
for(int i=0;i<result.size();i++){
points = new ArrayList<LatLng>();
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);
lineOptions.width(2);
lineOptions.color(Color.RED);
}
// Drawing polyline in the Google Map for the i-th route
mGoogleMap.addPolyline(lineOptions);
}
}
private void drawMarker(LatLng point){
mMarkerPoints.add(point);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
/**
* For the start location, the color of marker is GREEN and
* for the end location, the color of marker is RED.
*/
if(mMarkerPoints.size()==1){
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
}else if(mMarkerPoints.size()==2){
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
// Add new marker to the Google Map Android API V2
mGoogleMap.addMarker(options);
}
#Override
public void onLocationChanged(Location location) {
// Draw the marker, if destination location is not set
if(mMarkerPoints.size() < 2){
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
LatLng point = new LatLng(mLatitude, mLongitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(point));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
drawMarker(point);
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
I have a requirement in which I have an activity which contains Checkboxes and the onChangedEvent of Checkbox should get reflected in other activity which is a map fragment. I am not understanding how to do it. Following is my main activity
public class MainActivity extends FragmentActivity implements LocationListener {
GoogleMap mGoogleMap;
Spinner mSprPlaceType;
String[] mPlaceType=null;
String[] mPlaceTypeName=null;
double mLatitude=0;
double mLongitude=0;
Boolean isHospitalChecked;
Boolean isFireBrigadeChecked;
Boolean isPoliceStationChecked;
SharedPreferences sharedPreferences=null;
HashMap<String, String> mMarkerPlaceLink = new HashMap<String, String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences("instantmessagingmap", MODE_PRIVATE);
isHospitalChecked = sharedPreferences.getBoolean("hospital", false);
isPoliceStationChecked = sharedPreferences.getBoolean("police", false);
isFireBrigadeChecked = sharedPreferences.getBoolean("fire_station", false);
// Array of place types
mPlaceType = getResources().getStringArray(R.array.place_type);
// Array of place type names
mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);
// Creating an array adapter with an array of Place types
// to populate the spinner
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);
// Getting reference to the Spinner
mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);
// Setting adapter on Spinner to set place types
mSprPlaceType.setAdapter(adapter);
Button btnFind;
// Getting reference to Find Button
btnFind = ( Button ) findViewById(R.id.btn_find);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
// Getting reference to the SupportMapFragment
SupportMapFragment fragment = ( SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting Google Map
mGoogleMap = fragment.getMap();
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
mGoogleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
Intent intent = new Intent(getBaseContext(), PlaceDetailsActivity.class);
String reference = mMarkerPlaceLink.get(arg0.getId());
intent.putExtra("reference", reference);
// Starting the Place Details Activity
startActivity(intent);
}
});
// Setting click event lister for the find button
btnFind.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ListViewPlaces.class);
startActivity(intent);
/* int selectedPosition = mSprPlaceType.getSelectedItemPosition();
String type = mPlaceType[selectedPosition];
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?fire");
sb.append("location="+mLatitude+","+mLongitude);
sb.append("&radius=5000");
sb.append("&types="+type);
sb.append("&sensor=true");
sb.append("&key=AIzaSyChHq77IYR_BcjLejdOdUMkn43Ue0VWjeo");
// Creating a new non-ui thread task to download Google place json data
PlacesTask placesTask = new PlacesTask();
// Invokes the "doInBackground()" method of the class PlaceTask
placesTask.execute(sb.toString());*/
}
});
}
if(isHospitalChecked)
{
showMap("hospital");
}
if(isPoliceStationChecked)
{
showMap("police");
}
if(isFireBrigadeChecked)
{
showMap("fire_station");
}
}
private void showMap(String place)
{
int selectedPosition = mSprPlaceType.getSelectedItemPosition();
String type = mPlaceType[selectedPosition];
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?hospital|police|fire_station");
//sb.append(place);
sb.append("location=" + mLatitude + "," + mLongitude);
sb.append("&radius=5000");
//sb.append("&types=" + type);
sb.append("&sensor=true");
sb.append("&key=AIzaSyChHq77IYR_BcjLejdOdUMkn43Ue0VWjeo");
// Creating a new non-ui thread task to download Google
// place json data
PlacesTask placesTask = new PlacesTask();
// Invokes the "doInBackground()" method of the class
// PlaceTask
placesTask.execute(sb.toString());
}
/** A method to download json data from url */
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();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
/** A class, to download Google Places */
private class PlacesTask extends AsyncTask<String, Integer, String>{
String data = null;
// Invoked by execute() method of this object
#Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String result){
ParserTask parserTask = new ParserTask();
// Start parsing the Google places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{
JSONObject jObject;
// Invoked by execute() method of this object
#Override
protected List<HashMap<String,String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
try{
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a List construct */
places = placeJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(List<HashMap<String,String>> list){
// Clears all the existing markers
mGoogleMap.clear();
for(int i=0;i<list.size();i++){
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("lat"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("lng"));
// Getting name
String name = hmPlace.get("place_name");
// Getting vicinity
String vicinity = hmPlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
//This will be displayed on taping the marker
markerOptions.title(name + " : " + vicinity);
// Placing a marker on the touched position
Marker m = mGoogleMap.addMarker(markerOptions);
// Linking Marker id and place reference
mMarkerPlaceLink.put(m.getId(), hmPlace.get("reference"));
}
}
}
#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;
}
#Override
public void onLocationChanged(Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
LatLng latLng = new LatLng(mLatitude, mLongitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
My checkbox activity
public class ListViewPlaces extends Activity
{
SharedPreferences sharedPreferences = null;
TextView tvHospital;
TextView tvPoliceStation;
TextView tvFireBrigade;
CheckBox chBoxHospital;
CheckBox chBoxPoliceStations;
CheckBox chBoxFireBrigade;
Boolean isHospitalChecked;
Boolean isFireBrigadeChecked;
Boolean isPoliceStationChecked;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view_places);
initView();
setView();
}
private void setView()
{
chBoxFireBrigade.setChecked(isFireBrigadeChecked);
chBoxHospital.setChecked(isHospitalChecked);
chBoxPoliceStations.setChecked(isPoliceStationChecked);
}
private void initView()
{
tvHospital = (TextView) findViewById(R.id.list_view_places_tv_hospital);
tvPoliceStation = (TextView) findViewById(R.id.list_view_places_tv_police_staions);
tvFireBrigade = (TextView) findViewById(R.id.list_view_places_tv_fire_brigade);
chBoxFireBrigade = (CheckBox) findViewById(R.id.list_view_places_ch_box_fire_brigade);
chBoxHospital = (CheckBox) findViewById(R.id.list_view_places_ch_box_hospital);
chBoxPoliceStations = (CheckBox) findViewById(R.id.list_view_places_ch_box_police_staions);
sharedPreferences = getSharedPreferences("instantMessaging", MODE_PRIVATE);
isHospitalChecked = sharedPreferences.getBoolean("hospital", false);
isPoliceStationChecked = sharedPreferences.getBoolean("police_station", false);
isFireBrigadeChecked = sharedPreferences.getBoolean("fire", false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.list_view_places, menu);
return true;
}
#Override
public void onBackPressed()
{
SharedPreferences.Editor editor = sharedPreferences.edit();
isHospitalChecked = sharedPreferences.getBoolean("hospital", false);
isPoliceStationChecked = sharedPreferences.getBoolean("police", false);
isFireBrigadeChecked = sharedPreferences.getBoolean("fire_station", false);
if (chBoxFireBrigade.isChecked())
{
editor.putBoolean("fire_station", true);
} else
{
editor.putBoolean("fire_station", false);
}
if (chBoxHospital.isChecked())
{
editor.putBoolean("hospital", true);
} else
{
editor.putBoolean("hospital", false);
}
if (chBoxPoliceStations.isChecked())
{
editor.putBoolean("police", true);
} else
{
editor.putBoolean("police", false);
}
editor.commit();
super.onBackPressed();
}
}
You have to use the same SharedPreferences name in both, in order to write and read to the same table.
Change this line in ListViewPlaces:
sharedPreferences = getSharedPreferences("instantMessaging", MODE_PRIVATE);
To:
sharedPreferences = getSharedPreferences("instantmessagingmap", MODE_PRIVATE);
I have successfully made an activity that shows nearby places. Now I have to retrieve Maps based on spinner value and show the default world map if no value is selected from the spinner. Say I have a spinner in the action bar of an activity, and it consists of various city names, and if I chose New York from the spinner, the map of New York appears in the Map Screen Area. If possible, can Anyone guide me how to do this and also if possible, tell me how to show the famous tourist locations of that city. I have not found any beneficial tutorial on this. Any help would be appreciated.
My NearbyPlacesActivity.java
public class NearbyPlacesActivity extends Activity implements LocationListener {
//instance variables for Marker icon drawable resources
private int userIcon, foodIcon, drinkIcon, shopIcon, otherIcon;
//the map
private GoogleMap theMap;
//location manager
private LocationManager locMan;
//gps tracker and connnection detect to be included
//user marker
private Marker userMarker;
//places of interest
private Marker[] placeMarkers;
//max
private final int MAX_PLACES = 20;//most returned from google
//marker options
private MarkerOptions[] places;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearby_places);
//get drawable IDs
userIcon = R.drawable.yellow_point;
foodIcon = R.drawable.red_point;
drinkIcon = R.drawable.blue_point;
shopIcon = R.drawable.green_point;
otherIcon = R.drawable.purple_point;
//find out if we already have it
if(theMap==null){
//get the map
theMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.the_map)).getMap();
//check in case map/ Google Play services not available
if(theMap!=null){
//ok - proceed
theMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//create marker array
placeMarkers = new Marker[MAX_PLACES];
}
}
}
//location listener functions
#Override
public void onLocationChanged(Location location) {
Log.v("MyMapActivity", "location changed");
updatePlaces(location);
}
#Override
public void onProviderDisabled(String provider){
Log.v("MyMapActivity", "provider disabled");
}
#Override
public void onProviderEnabled(String provider) {
Log.v("MyMapActivity", "provider enabled");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.v("MyMapActivity", "status changed");
}
/*
* update the place markers
*/
private void updatePlaces(Location givenlocation){
//get location manager
double lat = givenlocation.getLatitude();
double lng = givenlocation.getLongitude();
//create LatLng
LatLng lastLatLng = new LatLng(lat, lng);
//remove any existing marker
if(userMarker!=null) userMarker.remove();
//create and set marker properties
userMarker = theMap.addMarker(new MarkerOptions()
.position(lastLatLng)
.title("You are here")
.icon(BitmapDescriptorFactory.fromResource(userIcon))
.snippet("Your last recorded location"));
//move to location
theMap.animateCamera(CameraUpdateFactory.newLatLng(lastLatLng), 3000, null);
//build places query string
#SuppressWarnings("deprecation")
String encodedstr = URLEncoder.encode("food|bar|movie_theater|museum|bank");
String placesSearchStr = "https://maps.googleapis.com/maps/api/place/nearbysearch/" +
"json?location="+lat+","+lng+
"&radius=7000&sensor=true"+
"&types="+encodedstr+
"&key=AIzaSyBqDgqbxFenOtooTivY5YSsJ2JrwBK42hw";//ADD KEY
//execute query
new GetPlaces().execute(placesSearchStr);
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, this);
}
private class GetPlaces extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... placesURL) {
//fetch places
//build result as string
StringBuilder placesBuilder = new StringBuilder();
//process search parameter string(s)
for (String placeSearchURL : placesURL) {
HttpClient placesClient = new DefaultHttpClient();
try {
//try to fetch the data
//HTTP Get receives URL string
HttpGet placesGet = new HttpGet(placeSearchURL);
//execute GET with Client - return response
HttpResponse placesResponse = placesClient.execute(placesGet);
//check response status
StatusLine placeSearchStatus = placesResponse.getStatusLine();
//only carry on if response is OK
if (placeSearchStatus.getStatusCode() == 200) {
//get response entity
HttpEntity placesEntity = placesResponse.getEntity();
//get input stream setup
InputStream placesContent = placesEntity.getContent();
//create reader
InputStreamReader placesInput = new InputStreamReader(placesContent);
//use buffered reader to process
BufferedReader placesReader = new BufferedReader(placesInput);
//read a line at a time, append to string builder
String lineIn;
while ((lineIn = placesReader.readLine()) != null) {
placesBuilder.append(lineIn);
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
return placesBuilder.toString();
}
//process data retrieved from doInBackground
protected void onPostExecute(String result) {
//parse place data returned from Google Places
//remove existing markers
if(placeMarkers!=null){
for(int pm=0; pm<placeMarkers.length; pm++){
if(placeMarkers[pm]!=null)
placeMarkers[pm].remove();
}
}
try {
//parse JSON
//create JSONObject, pass stinrg returned from doInBackground
JSONObject resultObject = new JSONObject(result);
//get "results" array
JSONArray placesArray = resultObject.getJSONArray("results");
//marker options for each place returned
places = new MarkerOptions[placesArray.length()];
//loop through places
for (int p=0; p<placesArray.length(); p++) {
//parse each place
//if any values are missing we won't show the marker
boolean missingValue=false;
LatLng placeLL=null;
String placeName="";
String vicinity="";
int currIcon = otherIcon;
try{
//attempt to retrieve place data values
missingValue=false;
//get place at this index
JSONObject placeObject = placesArray.getJSONObject(p);
//get location section
JSONObject loc = placeObject.getJSONObject("geometry")
.getJSONObject("location");
//read lat lng
placeLL = new LatLng(Double.valueOf(loc.getString("lat")),
Double.valueOf(loc.getString("lng")));
//get types
JSONArray types = placeObject.getJSONArray("types");
//loop through types
for(int t=0; t<types.length(); t++){
//what type is it
String thisType=types.get(t).toString();
//check for particular types - set icons
if(thisType.contains("food")){
currIcon = foodIcon;
break;
}
else if(thisType.contains("bar")){
currIcon = drinkIcon;
break;
}
else if(thisType.contains("movie_theater")){
currIcon = shopIcon;
break;
}
}
//vicinity
vicinity = placeObject.getString("vicinity");
//name
placeName = placeObject.getString("name");
}
catch(JSONException jse){
Log.v("PLACES", "missing value");
missingValue=true;
jse.printStackTrace();
}
//if values missing we don't display
if(missingValue) places[p]=null;
else
places[p]=new MarkerOptions()
.position(placeLL)
.title(placeName)
.icon(BitmapDescriptorFactory.fromResource(currIcon))
.snippet(vicinity);
}
}
catch (Exception e) {
e.printStackTrace();
}
if(places!=null && placeMarkers!=null){
for(int p=0; p<places.length && p<placeMarkers.length; p++){
//will be null if a value was missing
if(places[p]!=null)
placeMarkers[p]=theMap.addMarker(places[p]);
}
}
}
}
#Override
protected void onResume() {
super.onResume();
if(theMap!=null){
//get location manager
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//get last location
Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, this);
updatePlaces(lastLoc);
}
}
#Override
protected void onPause() {
super.onPause();
if(theMap!=null){
locMan.removeUpdates(this);
}
}
}
This is how, you may implement your spinner listener
yourpinner.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
});
you may check this and this for additional reference