.getLatitude and .getLongitude not working - java

I am new to android and I am trying to make this application where I need location co-ordinates of my current position and show my position on the map. all the other parts of the app run quite well until just when ever I try to get the latitude and longitude from the fusedLocationApi. I have followed this tutorial Get the Last Known Location and have tried to implement it on Google Map Activity.
here is my java file:
package com.example.deep.app_project;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.plus.Plus;
public class Map extends FragmentActivity implements GoogleMap.OnMyLocationChangeListener,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
LocationManager lm;
TextView lt, ln;
String provider;
Location l;
double lon= 0, lat =0;
GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
setUpMapIfNeeded();
client = new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
client.connect();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
mMap.setMyLocationEnabled(true);
}
public void button_Map_Back(View v){
Intent MainActivityIntent = new Intent(Map.this, MainActivity.class);
startActivity(MainActivityIntent);
finish();
}
#Override
public void onConnected(Bundle bundle) {
l = LocationServices.FusedLocationApi.getLastLocation(client);
if (l != null) {
lt.setText(String.valueOf(l.getLatitude()));
ln.setText(String.valueOf(l.getLongitude()));
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onMyLocationChange(Location location) {
lt.setText(String.valueOf(location.getLatitude()));
ln.setText(String.valueOf(location.getLongitude()));
}
here is my .xml file :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.deep.app_project" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but are recommended.
-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Distance_timer"
android:label="#string/title_activity_distance_timer" >
</activity>
<activity
android:name=".Journey_type"
android:label="#string/title_activity_journey_type" >
</activity>
<activity
android:name=".prev_stat_fragment"
android:label="#string/title_activity_prev_stat_fragment" >
</activity>
<activity
android:name=".Result"
android:label="#string/title_activity_result" >
</activity>
<activity
android:name=".settings_fragment"
android:label="#string/title_activity_settings_fragment" >
</activity>
<activity
android:name=".SimpleFragmentActivity"
android:label="#string/title_activity_simple_fragment" >
</activity>
<activity
android:name=".Time_timer"
android:label="#string/title_activity_time_timer" >
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyD-LoJLRIyTF2mI5HdKULNk1QhBAQlhkRQ"/>
<activity
android:name=".Map"
android:label="#string/title_activity_map" >
</activity>
</application>

I have recently done this... and found it confusing to deal with varying different documentation.
I found it easier to use OnMyLocationChangeListener:
Activity implements GoogleMap.OnMyLocationChangeListener
then Override onLocationChanged:
#Override
public void onMyLocationChange(Location location) {
LatLng pos = new LatLng(location.getLatitude(),location.getLongitude());
CameraUpdate mLoc = CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder().target(pos).zoom(ZOOM_LEVEL).build());
map.moveCamera(mLoc);
mLocMarker = map.addMarker(new MarkerOptions()
.title(TITLE)
.snippet(SNIPPET)
.position(pos)
.draggable(true));
mLocMarker.showInfoWindow();
map.setOnMyLocationChangeListener(null);
}

Related

My Maps Activity crashes as soon as it loads [duplicate]

This question already has answers here:
Android permission doesn't work even if I have declared it
(11 answers)
Closed 2 years ago.
Upon accessing the Maps Activity, it crashes. I've tried switching out the Activity with a generic Maps Activity which does work, and I've rolled back to a previous version that I know worked all to no avail.
This is the Android Java:
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Camera;
import android.location.Location;
import com.firebase.geofire.GeoFire;
import com.firebase.geofire.GeoLocation;
import com.google.android.gms.location.LocationListener;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApi;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.internal.GoogleApiAvailabilityCache;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
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.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class DriverMapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location driverLastLocation;
LocationRequest driverLocationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_driver_maps);
// 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);
Button buttonLogout = findViewById(R.id.buttonLogout);
buttonLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(DriverMapsActivity.this, MainActivity.class);
startActivity(intent);
finish();
return;
}
});
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
protected synchronized void buildGoogleApiClient(){
mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
driverLastLocation = location;
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("driversClear");
GeoFire geoFire = new GeoFire(ref);
geoFire.setLocation(userID, new GeoLocation(location.getLatitude(), location.getLongitude()));
}
#Override
public void onConnected(#Nullable Bundle bundle) {
driverLocationRequest = new LocationRequest();
driverLocationRequest.setInterval(1000);
driverLocationRequest.setFastestInterval(2000);
driverLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, driverLocationRequest, (com.google.android.gms.location.LocationListener) this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onStop(){
super.onStop();
String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("driversClear");
GeoFire geoFire = new GeoFire(ref);
geoFire.removeLocation(userID);
}
}
I'm new to Android Dev so I'm not sure if it is particularly vital to debugging this kind of issue but here is the layout XML thing
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DriverMapsActivity" >
<Button
android:id="#+id/buttonLogout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Logout" />
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
and I'm not sure if I should share the AndroidManifest but I feel like it is important
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity android:name=".CustomerMapsActivity" >
</activity>
<activity android:name=".TestClass" />
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".DriverMapsActivity"
android:label="#string/title_activity_driver_maps" />
<activity android:name=".DriverLogin" />
<activity android:name=".DriverRegistration" />
<activity android:name=".CustomerLogin" />
<activity android:name=".CustomerRegistration" />
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Also if anyone can tell me why the built in debugger isn't notifying me of this error that would be appreciated (as in do I need to toggle a setting or install something extra?)
Thanks
Can you check the 'Run' tab for error, instead of Logcat. If the app crashes as soon as it starts, logs may be present in 'Run' tab.

