Hi i a m writing an application whih gets the current latitude and longitude and convert it to corrsponding address.i can get the lattitude and longitutde but how to convert it to the corresponding address using json. i am new to json. i tried some sample codes butnot getting the address
This is my code
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
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.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.maps.GeoPoint;
public class GMapActivity extends FragmentActivity {
private GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
LocationManager locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener locListener = new GpsActivity(getBaseContext());
locManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, locListener);
if (map == null) {
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
map.setMyLocationEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
private class GpsActivity implements LocationListener{
Marker marker;
Context mcontext;
public GpsActivity(Context context){
super();
mcontext=context;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
double latitude=location.getLatitude();
double longitude=location.getLongitude();
LatLng gpslocation=new LatLng(latitude,longitude);
Toast.makeText(getApplicationContext(),"" +gpslocation,
Toast.LENGTH_LONG).show();
pls help me
thanks in advance
To change back human readable format, you can also use Geocoder but that is not working sometimes because google play service problem. I used this json geocodeing as second option for in case.
Please refer Google Geocoding API
Workflow is pass your latitude and longitude and get current location. Request url gonna be like this.
String reqURL = "http://maps.googleapis.com/maps/api/geocode/json?latlng="+ lat+","+lng +"&sensor=true";
Hopefully, this answer will help you.
public static JSONObject getLocationInfo(double lat, double lng) {
HttpGet httpGet = new HttpGet("http://maps.googleapis.com/maps/api/geocode/json?latlng="+ lat+","+lng +"&sensor=true");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
public static String getCurrentLocationViaJSON(double lat, double lng) {
JSONObject jsonObj = getLocationInfo(lat, lng);
Log.i("JSON string =>", jsonObj.toString());
String currentLocation = "testing";
String street_address = null;
String postal_code = null;
try {
String status = jsonObj.getString("status").toString();
Log.i("status", status);
if(status.equalsIgnoreCase("OK")){
JSONArray results = jsonObj.getJSONArray("results");
int i = 0;
Log.i("i", i+ "," + results.length() ); //TODO delete this
do{
JSONObject r = results.getJSONObject(i);
JSONArray typesArray = r.getJSONArray("types");
String types = typesArray.getString(0);
if(types.equalsIgnoreCase("street_address")){
street_address = r.getString("formatted_address").split(",")[0];
Log.i("street_address", street_address);
}else if(types.equalsIgnoreCase("postal_code")){
postal_code = r.getString("formatted_address");
Log.i("postal_code", postal_code);
}
if(street_address!=null && postal_code!=null){
currentLocation = street_address + "," + postal_code;
Log.i("Current Location =>", currentLocation); //Delete this
i = results.length();
}
i++;
}while(i<results.length());
Log.i("JSON Geo Locatoin =>", currentLocation);
return currentLocation;
}
} catch (JSONException e) {
Log.e("testing","Failed to load JSON");
e.printStackTrace();
}
return null;
}
As my experience, only device generated latitude and longitude will work.
Then call
String currentLocation = getCurrentLocationViaJSON(lat, lng);
Related
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 {
}
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.
I'm try to develop a location based app. I try to draw a route but program returns to me a NullPointerException.
I faced this problem at line 361.
MapsActivity.java
package com.example.tcarcelik.glympse;
/**
* Created by TCARCELIK on 09.07.2015.
*/
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.provider.ContactsContract;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.android.gms.ads.formats.NativeContentAd;
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.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
public class MapsActivity extends FragmentActivity implements Parcelable,LocationListener {
LatLng destination;
Polyline line;
Button mBtnDest;
Button btnDraw;
Button btnOk;
Button btnNextStep;
int counter;
GoogleMap mMap;
EditText editPlace_Dest;
ArrayList<LatLng> markerPoints;
ArrayList<LatLng> list;
private LocationManager locationManager;
private static final long MIN_TIME = 400;
private static final float MIN_DISTANCE = 1000;
double mLatitude = 0;
double mLongitude = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
markerPoints = new ArrayList<LatLng>();
SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
Criteria criteria = new Criteria();
btnDraw = (Button) findViewById(R.id.btn_draw);
btnOk = (Button) findViewById(R.id.btn_ok);
mMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
destination = point;
mMap.clear();
drawMarker(point);
markerPoints.add(point);
FrameLayout mapLayout = (FrameLayout)findViewById(R.id.map);
btnDraw.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
double lat1 = mMap.getMyLocation().getLatitude();
double long1 = mMap.getMyLocation().getLongitude();
LatLng latlng = new LatLng(lat1, long1);
String url = getDirectionsUrl(latlng, destination);
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(url);
}
});
// Button of OK
btnOk.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("listToPass", list);
// CameraPosition myCam = mMap.getCameraPosition();
ArrayList<Double> first_param = new ArrayList<Double>();
ArrayList<Double> second_param = new ArrayList<Double>();
for(LatLng point:list){
first_param.add(point.latitude);
second_param.add(point.longitude);
}
Collections.sort(first_param);
Collections.sort(second_param);
double lat_min = first_param.get(0);
double lat_max = first_param.get(first_param.size()-1);
double lng_min = second_param.get(0);
double lng_max = second_param.get(second_param.size()-1);
LatLng bound_1 = new LatLng(lat_min,lng_min);
LatLng bound_2 = new LatLng(lat_max,lng_max);
LatLngBounds mainbound = new LatLngBounds(bound_1,bound_2);
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(mainbound,100));
CameraPosition myCam = mMap.getCameraPosition();
i.putExtra("cameraPosition", myCam);
startActivity(i);
}
});
}
});
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, (LocationListener) this);
}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
mMap.setMyLocationEnabled(true);
if (mMap != null) {
// setUpMap();
}
}
}
public GoogleMap get_MapsMap(){
return mMap;
}
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="+dest.latitude+","+dest.longitude;
// 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;
}
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;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
}
/** A class, to download Places from Geocoding webservice */
private class DownloadTask extends AsyncTask<String, Integer, String> {
String data = null;
ProgressDialog progressDialog;
// 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
// Draw path'in onPostExecute ' u
#Override
protected void onPostExecute(String result){
// Instantiating ParserTask which parses the json data from Geocoding webservice
// in a non-ui thread
ParserTask parserTask = new ParserTask();
// Start parsing the places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
drawPath(result); // Ben ekledim
if(progressDialog.isShowing()){
progressDialog.dismiss();
}
}
#Override
protected void onPreExecute() {
if(progressDialog == null){
progressDialog = new ProgressDialog(MapsActivity.this);
progressDialog.setMessage("Drawing route");
progressDialog.show();
}
}
}
/** A class to parse the Geocoding Places in non-ui thread */
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;
GeocodeJSONParser parser = new GeocodeJSONParser();
try{
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a an ArrayList */
places = parser.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){
}
}
//YENI EKLENENLER
private void drawMarker(LatLng point){
markerPoints.add(point);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
mMap.addMarker(options);
}
public void drawPath(String result){
try {
final JSONObject jsonObject = new JSONObject(result);
JSONArray routeArray = jsonObject.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
list = (ArrayList<LatLng>) decodePoly(encodedString);
PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
for (int z = 0; z < list.size(); z++) {
LatLng point = list.get(z);
options.add(point);
}
line = mMap.addPolyline(options);
// Animate camera after drawing route
ArrayList<Double> first_param = new ArrayList<Double>();
ArrayList<Double> second_param = new ArrayList<Double>();
for(LatLng point:list){
first_param.add(point.latitude);
second_param.add(point.longitude);
}
Collections.sort(first_param);
Collections.sort(second_param);
double lat_min = first_param.get(0);
double lat_max = first_param.get(first_param.size()-1);
double lng_min = second_param.get(0);
double lng_max = second_param.get(second_param.size()-1);
LatLng bound_1 = new LatLng(lat_min,lng_min);
LatLng bound_2 = new LatLng(lat_max,lng_max);
LatLngBounds mainbound = new LatLngBounds(bound_1,bound_2);
mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(mainbound, 100));
// Animate camera after drawing route
} catch (JSONException e) {
e.printStackTrace();
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
mMap.moveCamera(cameraUpdate);
locationManager.removeUpdates((LocationListener) this);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
//YENI EKLENENLER
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
public void onMyLocationChange(Location location) {
// TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude of the current 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));
// Setting latitude and longitude in the TextView tv_location
// tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
please, debug and make sure you are correctly downloading the file, check the downloadUrl(String strUrl) method and make sure it reaches line 256. i believe the problem is with the download method.
i used the code on my phone bellow to get address { country, street, city}, but it didnt work for many inputs, why? and sometimes crashing. please how to get the full address by passing Longitude and Latitude to a method that returns all the available address to this Longitude and Latitude. can you please provide me with the answer to get best result. help me.
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Get_Location_Name extends Activity implements OnClickListener {
private EditText ET1;
private EditText ET2;
private TextView TV1;
private Button B1;
static String result ="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location_name);
ET1=(EditText)this.findViewById(R.id.ET1_location_name);
ET2=(EditText)this.findViewById(R.id.ET2_location_name);
TV1=(TextView)this.findViewById(R.id.TV1_Location_name);
B1=(Button)this.findViewById(R.id.B1_Location_name);
B1.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
String s=null;
if(!ET1.getText().toString().isEmpty() && !ET2.getText().toString().isEmpty())
{
if(this.isOnline())
{
for(int i=0;i<=10;i++)
{
s=getAddressFromLocation(Double.parseDouble(ET2.getText().toString()),
Double.parseDouble(ET1.getText().toString()),this);
}
if(s!=null)
{
Log.d("ssss","s"+s);
TV1.setText(s);
}
else
TV1.setText("s is null");
}
else
TV1.setText("no internet connection");
}
else
TV1.setText("Enter the Lat. and Lon.");
}
public boolean isOnline() {
// code to check connectivity // it works fine(no problems)
}
here is the method that i want to modify
public static String getAddressFromLocation(final double lon,final double lat, final Context context)
{
Thread thread = new Thread() {
#Override public void run()
{
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> list = geocoder.getFromLocation(
lat, lon, 1);
if (list != null && list.size() > 0)
{
Address address = list.get(0);
result = " "+address.getAddressLine(0) + ", " + address.getLocality()+","+address.getCountryName();
}
}
catch (IOException e)
{
Log.e("fafvsafagag", "Impossible to connect to Geocoder", e);
}
}
};
thread.start();
return result;
}
}
please answer my question.
There is a known issue that Geocoder doesn't always returns a value. See Geocoder doesn't always return a value and geocoder.getFromLocationName returns only null. You can try to send a request 3 times in a for loop. It should be able to return atleast once. If not then, their might be a connection issue or can be other issues like server did not reply to your request. For me sometimes it never returned anything even if it was connected to internet. Then, I used this much more reliable way to get the address everytime:
//lat, lng are Double variables containing latitude and longitude values.
public JSONObject getLocationInfo() {
//Http Request
HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?latlng="+lat+","+lng+"&sensor=true");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
//Create a JSON from the String that was return.
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
I called the function as follows to get the complete address:
JSONObject ret = getLocationInfo(); //Get the JSON that is returned from the API call
JSONObject location;
String location_string;
//Parse to get the value corresponding to `formatted_address` key.
try {
location = ret.getJSONArray("results").getJSONObject(0);
location_string = location.getString("formatted_address");
Log.d("test", "formattted address:" + location_string);
} catch (JSONException e1) {
e1.printStackTrace();
}
You can call this inside AsyncTask or a new thread. I used Asynctask for the same.
Hope this helps.This worked for me. If you replace the URL with the lat and longitude coordinates and see the returned JSON object in a web browser. You'll see what just happened.
I want to get the latitude and longitude positions from the Geo Coding API. I wrote the following code for that.
package com.appulento.mapsexample.pack;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;
import com.mapsinfo.pack.DBAdapter;
public class MapsMianClass extends MapActivity {
private MapController mapController;
private LocationManager locationManager;
private MapView mapView;
List<Overlay> listOfOverlays ;
private List mapOverlays;
private Projection projection;
private Geocoder geoCoder;
private MapController mc;
private GeoPoint gP;
private DBAdapter db;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//here i am giving the Maps Geo coding API URL
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true_or_false"));
startActivity(intent);
//starting the Intent
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
//default method of maps Activity.
}
}
Is it correct? How can I incorporate JSON in the above code for getting latitude and longitude values from the URL?
Try this Code
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
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.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AsyncTask<String, Void, Void> stringVoidVoidAsyncTask = new AsyncTask<String, Void, Void>() {
BufferedReader in;
#Override
protected Void doInBackground(String... strings) {
String url = "";
if (strings.length > 0) {
url = strings[0];
} else {
return null;
}
try {
HttpClient httpClient = new DefaultHttpClient();// Client
HttpGet getRequest = new HttpGet();
getRequest.setURI(new URI(url));
HttpResponse response = httpClient.execute(getRequest);
in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String page = sb.toString();
JSONObject jsonObject = new JSONObject(page);
JSONArray jsonArray = (JSONArray) jsonObject.get("results");
if (jsonArray.length() > 0) {
jsonObject = (JSONObject) jsonArray.get(0);
jsonObject = (JSONObject) jsonObject.get("geometry");
JSONObject location = (JSONObject) jsonObject.get("location");
Double lat = (Double) location.get("lat");
Double lng = (Double) location.get("lng");
System.out.println("lat - " + lat + " , lon - " + lng);
}
System.out.println(page);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
};
stringVoidVoidAsyncTask.execute("http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true");
}
}
And do add permission in AndroidManifest for Internet
<uses-permission android:name="android.permission.INTERNET"/>
And for next time do homework before asking question do googleing first. Hope this help you.
What are you want to start in StartActivity() method in Activity's onCreate()?
You should go for http request using HttpClient
and parse the response from it