I followed this tutorial: http://android-er.blogspot.com/2013/03/embed-google-map-in-webview.html
I'm trying to just use the Google Map in the WebView, but it can't get my current location. I've enabled JavaScript on the WebView. What else do I have to enable?
Does anyone know why that might be? Shouldn't it prompt me to use my current location?
Note that I am not interested in using a MapView as an alternative whatsoever. I'm trying to find out what I need to set on the WebView or maybe on the device's location services?
You should permit the web view to access your location by overriding the method onGeolocationPermissionsShowPrompt like this:
webView.setWebChromeClient(new WebChromeClient(){
#Override
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
callback.invoke(origin, true, false);
}
});
On API 5.x and below, you will need
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
in your AndroidManifest.xml.
But to allow permissions for geolocation on API 6.0+, you have to request the permission at runtime.
To do this, use
private String mGeolocationOrigin;
private GeolocationPermissions.Callback mGeolocationCallback;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// other setup
myWebView.setWebChromeClient(new MyWebChromeClient());
}
private WebChromeClient mWebChromeClient = new WebChromeClient() {
#Override
public void onGeolocationPermissionsShowPrompt(String origin,
GeolocationPermissions.Callback callback) {
// Geolocation permissions coming from this app's Manifest will only be valid for devices with API_VERSION < 23.
// On API 23 and above, we must check for permission, and possibly ask for it.
final String permission = Manifest.permission.ACCESS_FINE_LOCATION;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||
ContextCompat.checkSelfPermission(MainActivity.this, permission) == PackageManager.PERMISSION_GRANTED) {
// we're on SDK < 23 OR user has already granted permission
callback.invoke(origin, true, false);
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permission)) {
// user has denied this permission before and selected [/] DON'T ASK ME AGAIN
// TODO Best Practice: show an AlertDialog explaining why the user could allow this permission, then ask again
} else {
// ask the user for permissions
ActivityCompat.requestPermissions(MainActivity.this, new String[] {permission}, RP_ACCESS_LOCATION);
mGeolocationOrigin = origin;
mGeolocationCallback = callback;
}
}
}
}
and receive the result:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case RP_ACCESS_LOCATION:
boolean allow = false;
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// user has allowed these permissions
allow = true;
}
if (mGeolocationCallback != null) {
mGeolocationCallback.invoke(mGeolocationOrigin, allow, false);
}
break;
}
}
in your activity.
You can try GreenDroid with Google Maps.
Checkt it out: https://github.com/cyrilmottier/GreenDroid
You'd have to enable android.permission.ACCESS_FINE_LOCATION and android.permission.INTERNET,
Create a LocationManager instance and LocationListener instance
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
and add onLocationChanged(Location loc) method that inside of it have your loc generate the longitude and latitude (String long = loc.getLongitude(); String lat = loc.getLatitude();)
and now use long, lat to generate your mapPath string and continue to generate the WebView
You can use this for ref: http://www.rdcworld-android.blogspot.in/2012/01/get-current-location-coordinates-city.html
Related
I am displaying Map using Map view and before API 23 my App is Working fine and showing current location but when I run on 23 and above it's not showing current location.My code is as follow:
mMap = googleMap;
mMap.getUiSettings().setMapToolbarEnabled(false);
LatLng loc = new LatLng(currentLatitude, currentLongitude);
//mMap.addMarker(new MarkerOptions().position(loc).title(currentLocation + ", none"));
//mMap.moveCamera(CameraUpdateFactory.newLatLng(loc));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 14.0f));
if (ActivityCompat.checkSelfPermission(MapClass.this.getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MapClass.this.getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
help me?
I might be a little late, but this answer will help people, who are having the same issue and want to run their app on both the versions. The catch is that for API's more than 21, you need to ask for Run time permission.
Firstly, I created a function named gettingLocationBasedOnApiVersion(mMap) in which I put all the code for which I used user's location. But beforehand, in the onMapReady()I checked for the API version and if the API version is more than 21, I asked for permissions.
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if(Build.VERSION.SDK_INT <= 21){
gettingLocationBasedOnApiVersion(mMap);
Toast.makeText(getApplicationContext(), "APK less than 21", Toast.LENGTH_LONG).show();
}else{
Log.i("SDK Version", "SDK more than 21 will require permissions on run time");
Toast.makeText(getApplicationContext(), "APK greater than 21", Toast.LENGTH_LONG).show();
enableMyLocation();
}
}
Then In the enable function I asked for the run time permissions.
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
private boolean mPermissionDenied = false;
private void enableMyLocation() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Permission to access the location is missing.
PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
Manifest.permission.ACCESS_FINE_LOCATION, true);
} else if (mMap != null) {
// Access to the location has been granted to the app.
mMap.setMyLocationEnabled(true);
gettingLocationBasedOnApiVersion(mMap);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
return;
}
if (PermissionUtils.isPermissionGranted(permissions, grantResults,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Enable the my location layer if the permission has been granted.
enableMyLocation();
} else {
// Display the missing permission error dialog when the fragments resume.
mPermissionDenied = true;
}
}
#Override
protected void onResumeFragments() {
super.onResumeFragments();
if (mPermissionDenied) {
// Permission was not granted, display error dialog.
showMissingPermissionError();
mPermissionDenied = false;
}
}
/**
* Displays a dialog with error message explaining that the location permission is missing.
*/
private void showMissingPermissionError() {
PermissionUtils.PermissionDeniedDialog
.newInstance(true).show(getSupportFragmentManager(), "dialog");
}
For better understanding, use you can refer the Places Class on my github page.
PS. Don't forget to add the PermissionUtils Class in your app folder.
Checking the document about Requesting Permissions at Run Time it is stated that:
Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. This approach streamlines the app install process, since the user does not need to grant permissions when they install or update the app. It also gives the user more control over the app's functionality; for example, a user could choose to give a camera app access to the camera but not to the device location. The user can revoke the permissions at any time, by going to the app's Settings screen.
If the device is running Android 6.0 or higher, and your app's target SDK is 23 or higher: The app has to list the permissions in the manifest, and it must request each dangerous permission it needs while the app is running. The user can grant or deny each permission, and the app can continue to run with limited capabilities even if the user denies a permission request
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
return;
}
if (PermissionUtils.isPermissionGranted(permissions, grantResults,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Enable the my location layer if the permission has been granted.
enableMyLocation();
} else {
// Display the missing permission error dialog when the fragments resume.
mPermissionDenied = true;
}
}
The ApiDemos repository on GitHub includes samples that demonstrate the use of location on a map:
MyLocationDemoActivity: Using the My Location layer, including runtime permissions
LocationSourceDemoActivity: Using a custom LocationSource
Hope this helps.
I am using the code as shown in this https://developers.google.com/drive/android/auth#connecting_and_authorizing_the_google_drive_android_api
In my app I click to connect to Drive, but it results in this line being executed
connectionResult.startResolutionForResult(this, 1);
As the connection fails.
Then it opens an account menu for me to choose an account. When I click it then the dialog dismisses and I still can not connect to Google Drive because everytime the result code is 0
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
mGoogleApiClient.connect();
}
break;
}
}
I would assume the code is correct, but does anyone know what I need to do to prevent is canceling? I believe I set up my credentials correctly for the OA Auth
I tried using the Drive demo code by Google here and I was able to run the android sample.
Check their implementation of authentication and try to compare it with yours. Here's the relevant part:
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addScope(Drive.SCOPE_APPFOLDER) // required for App Folder sample
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
mGoogleApiClient.connect();
}
/**
* Handles resolution callbacks.
*/
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_RESOLUTION && resultCode == RESULT_OK) {
mGoogleApiClient.connect();
}
}
I was able to login successfully and tried out some of the features.
If you're going to use this sample, don't forget to setup your Credentials like Oauth CliendID and indicate the correct package name indicated in the Getting Started guide.
Here's what it looks like:
This is the link that i have refereed but when i enter the name like atm or school in search box it gives me error in
PlacesDisplayTask.java on googleMap.clear()
NullPointer exception
http://javapapers.com/android/find-places-nearby-in-google-maps-using-google-places-apiandroid-app/
I tried another code
this is
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_neighborhood);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
/* SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
*/
// 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
fragment.getMapAsync(this);
// Enabling MyLocation in Google Map
// 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
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider,this );
// Setting click event lister for the find button
btnFind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int selectedPosition = mSprPlaceType.getSelectedItemPosition();
String type = mPlaceType[selectedPosition];
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location=" + mLatitude + "," + mLongitude);
sb.append("&radius=5000");
sb.append("&types=" + type);
sb.append("&sensor=true");
sb.append("&key=YOUR_API_KEY");
// 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());
}
});
}
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
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
mGoogleMap.addMarker(markerOptions);
}
}
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
googleMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(19.0330488, 73.0296625);
googleMap.addMarker(new MarkerOptions().position(sydney).title("CBD"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
googleMap.setMinZoomPreference(15.0f);
googleMap.setMaxZoomPreference(20.0f);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
googleMap.setMyLocationEnabled(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 onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Neighborhood Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://com.example.soulsystem_4.myapplication/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Neighborhood Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://com.example.soulsystem_4.myapplication/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
}
What shoul i pass 4th parameter in locationManager.requestLocationUpdates(provider, 20000, 0, );
it is always saying cast 4th parameter to location listener and when i cast it still it gives me error cannot be cast to android.location.LocationListener
Change Location listener to ClientAngent ist new in api. They I ahve changed it.
Refer https://developers.google.com/places/android-api/
I want to use google map v2 to load the map using either gps or internet, I can do it using just internet.
when I connect my application to internet, the map is loaded successfully, but if i used just gps the map doesn't show even though I have already activiate the gps in my phone and in my app.
this is my code, first i get my location then i load the mapp
setContentView(R.layout.google_map_layout);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
} else {
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
Toast.makeText(RestaurantsNearBy.this,
location.getLatitude() + "", Toast.LENGTH_LONG).show();
LatLng currentLocation = new LatLng(location.getLatitude(),
location.getLongitude());
new getRestaurantNearBy().execute(currentLocation.latitude,
currentLocation.longitude);
map = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
map.setInfoWindowAdapter(new InfoWindowAdapter() {
private final View window = getLayoutInflater().inflate(
R.layout.restaurant_marker, null);
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
TextView tv_title = ((TextView) window
.findViewById(R.id.tv_title));
TextView tv_description = ((TextView) window
.findViewById(R.id.tv_description));
ImageView iv_image = ((ImageView) window
.findViewById(R.id.iv_image));
AddressMap oneAddres = markersMap.get(marker);
tv_title.setText(oneAddres.getRestaurant().getName());
tv_description.setText(oneAddres.getDescription());
Restaurant r = markersMap.get(marker).getRestaurant();
if (Restaurant.getRestaurant(r.getID()) != null) {
if (Restaurant.getRestaurant(r.getID()).getImage() != null) {
iv_image.setImageBitmap(Restaurant
.getRestaurant(r.getID()).getImage());
} else {
try {
iv_image.setImageBitmap(r
.getImageFromWebService());
} catch (Exception e) {
iv_image.setImageResource(R.drawable.unknown);
}
}
} else {
iv_image.setImageBitmap(r.getImageFromWebService());
}
return window;
}
});
map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
final AddressMap oneAddress = markersMap.get(marker);
AlertDialog alertDialog3 = new AlertDialog.Builder(
RestaurantsNearBy.this).create();
alertDialog3.setTitle("Order !");
alertDialog3
.setMessage("Do you want to order from the restaurant "
+ oneAddress.getRestaurant().getName());
alertDialog3.setIcon(R.drawable.more_information);
alertDialog3.setButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
Basket.setRestaurant(oneAddress
.getRestaurant());
dialog.dismiss();
Intent addAddressIntent = new Intent(
RestaurantsNearBy.this,
OrderMeal.class);
startActivity(addAddressIntent);
}
});
alertDialog3.setButton2("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
alertDialog3.show();
}
});
// Move the camera instantly to hamburg with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(
currentLocation, 15));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
Log.d("Provider ", provider + " has been selected.");
onLocationChanged(location);
} else {
Toast.makeText(RestaurantsNearBy.this, "Sorry we couldn't define your location",
Toast.LENGTH_SHORT).show();
}
}
You should use proper tags, Google Maps can be found on loads of platforms, and you have a question about the android versions, so at least add Android tag.
On the question: Google Maps NEEDS active internet connection, when you first load the maps. V2 does some decent caching on your SD card (sometimes a bit excessive too), allowing you to later check thoose already loaded maps offline, but the principle is: no active internet connection, no Google Maps.
ps: GPS is NOT an internet connection.
By default you can't load the map data properly if you aren't connected with wifi or mobile connection. GPS only lets you find your position.
I am trying to implement jsr-179 APi into Nokia Symbian phone for periodic location update using setLocationListener through J2me. In emulator it is working fine. While I installed Midlet on the device nokia 5230, it is given NullPointerException and the application is automatically terminating. What might be possible causes?
Below is my class, I am instantiating object for this class on a form in netbeans
class MovementTracker implements LocationListener {
LocationProvider provider;
Location lastValidLocation;
UpdateHandler handler;
boolean done;
public MovementTracker() throws LocationException
{
done = false;
handler = new UpdateHandler();
new Thread(handler).start();
//Defining Criteria for Location Provider
/*
Criteria cr = new Criteria();
cr.setHorizontalAccuracy(500);
*/
//you can place cr inside getInstance
provider = LocationProvider.getInstance(null);
//listener,interval,timeout,int maxAge
//Passing -1 selects default interval
// provider.setLocationListener(MovementTracker.this, -1, -1, -1);
provider.setLocationListener(MovementTracker.this, -1, 30000, 30000);
}
public void locationUpdated(LocationProvider provider, Location location)
{
handler.handleUpdate(location);
batteryLevel = System.getProperty("com.nokia.mid.batterylevel");
sn = System.getProperty("com.nokia.mid.networksignal");
localTime = System.currentTimeMillis();
Send_Location();
}
public void providerStateChanged(LocationProvider provider, int newState)
{
}
class UpdateHandler implements Runnable
{
private Location updatedLocation = null;
// The run method performs the actual processing of the location
public void run()
{
Location locationToBeHandled = null;
while (!done)
{
synchronized(this)
{
if (updatedLocation == null)
{
try
{
wait();
}
catch (Exception e)
{
// Handle interruption
}
}
locationToBeHandled = updatedLocation;
updatedLocation = null;
}
// The benefit of the MessageListener is here.
// This thread could via similar triggers be
// handling other kind of events as well in
// addition to just receiving the location updates.
if (locationToBeHandled != null)
processUpdate(locationToBeHandled);
}
try
{
Thread.sleep(10000); //Sleeps for 10 sec & then sends the data
}
catch (InterruptedException ex)
{
}
}
public synchronized void handleUpdate(Location update)
{
updatedLocation = update;
notify();
}
private void processUpdate(Location update)
{
latitude = update.getQualifiedCoordinates().getLatitude();
longitude = update.getQualifiedCoordinates().getLongitude();
altitude = update.getQualifiedCoordinates().getAltitude();
}
}
}
public MovementTracker() throws LocationException
...
I have not written any code for handling LocationException.
No code is very dangerous practice, just search the web for something like "java swallow exceptions".
It is quite possible that because of implementation specifics Nokia throws LocationException where emulator does not throw it. Since you don't handle exception this may indeed crash you midlet at Nokia - and you wouldn't know the reason for that because, again, you have written no code to handle it.
How can I catch that exception?
The simplest thing you can do is to display an Alert with exception message and exit the midlet after user reads and dismisses alert