My application is implementing a Google map capabiity. I amd getting a location permission error on

I am implementing a Google Map into my application which includes setting the current location of the user. I have added the ACCESS_FINE_LOCATION into the application manifest and my gradle file uses a minimum SDK of 23. The device emulator that I am running is also 23.
My understanding is that with version 23 I do not need to ask for permission, as that is handled with the app installation or upgrade.
The application is crashing saying that I need to allow location access (see attached logcat entry). It is on the statement (line 64) on the attached MapsActivity.java
mMap.setMyLocationEnabled(true);
MapAcitivity.java
package com.grgapps.checkingin;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements GoogleMap.OnMyLocationButtonClickListener,
GoogleMap.OnMyLocationClickListener, ActivityCompat.OnRequestPermissionsResultCallback ,
OnMapReadyCallback {
private GoogleMap mMap;
private static final String MAPVIEW_BUNDLE_KEY = "MapViewBundleKey";
private MapView mMapView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
Bundle mapViewBundle = null;
if (savedInstanceState != null) {
mapViewBundle = savedInstanceState.getBundle(MAPVIEW_BUNDLE_KEY); }
//mMapView = (MapView) findViewById(R.id.map);
//mMapView.onCreate(mapViewBundle);
mapFragment.getMapAsync(this);
}
/**
* 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) {
mMap = googleMap;
// Add a marker in Gordon and move the camera
LatLng gordon = new LatLng(46.218972, -91.910414);
mMap.addMarker(new MarkerOptions().position(gordon).title("Home"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(gordon));
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//UiSettings.setZoomControlsEnabled(true);
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(this::onMyLocationButtonClick);
mMap.setOnMyLocationClickListener(this::onMyLocationClick);
}
public void onMyLocationClick(#NonNull Location location) {
Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
}
public boolean onMyLocationButtonClick() {
Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
// Return false so that we don't consume the event and the default behavior still occurs
// (the camera animates to the user's current position).
return false;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Bundle mapViewBundle = outState.getBundle(MAPVIEW_BUNDLE_KEY);
if (mapViewBundle == null) {
mapViewBundle = new Bundle();
outState.putBundle(MAPVIEW_BUNDLE_KEY, mapViewBundle);
}
mMapView.onSaveInstanceState(mapViewBundle);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode != 0) {
return;
}
if (PermissionUtils.isPermissionGranted(permissions, grantResults, Manifest.permission.ACCESS_FINE_LOCATION)) {
// Enable the my location layer if the permission has been granted.
enableMyLocation();
} else {
// Permission was denied. Display an error message
// ...
}
}
private void enableMyLocation() {
// [START maps_check_location_permission]
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mMap != null) {
mMap.setMyLocationEnabled(true);
}
} else {
// Permission to access the location is missing. Show rationale and request permission
PermissionUtils.requestPermission(this, 0,
Manifest.permission.ACCESS_FINE_LOCATION, true);
}
}
/*
#Override
protected void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
protected void onStart() {
super.onStart();
mMapView.onStart();
}
#Override
protected void onStop() {
super.onStop();
mMapView.onStop();
}
#Override
protected void onPause() {
mMapView.onPause();
super.onPause();
}
#Override
protected void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
*/
}
Application Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.grgapps.checkingin">
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyAPQCMFgUWQp4RSDDO0EjpCPuDLhTUjcfg" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
android:label="#string/title_activity_maps_and_directions"
android:theme="#style/AppTheme.NoActionBar"
</activity>
<!--
Set custom default icon. This is used when no icon is set for incoming notification messages.
-->
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_launcher" />
<!--
Set color used with incoming notification messages. This is used when no color is set for the incoming
notification message.
-->
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorAccent" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/default_notification_channel_id" />
<activity
android:name=".SettingsActivity"
android:label="#string/title_activity_settings" />
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-3940256099942544~3347511713" />
<activity
android:name=".Emergency"
android:label="#string/title_activity_emergency"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".Contacts"
android:label="#string/title_activity_contacts"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".PeepsLocator"
android:label="#string/title_activity_peeps_locator"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".RequestCheckIn"
android:label="#string/title_activity_request_check_in"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".ViewCheckIns"
android:label="#string/title_activity_view_check_ins"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".RoadTrip"
android:label="#string/title_activity_road_trip"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".Commute"
android:label="#string/title_activity_commute"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".Settings"
android:label="#string/title_activity_settings"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".CheckIn"
android:label="#string/title_activity_check_in"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".CheckInNew"
android:label="CheckInNew"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_SERVICE" />
</intent-filter>
</service>
</application>
</manifest>
Logcat entry
03-18 06:27:54.442 5342-5342/com.grgapps.checkingin E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.grgapps.checkingin, PID: 5342
java.lang.SecurityException: my location requires permission ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION
at com.google.maps.api.android.lib6.impl.bf.c(:com.google.android.gms.dynamite_mapsdynamite#16089052#16.0.89 (040700-239467275):569)
at com.google.android.gms.maps.internal.l.a(:com.google.android.gms.dynamite_mapsdynamite#16089052#16.0.89 (040700-239467275):361)
at fw.onTransact(:com.google.android.gms.dynamite_mapsdynamite#16089052#16.0.89 (040700-239467275):4)
at android.os.Binder.transact(Binder.java:387)
at com.google.android.gms.internal.maps.zza.zzb(Unknown Source)
at com.google.android.gms.maps.internal.zzg.setMyLocationEnabled(Unknown Source)
at com.google.android.gms.maps.GoogleMap.setMyLocationEnabled(Unknown Source)
at com.grgapps.checkingin.MapsActivity.onMapReady(MapsActivity.java:64)
at com.google.android.gms.maps.zzak.zza(Unknown Source)
at com.google.android.gms.maps.internal.zzaq.dispatchTransaction(Unknown Source)
at com.google.android.gms.internal.maps.zzb.onTransact(Unknown Source)
at android.os.Binder.transact(Binder.java:387)
at fv.b(:com.google.android.gms.dynamite_mapsdynamite#16089052#16.0.89 (040700-239467275):14)
at com.google.android.gms.maps.internal.bd.a(:com.google.android.gms.dynamite_mapsdynamite#16089052#16.0.89 (040700-239467275):4)
at com.google.maps.api.android.lib6.impl.bk.run(:com.google.android.gms.dynamite_mapsdynamite#16089052#16.0.89 (040700-239467275):4)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
As per Android Document:
Android 6.0 Marshmallow introduced a new permissions model that lets apps request permissions from the user at runtime, rather than prior to installation. Apps that support the new model request permissions when the app actually requires the services or data protected by the services. While this doesn't (necessarily) change overall app behavior, it does create a few changes relevant to the way sensitive user data is handled:
For SDK version 23, you need to ask run time permission to access the device location. For that, please call enableMyLocation() method in onCreate() function

Android - Can't show the google map

I need some help...
My application can't show the map. I've enabled the API Key and try to create it many times, with new keystore.
Screenshot for result
The error code says:
12-14 03:47:45.527 31641-31956/tkj5a.dhiaulhaq.pnj.project_paksyamsi E/b: Authentication failed on the server.
12-14 03:47:45.527 31641-31956/tkj5a.dhiaulhaq.pnj.project_paksyamsi E/Google Maps Android API: Authorization failure. Please see
12-14 03:47:45.533 31641-31956/tkj5a.dhiaulhaq.pnj.project_paksyamsi E/Google Maps Android API: In the Google Developer Console (https://console.developers.google.com)
Ensure that the "Google Maps Android API v2" is enabled.
Ensure that the following Android Key exists:
API Key: AIzaSyCLdUfhN9SoszJQiGzDF1rcOuV5P2RfcJs
Android Application (<cert_fingerprint>;<package_name>): 39:AD:91:AB:60:3D:34:22:1C:F3:36:4B:B6:98:6F:BB:61:5A:B5:60;tkj5a.dhiaulhaq.pnj.project_paksyamsi
And my layout:
<?xml version="1.0" encoding="utf-8"?>
<fragment
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapsActivity"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="tkj5a.dhiaulhaq.pnj.project_paksyamsi">
<permission android:name="tkj5a.dhiaulhaq.pnj.project_paksyamsi.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="tkj5a.dhiaulhaq.pnj.project_paksyamsi.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="tkj5a.dhiaulhaq.pnj.project_paksyamsi.permission.READ_GSERVICES"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MapsActivity"
android:theme="#style/AppTheme.NoActionBar"></activity>
<activity android:name=".CheckInActivity"
android:theme="#style/AppTheme.NoActionBar"></activity>
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyCLdUfhN9SoszJQiGzDF1rcOuV5P2RfcJs"/>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
</application>
</manifest>
And here's the MapsActivity.java:
package tkj5a.dhiaulhaq.pnj.project_paksyamsi;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
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 java.util.ArrayList;
public class MapsActivity extends FragmentActivity {
private GoogleMap map;
private DBLokasi lokasi;
private ArrayList<DBLokasi> values;
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFrag=(SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
map=mapFrag.getMap();
map.setMyLocationEnabled(true);
Bundle b=this.getIntent().getExtras();
if (b.containsKey("longitude")){
final LatLng latLng=new LatLng(b.getDouble("latitude"),b.getDouble("longitude"));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,16));
map.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)));
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
Toast.makeText(MapsActivity.this,"Lokasi Saat Ini " + latLng.latitude+ "," +latLng.longitude,Toast.LENGTH_LONG).show();
return false;
}
});
}else if (this.getIntent().getSerializableExtra("lokasi")!=null){
lokasi=(DBLokasi)this.getIntent().getSerializableExtra("lokasi");
if (lokasi!=null){
LatLng latLng=new LatLng(lokasi.getLatD(),lokasi.getLngD());
map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,16));
map.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)).title(lokasi.getNama()));
}
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
final Dialog dialog=new Dialog(MapsActivity.this);
dialog.setTitle("Checkin Data : ");
dialog.setContentView(R.layout.fragment_dialog_datashow);
TextView tvNama=(TextView)dialog.findViewById(R.id.tv_nama);
TextView tvKoordinat=(TextView)dialog.findViewById(R.id.tv_koordinat);
Button btOK=(Button)dialog.findViewById(R.id.bt_checkin_ok);
tvNama.setText(String.format(getResources().getString(R.string.checkin_label_name),marker.getTitle()));
tvKoordinat.setText(marker.getPosition().latitude+ ","+ marker.getPosition().longitude);
btOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.cancel();
}
});
dialog.show();
return false;
}
});
}
else {
LatLng init;
DBLokasi lokInit;
LatLng latLng;
values=((ArrayList<DBLokasi>)this.getIntent().getSerializableExtra("arraylokasi"));
lokInit=values.get(0);
init=new LatLng(lokInit.getLatD(),lokInit.getLngD());
map.animateCamera(CameraUpdateFactory.newLatLngZoom(init,16));
for (DBLokasi lok:values){
latLng=new LatLng(lok.getLatD(),lok.getLngD());
map.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)));
}
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
final Dialog dialog=new Dialog(MapsActivity.this);
dialog.setTitle("Checkin Data : ");
dialog.setContentView(R.layout.fragment_dialog_datashow);
TextView tvNama=(TextView)dialog.findViewById(R.id.tv_nama);
TextView tvKoordinat=(TextView)dialog.findViewById(R.id.tv_koordinat);
Button btOK=(Button)dialog.findViewById(R.id.bt_checkin_ok);
tvNama.setText(String.format(getResources().getString(R.string.checkin_label_name)));
tvKoordinat.setText(marker.getPosition().latitude+","+marker.getPosition().longitude);
btOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.cancel();
}
});
dialog.show();
return false;
}
});
}
}
}
Thanks for any helps guys :)
Confirm the SHA-1 key you are getting in the message and the key you have on server are same. Also, make sure adding the API key in manifest as well as in a XML file (release -> res -> values -> google_maps_api.xml) which automatically gets generated.
**Manifest:**
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="#string/google_maps_key" />
and
**google_maps_api.xml**
<string name="google_maps_key" translatable="false" templateMergeStrategy="preserve">
YOUR_KEY_HERE
</string>
You can get SHA-1 key and package name from the error message you have posted. Both are separated by ';'
Make sure your API key is the correct one... and maybe check if you have the 'Google Play Services' SDK installed.
It says "In the Google Developer Console" so i would start there lol
Check:
-SHA 1 key
-API Key
Don't forget to hit 'Save' once you're done, i know a few people who have made that mistake before!

