I am working on a mobile application and I'm still new to Android Studio. In this app I need to use Google Maps. The app runs fine on my smartphone but when i click the button to navigate to the Google Map page, there is a pop up message that says my app has stopped. Can someone please help me troubleshoot this problem?
MapsActivity.java
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
private GoogleApiClient client;
private LocationRequest locationRequest;
private Location lastlocation;
private Marker currentLocationMarker;
public static final int REQUEST_LOCATION_CODE = 99;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
checkLocationPermission();
}
// 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);
setUpMapIfNeeded();
}
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch(requestCode)
{
case REQUEST_LOCATION_CODE:
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
//permission is granted
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
if(client == null)
{
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
}
else //permission is denied
{
Toast.makeText(this, "Permission Denied!", Toast.LENGTH_LONG).show();
}
return;
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
//DO WHATEVER YOU WANT WITH GOOGLEMAP
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//mMap.setMyLocationEnabled(true);
mMap.setTrafficEnabled(true);
mMap.setIndoorEnabled(true);
mMap.setBuildingsEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
setUpMap();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
SupportMapFragment mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map));
mMap.getMapAsync(this);
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(3.188426, 101.682027)).title("This is my first marker"));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
//
mMap.setMyLocationEnabled(true); //int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
}
protected synchronized void buildGoogleApiClient()
{
client = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
client.connect();
}
#Override
public void onLocationChanged(Location location) {
// latitude = location.getLatitude();
//longiude = location.getLongitude();
lastlocation = location;
if (currentLocationMarker != null)
{
currentLocationMarker.remove();
}
LatLng latlng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latlng);
markerOptions.title("Current Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
currentLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
mMap.animateCamera(CameraUpdateFactory.zoomBy(10));
if (client != null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(client, this);
}
}
/*#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}*/
public void onClick (View v)
{
if(v.getId() == R.id.searchbtn)
{
EditText userlocation = (EditText)findViewById(R.id.userLocation);
String location = userlocation.getText().toString();
List<Address> addressList = null;
MarkerOptions mo = new MarkerOptions();
if( !location.equals(""))
{
Geocoder geocoder = new Geocoder(this);
try
{
addressList = geocoder.getFromLocationName(location, 5);
}
catch (IOException e)
{
e.printStackTrace();
}
for(int i=0; i<addressList.size(); i++)
{
Address myAddress = addressList.get(i);
LatLng latLng = new LatLng(myAddress.getLatitude(), myAddress.getLongitude());
mo.position(latLng);
mo.title("Your Search Result");
mMap.addMarker(mo);
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
locationRequest = new LocationRequest();
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);
}
}
public boolean checkLocationPermission()
{
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_CODE);
}
else
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_CODE);
}
return false;
}
else
return true;
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.asus.autocare">
<!-- To auto-complete the email text field in the login form with the user's
emails -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name =
"com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<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=".MainActivity" />
<activity android:name=".LoginActivity" />
<activity android:name=".RegisterActivity" />
<activity android:name=".SplashScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps" />
<activity android:name=".ChooseActivity"></activity>
</application> </manifest>
This is the error that I got:
05-02 21:11:10.236 30445-30445/? E/Zygote: v2
05-02 21:11:10.238 30445-30445/? E/Zygote: accessInfo : 0
05-02 21:11:12.271 30445-30445/com.example.asus.autocare E/BoostFramework:
BoostFramework() : Exception_1 = java.lang.ClassNotFoundException: Didn't
find class "com.qualcomm.qti.Performance" on path:
DexPathList[[],nativeLibraryDirectories=[/system/lib, /vendor/lib]]
05-02 21:11:30.904 30445-30445/com.example.asus.autocare E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.example.asus.autocare, PID: 30445
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.asus.autocare/com.example.asus.autocare.MapsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2984)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
at com.example.asus.autocare.MapsActivity.setUpMap(MapsActivity.java:147)
at com.example.asus.autocare.MapsActivity.setUpMapIfNeeded(MapsActivity.java:140)
at com.example.asus.autocare.MapsActivity.onCreate(MapsActivity.java:64)
at android.app.Activity.performCreate(Activity.java:6955)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
Try Moving these lines to onMapLoaded() instead.
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
Related
My app cannot get the longitude and latitude of the current online user and store it in a firebase database, the database keeps on being empty even when there is a user that is currently online. At times the app keeps crashing. I want to save the longitude and latitude of the user that is online into the firebase database using Geofire but it seems that it's not even getting the longitude and latitude of the current online user because it's returning null at times. I don't know what is the issue.
Here is my code.
public class DriversMapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener {
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private Location lastLocation;
private LocationRequest locationRequest;
public static final int PERMISSION_FINE_LOCATION = 99;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drivers_maps);
driverSetting = findViewById(R.id.driver_maps_setting);
logoutBtn = findViewById(R.id.driver_maps_logout);
mAuth = FirebaseAuth.getInstance();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
checkLocationPermission();
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
buildGoogleApiClient();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
locationRequest = new LocationRequest();
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(locationRequest.PRIORITY_HIGH_ACCURACY);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
// if (getApplicationContext()!=null){
if (location !=null && mMap !=null){
try {
lastLocation = location;
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference driverAvailableRef = FirebaseDatabase.getInstance().getReference().child("Drivers Available");
GeoFire geoFireDriverAvailability = new GeoFire(driverAvailableRef);
geoFireDriverAvailability.setLocation(userID,new GeoLocation(location.getLatitude(),location.getLongitude()));
}catch (Exception e){
Toast.makeText(DriversMapsActivity.this,e.getMessage(),Toast.LENGTH_LONG).show();
}
}
}
protected synchronized void buildGoogleApiClient(){
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference driverAvailableRef = FirebaseDatabase.getInstance().getReference().child("Drivers Available");
GeoFire geoFireDriverAvailability = new GeoFire(driverAvailableRef);
geoFireDriverAvailability.removeLocation(userID);
}
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(DriversMapsActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(DriversMapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_FINE_LOCATION);
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_FINE_LOCATION);
}
}
return true;
}
}
I have added all these permissions in the manifest.
<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="android.permission.ACCESS_COARSE_LOCATION" />
Here is the error from the logcat
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.elijah.ukeme.ride_booking_app, PID: 12273
java.lang.NoSuchMethodError: No virtual method setValueAsync(Ljava/lang/Object;Ljava/lang/Object;)Lcom/google/api/core/ApiFuture; in class Lcom/google/firebase/database/DatabaseReference; or its super classes (declaration of 'com.google.firebase.database.DatabaseReference' appears in /data/app/com.elijah.ukeme.ride_booking_app-1/base.apk:classes3.dex)
at com.firebase.geofire.GeoFire.setLocation(GeoFire.java:178)
at com.firebase.geofire.GeoFire.setLocation(GeoFire.java:149)
at com.elijah.ukeme.ride_booking_app.activity.DriversMapsActivity.onLocationChanged(DriversMapsActivity.java:224)
at com.google.android.gms.internal.location.zzay.notifyListener(Unknown Source)
at com.google.android.gms.common.api.internal.ListenerHolder.zaa(com.google.android.gms:play-services-base##18.0.1:2)
at com.google.android.gms.common.api.internal.zacb.run(com.google.android.gms:play-services-base##18.0.1)
at android.os.Handler.handleCallback(Handler.java:836)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6275)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
I am trying to make my map app redirect to the settings for location permissions and once permissions are granted redirect again to the app. for some reason my onActivityResult is not even called after starting the activity intent. and basically what happens is when I click on the snackbar action button that appears, it starts the settingsIntent and redirects me to the settings nicely but the activity isn't going for result state and the onActivityResult is never called
any suggestions?
here is the code:
class MapsActivity : AppCompatActivity(), OnMapReadyCallback {
private lateinit var mMap: GoogleMap
private fun checkPermissions(): Boolean {
//returns true if granted permission for location
var checker = ActivityCompat.checkSelfPermission(
applicationContext,
android.Manifest.permission.ACCESS_COARSE_LOCATION
) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
applicationContext,
android.Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
if (checker) {
Log.d(TAG, "granted Permissions")
} else {
Log.d(TAG, "no Permissions granted")
}
return checker
}
#RequiresApi(Build.VERSION_CODES.M)
private fun requestPermissions() {
requestPermissions(
arrayOf(
android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.ACCESS_FINE_LOCATION
), PERMISSION_ID
)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (!checkPermissions()) {
Snackbar.make(
map.view!!,
"Please Enable Location Permission",
Snackbar.LENGTH_INDEFINITE
).setAction("Enable Location",
View.OnClickListener {
var settingsIntent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
startActivityForResult(settingsIntent, 1)
})
.show()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
Log.d(TAG, "Redirected to settings for Location Permissions ")
if (resultCode == Activity.RESULT_OK) {
if (checkPermissions()) {
Log.d(TAG, "Permissions granted from settings")
startActivity(Intent(this, MapsActivity::class.java))
}
}
super.onActivityResult(requestCode, resultCode, data)
}
override fun onCreate(savedInstanceState: Bundle?) {
Log.d(TAG, "onCreate called")
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_maps)
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
val mapFragment = supportFragmentManager
.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
}
#RequiresApi(Build.VERSION_CODES.M)
override fun onMapReady(googleMap: GoogleMap) {
Log.d(TAG, "omMapReady:starts")
mMap = googleMap
requestPermissions()
}
}
manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.burgertracker">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<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">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
This is working for me,
MainActivity
import android.content.Intent
import android.os.Bundle
import android.provider.Settings
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<TextView>(R.id.tv_click).setOnClickListener {
val settingsIntent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
startActivityForResult(settingsIntent, 1)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
Toast.makeText(this, "Hakuna Mattat", Toast.LENGTH_SHORT).show()
}
}
activity_main_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="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=".MainActivity">
<TextView
android:id="#+id/tv_click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.demointentapplication">
<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=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I navigate to Settings page when I click the TextView on MainActivity and when I press back from Settings page I see the Toast message Hakuna Mattat everytime.
there are some differences between our codes, your code is just on a regular activity and mine is on a mapActivity which has a map Fragment displayed.. i run the startActivityForResult from my onRequestPermissiosnResult function since i need to to run only if the permissions are not granted.. so i guess any of those must be the reason..
also i checked and the onActivityResult is called only when i press back once the location settings is displayed.. but the problem is that i need to click on the app in that location setting page and then allow location for it and if i do so and then press home button 2 times to go back the the app it does not go back and onActivityResult is not called..
so either i need to know if theres an option to start an intent that will start an activity that goes directly to my specific app location settings and then i guess it will work or either if i will know how to control that settings activity because once it moves to the settings the mapAcitivty is stopped..
int PERMISSION_ID = 44;
FusedLocationProviderClient mFusedLocationClient;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_home);
mFusedLocationClient =
LocationServices.getFusedLocationProviderClient(this);
getLastLocation();
}
private boolean checkPermissions() {
if (ActivityCompat.checkSelfPermission(HomeActivity.this,
Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(HomeActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
return true;
}
return false;
}
private void requestPermissions() {
ActivityCompat.requestPermissions(
HomeActivity.this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSION_ID
);
}
private boolean isLocationEnabled() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(
LocationManager.NETWORK_PROVIDER
);
}
#RequiresApi(api = Build.VERSION_CODES.M)
#SuppressLint("MissingPermission")
private void getLastLocation() {
if (checkPermissions()) {
if (isLocationEnabled()) {
mFusedLocationClient.getLastLocation().addOnCompleteListener(
new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
Location location = task.getResult();
if (location == null) {
requestNewLocationData();
} else {
Geocoder geocoder = new Geocoder(HomeActivity.this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
assert addresses != null;
if (addresses != null) {
String cityName = addresses.get(0).getAddressLine(0);
String stateName = addresses.get(0).getAddressLine(1);
String countryName = addresses.get(0).getAddressLine(2);
String[] arrOfStr = cityName.split(",");
locationTV.setText("You're in " + arrOfStr[arrOfStr.length - 2] + ", " + arrOfStr[arrOfStr.length - 1]);
}
}
}
}
);
} else {
Toast.makeText(this, "Turn on location", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
} else {
requestPermissions();
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_ID) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getLastLocation();
}
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onResume() {
super.onResume();
if (checkPermissions()) {
getLastLocation();
}
}
#SuppressLint("MissingPermission")
private void requestNewLocationData() {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(0);
mLocationRequest.setFastestInterval(0);
mLocationRequest.setNumUpdates(1);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mFusedLocationClient.requestLocationUpdates(
mLocationRequest, mLocationCallback,
Looper.myLooper()
);
}
private LocationCallback mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
Location mLastLocation = locationResult.getLastLocation();
Geocoder geocoder = new Geocoder(HomeActivity.this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
assert addresses != null;
if (addresses != null) {
String cityName = addresses.get(0).getAddressLine(0);
String stateName = addresses.get(0).getAddressLine(1);
String countryName = addresses.get(0).getAddressLine(2);
String[] arrOfStr = cityName.split(",");
locationTV.setText("You're in " + arrOfStr[arrOfStr.length - 2] + ", " +
arrOfStr[arrOfStr.length - 1]);
}
}
};
I have a problem in my project. when i click search bar in top of screen then show an error the error is:
status (statuscode=places_api_access_not_configured resolution=null)
my place api is enabled but I am still getting the error.
Here is my Welcome.java
public class Welcome extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener
{
private GoogleMap mMap;
private static final int MY_PERMISSION_REQUEST_CODE=7000;
private static final int PLAY_SERIVICES_RES_REQUEST=7001;
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private Location lastLocation;
private static int UPDATE_INTERVAL=5000;
private static int FATEST_INTERVAL=3000;
private static int DISPLACEMENT=10;
DatabaseReference drivers;
GeoFire geoFire;
Marker mCurrent;
Switch location_switch;
SupportMapFragment mapFragment;
//car animation...
private List<LatLng> polyLineList;
private Marker carMarker;
private float v;
private double lat,lng;
private Handler handler;
private LatLng startPosition,endPosition,currentPosition;
private int index,next;
//private Button btnGo;
private PlaceAutocompleteFragment places;
private String destination;
private PolylineOptions polylineOptions,blackPolylineOptions;
private Polyline blackPolyline,greyPolyline;
private IGoogleAPI mService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//init view..
location_switch= findViewById(R.id.location_switch);
location_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isOnline) {
if(isOnline)
{
startLocationUpdate();
displayLocation();
Snackbar.make(mapFragment.getView(),"You are Online",Snackbar.LENGTH_SHORT).show();
}
else
{
stopLocationUpdate();
mCurrent.remove();
mMap.clear();
//handler.removeCallbacks(drawPathRunnable);
Snackbar.make(mapFragment.getView(),"You are Offline",Snackbar.LENGTH_SHORT).show();
}
}
});
polyLineList=new ArrayList<>();
//places Api....
places=(PlaceAutocompleteFragment)getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
places.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
if(location_switch.isChecked())
{
destination=place.getAddress().toString();
destination=destination.replace(" ","+");
getDirection();
}
else {
Toast.makeText(Welcome.this, "Please Change your status in Online", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onError(Status status) {
Toast.makeText(Welcome.this, ""+status.toString(), Toast.LENGTH_SHORT).show();
}
});
//Geo fire
drivers= FirebaseDatabase.getInstance().getReference("Drivers");
geoFire=new GeoFire(drivers);
setUpLocation();
mService= Common.getGoogleAPI();
}
//we request run time permission ,we need override OnRequestPermission Result..
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode)
{
case MY_PERMISSION_REQUEST_CODE:
if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED)
{
if(checkPlayServices())
{
buildGoogleApiClient();
createLocationRequest();
if(location_switch.isChecked())
displayLocation();
}
}
}
}
private void setUpLocation() {
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) !=PackageManager.PERMISSION_GRANTED)
{
//Request Runtime permission...
ActivityCompat.requestPermissions(this,new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
},MY_PERMISSION_REQUEST_CODE);
}
else
{
if(checkPlayServices())
{
buildGoogleApiClient();
createLocationRequest();
if(location_switch.isChecked())
displayLocation();
}
}
}
private void createLocationRequest() {
mLocationRequest=new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
private void buildGoogleApiClient() {
mGoogleApiClient=new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect(); //Connected Google api client.....
}
private boolean checkPlayServices() {
int resultCode= GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(resultCode!=ConnectionResult.SUCCESS)
{
if(GooglePlayServicesUtil.isUserRecoverableError(resultCode))
GooglePlayServicesUtil.getErrorDialog(resultCode,this,PLAY_SERIVICES_RES_REQUEST).show();
else {
Toast.makeText(this, "This device is not supported ", Toast.LENGTH_SHORT).show();
}
return false;
}
return true;
}
private void stopLocationUpdate() {
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) !=PackageManager.PERMISSION_GRANTED)
{
return;
}
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,(com.google.android.gms.location.LocationListener) this);
}
private void displayLocation() {
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) !=PackageManager.PERMISSION_GRANTED)
{
return;
}
lastLocation=LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(lastLocation!=null)
{
if(location_switch.isChecked())
{
final double latitude=lastLocation.getLatitude();
final double longitude=lastLocation.getLongitude();
//update firebase..
geoFire.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(latitude, longitude), new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, DatabaseError error) {
//add marker
if(mCurrent!=null)
mCurrent.remove();//marker remove already
mCurrent=mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude,longitude))
.title("YOUR LOCATION"));
//Move camera from this position..
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude),15.0f));
/*//draw animated rotated marker..
rotateMarker(mCurrent,-360,mMap);*/
}
});
}
}
else
{
Log.d("ERROR","Cannot get your location");
}
}
private void rotateMarker(final Marker mCurrent, final float i, GoogleMap mMap) {
final Handler handler=new Handler();
final long start= SystemClock.uptimeMillis();
final float startRotation=mCurrent.getRotation();
final long duration=1500;
final Interpolator interpolator=new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
long elapsed=SystemClock.uptimeMillis()-start;
float t=interpolator.getInterpolation((float)elapsed/duration);
float rot=t*i+(1-t)*startRotation;
mCurrent.setRotation(-rot>180?rot/2:rot);
if(t<1.0)
{
handler.postDelayed(this,16);
}
}
});
}
private void startLocationUpdate() {
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) !=PackageManager.PERMISSION_GRANTED)
{
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest, this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setTrafficEnabled(false);
mMap.setIndoorEnabled(false);
mMap.setBuildingsEnabled(false);
mMap.getUiSettings().setZoomControlsEnabled(true);
}
#Override
public void onLocationChanged(Location location) {
lastLocation=location;
displayLocation();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
displayLocation();
startLocationUpdate();
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
Hare is my Android Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.ubarclone">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permisson.READ_GSERVICES" />
<application
android:allowBackup="true"
android:appComponentFactory="whateverString"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:replace="android:appComponentFactory">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".Welcome"
android:label="#string/title_activity_welcome"></activity>
<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>
A screenshot of my issue:
When I click the search bar at the top this error message displays:
I am trying to get my current location using GoogleApiClient and LocationListner. Below is my code which I got from Here.
But the problem is when I start this app in mobile. It is not giving me my current location. I also have checked in debug mode. Latitude and Longitude are not updating in variables. Please check this code and guide me where i am doing wrong or any other logical error. In tutorial developer make a boolean type function named checkLocationPermission(). But this function never used in application. Where should I call that function.
Thanks in advance
Here are my coding files
AndroidManifest.xml
`<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sufian.androidmaps">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<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">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>`
and My MapsActivity.java File is below
`
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener
{
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
Location mLastLocation;
Marker mCurrLocationMarker;
#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);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//initialize google play services
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
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) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, (com.google.android.gms.location.LocationListener) this);
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 100;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission was granted.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
//toast here
}
return;
}
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority
(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi
.requestLocationUpdates(mGoogleApiClient,
mLocationRequest,
(com.google.android.gms.location.
LocationListener) this);
}
}
#Override
public void onConnectionSuspended(int i){
}
The reason your not receiving update locations is because you check if you have location permissions which you don't have before building the Google ApiClient which triggers the location updates.
From Android 6 and higher these aren't granted automatically. But if you call checkLocationPermission() in OnCreate it should prompt the user to grant the permission as soon as you launch the activity
I am developing an application that is based on GPS/user location using this tutorial. The idea is when the user opens second activity (by clicking the button) it should locate the device on the map and update it every second, here is the activity code:
public class MapLocation extends AppCompatActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
GoogleMap mGoogleMap;
GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maplocation);
initMap();
}
private void initMap() {
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapFragment);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
LocationRequest mLocationRequest;
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(1000);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// public void requestPermissions(#NonNull String[] permissions, int requestCode)
// 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 Activity#requestPermissions for more details.
return;
}
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
if(location == null) {
Toast.makeText(this, "Can't get current location!", Toast.LENGTH_LONG).show();
} else {
LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, 15);
mGoogleMap.animateCamera(update);
}
}}
and here is the xml code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/_fff">
<fragment
android:id="#+id/mapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment" />
</LinearLayout>
and here are the necessary permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
The map works fine, however the problem is that it wont show my device on the map (my location), in the tutorial it works. I'm running the application on the device and emulator and the results are the same, map is working fine but my location is not displayed on the map. Can someone explain to me what am i doing wrong?
A crucial mistake that you can see right away is that you are missing the setLocationEnabbled(true) method.
Try this code:
#Override
public void onMapReady(GoogleMap googleMap) {
Toast.makeText(this, "onMapReady", Toast.LENGTH_LONG).show();
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) {
return;
} else {
mMap = googleMap;
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
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) {
Toast.makeText(this, "Location is disabled, turn it on in your settings,", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "onConnected", Toast.LENGTH_LONG).show();
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
//place marker at current position
mMap.clear();
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_VIOLET));
mCurrLocation = mMap.addMarker(markerOptions);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude))
.zoom(11)
.build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}else{
Toast.makeText(this, "LastLocation is null", Toast.LENGTH_LONG).show();}
Hope it helps :)