Google Maps won't show up

I'm working on a project which involves a "Points of Interest" locator. I have a generated Google Maps API v2 key and I've added all the proper permissions to the AndroidManifest (as you'll see below), and everything compiles...except for the map itself! There's a marker that shows your current location and as well as the GPS coordinates but not the map, which needless to say is essential. Also there are no runtime erros except that the LogCat says at points "There is too much output to process". Any help would be greatly appreciated.
Android Manifest
package="com.example.kavin_000.travelapplication" >
<!-- suppress AndroidDomInspection -->
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="19" />
<permission
android:name="com.example.kavin_000.travelapplication.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.kavin_000.travelapplication.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="#drawable/nyit_icon"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".ow_main_page"
android:label="#string/app_name" >
</activity>
<activity
android:name=".manhattan_main_page"
android:label="#string/title_activity_manhattan_main_page" >
</activity>
<activity
android:name=".main_page"
android:label="Travel Application" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ow_campus_points_of_interest"
android:label="#string/title_activity_ow_campus_points_of_interest" >
</activity>
<activity
android:name=".manhattan_campus_points_of_interest"
android:label="#string/title_activity_manhattan_campus_points_of_interest" >
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="MY_KEY" />
</application>
</manifest>
Layout XML file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".ow_main_page"
android:background="#ffffb502">
<fragment
android:id="#+id/googleMap"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_above="#+id/latlongLocation" />
<TextView
android:id="#+id/latlongLocation"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="bottom"
android:layout_alignParentBottom="true"
android:background="#ff058fff"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:textColor="#ffffffff"
android:paddingLeft="5dp"
android:paddingRight="5dp" />
</RelativeLayout>
Java class in question
package com.example.kavin_000.travelapplication;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
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.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class ow_campus_points_of_interest extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//show error dialog if GooglePlayServices not available
if (!isGooglePlayServicesAvailable()) {
finish();
}
setContentView(R.layout.activity_ow_campus_points_of_interest);
SupportMapFragment supportMapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
googleMap = supportMapFragment.getMap();
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
}
#Override
public void onLocationChanged(Location location) {
TextView locationTv = (TextView) findViewById(R.id.latlongLocation);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLng));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
locationTv.setText("Latitude:" + latitude + ", Longitude:" + longitude);
}
#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
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
}
It sounds like there may be an issue with your authorization on Google App Engine. Did you make sure to use the SHA1 fingerprint from your debug.keystore and not from your release keystore? Additionally, make sure that you are appending ;com.example.kavin_000.travelapplication to the end of the SHA1 fingerprint.
If you have not added your SHA1 fingerprint to the list of authorized applications, that is the issue. It can be done by finding your debug.keystore file (search on Google depending on your OS), and running the following command:
keytool -list -v -keystore debug.keystore

Installation error: INSTALL_FAILED_MISSING_SHARED_LIBRARY for Android 2.2 API Level 8

I'm having an Android GPS project for my CS class. Right now I'm working through tutorials (using Eclipse with ADT plugin) to have an idea of how to use the Android library, but along the way, I received the Installation error: INSTALL_FAILED_MISSING_SHARED_LIBRARY
I checked on LogCat and it seems the error starts on this line:
03-29 23:05:14.721: E/PackageManager(72): Package virginia.edu.cs2110 requires unavailable shared library android.location; failing!
I have looked up this problem and did all the things that I was able to find. I declared the uses-library field in the manifest file:
<uses-library android:name="android.location" />
<uses-library android:name="com.google.android.maps" />
If anyone is wondering, this is my whole manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="virginia.edu.cs2110"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".TrivialGPS"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-library android:name="android.location" />
<uses-library android:name="com.google.android.maps" />
</application>
</manifest>
I also created an Android emulator with Target Name "Google API (Google Inc.)":
http://i42.tinypic.com/2dj3vd5.jpg
Also, here's the code that I wanted to run:
package virginia.edu.cs2110;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
public class TrivialGPS extends MapActivity {
private MapController mapController;
private MapView mapView;
private LocationManager locationManager;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// create a map view
mapView = new MapView(this, "C7:63:2F:C8:93:8B:E1:83:D6:4F:D3:5B:62:C1:75:90");
mapController = mapView.getController();
mapController.setZoom(22);
setContentView(mapView);
// get a hangle on the location manager
locationManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
new LocationUpdateHandler());
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
public class LocationUpdateHandler implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
int lat = (int) (loc.getLatitude()*1E6);
int lng = (int) (loc.getLongitude()*1E6);
GeoPoint point = new GeoPoint(lat, lng);
mapController.setCenter(point);
setContentView(mapView);
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
}
Delete <uses-library android:name="android.location" />, as there is no such library.

Categories

Resources