GoogleApiClient is not connected despite onconnect() being called? - android

I want to add a geofence on the current location of the user when the user clicks on the ad geofence button.however,after using fused api client it states that its not connected yet.here is my code-
import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.Geofence;
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.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.ArrayList;
public class MapsActivity extends FragmentActivity implements com.google.android.gms.location.LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private GoogleMap googleMap; // Might be null if Google Play services APK is not available.
public SQLiteDatabase db;
ArrayList<Geofence> mGeofences;
public double latitude = 77.80;
public double longitude = 55.76;
Double valueindex = 0.0;
private int request = 0;
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
/**
* Geofence Coordinates
*/
ArrayList<LatLng> mGeofenceCoordinates;
/**
* Geofence Store
*/
private GeofenceStore mGeofenceStore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGeofences = new ArrayList<Geofence>();
mGeofenceCoordinates = new ArrayList<LatLng>();
db = openOrCreateDatabase("CoordsDB", Context.MODE_PRIVATE, null);
// db.execSQL("CREATE TABLE IF NOT EXISTS Coordinates(number DOUBLE,latitude DOUBLE,longitude DOUBLE);");
// db.execSQL("INSERT INTO Coordinates VALUES('Fixed', 28.61,77.20)");
setContentView(R.layout.activity_maps);
SupportMapFragment supportMapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
/**
* SupportMapFragment belongs to the v4 support library, contrary to the default MagFragment that is a native component in Android.
SupportMapFragment will support more Android versions, but it is also an additional library you have to add in your project,
so I think it really depends on the Android versions you are targeting:
• On recent versions, the default components should be enough
• On older versions you will need to install the v4 support library and maybe others
*
*/
googleMap = supportMapFragment.getMap();
Log.i("My activity", "maps=" + googleMap);
googleMap.setMyLocationEnabled(true);
/**
* setMyLocationEnabled(true/false) shows the true location when the GPS is switched on from the device. It is an inbuilt feature of the googlemaps .
*/
LocationManager locationManager = (LocationManager) getSystemService(Service.LOCATION_SERVICE);
// getting GPS status
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.i("My activity", "gps is" + isGPSEnabled);
// getting network status
boolean isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Log.i("My activity", "network is" + isNetworkEnabled);
Criteria crta = new Criteria();
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD) {
crta.setAccuracy(Criteria.ACCURACY_FINE);
} else {
crta.setAccuracy(Criteria.ACCURACY_MEDIUM);
}
/**
* we have used .setAccuracy as fine for higher SDks than gingerbread .Gingerbread is used as a reference because in apks lower
* than gingerbread there is very poor geofencing, with gingerbread google made it a lot easier for locationservices to be used for devleopers.
* it had improved set of tools for Location Services, which included geofencing and substantially improved location discovery.
*/
crta.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(crta, true);
/**
* It request Location updates after every 5 sec or if the user traveled 10m
*/
Log.i("My activity", "manager is " + locationManager);
Log.i("My activity", "provider is " + provider);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
MapsActivity.this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 100);
// 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;
}
}
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks((GoogleApiClient.ConnectionCallbacks) this)
.addOnConnectionFailedListener((GoogleApiClient.OnConnectionFailedListener) this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
Log.i("Api is",""+mGoogleApiClient);
}
mLocationRequest = new LocationRequest();
// We want a location update every 10 seconds.
mLocationRequest.setInterval(10000);
// We want the location to be as accurate as possible.
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Location location = locationManager.getLastKnownLocation(provider);
Location location = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
startLocationUpdates();
Log.i("Location is", location + "");
if (location != null) {
onLocationChanged(location);
}
/**
* the Permission is requested after every sec or at a distance of 0 metres by the user.
*/
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 100: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Thanks for the permission", Toast.LENGTH_LONG).show();
// permission was granted, yay! do the
// calendar task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "You did not allow to access your current location", Toast.LENGTH_LONG).show();
}
}
// other 'switch' lines to check for other
// permissions this app might request
}
}
#Override
public void onLocationChanged(Location location) {
CameraPosition INIT =
new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude()))
.zoom(17.5F)
.bearing(300F) // orientation
.tilt(50F) // viewing angle
.build();
// use GooggleMap mMap to move camera into position
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(INIT));
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
mGoogleApiClient.disconnect();
}
public void Add(View view) {
if (request <= 3) {
mGeofenceCoordinates.add(new LatLng(latitude, longitude));
Log.i("The id is", "" + valueindex);
mGeofences.add(new Geofence.Builder()
// The coordinates of the center of the geofence and the radius in meters.
.setRequestId("" + valueindex)
.setCircularRegion(latitude, longitude, 30)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
// Required when we use the transition type of GEOFENCE_TRANSITION_DWELL
.setLoiteringDelay(50000)
.setTransitionTypes(
Geofence.GEOFENCE_TRANSITION_ENTER
| Geofence.GEOFENCE_TRANSITION_DWELL
| Geofence.GEOFENCE_TRANSITION_EXIT).build());
mGeofenceStore = new GeofenceStore(this, mGeofences);
valueindex++;
request++;
// Cursor c = db.rawQuery("SELECT * FROM Coordinates WHERE Id='"+valueindex+"'", null);
googleMap.addMarker(new MarkerOptions().snippet("Radius:30m").draggable(false).title(valueindex + "").position(new LatLng(latitude, longitude)));
} else {
Toast.makeText(this, "Maximum limit exceeded", Toast.LENGTH_LONG).show();
}
}
#Override
public void onConnected(Bundle bundle) {
Location mlastlocation;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
MapsActivity.this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 100);
// 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;
}
}
mlastlocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
startLocationUpdates();
if (mlastlocation != null) {
Log.i("the last location:", "" + mlastlocation);
Toast.makeText(this, "Get last location first asshole!", Toast.LENGTH_LONG).show();
}
}
protected void startLocationUpdates() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
MapsActivity.this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 100);
// 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;
}
LocationRequest mLocationRequest = new LocationRequest();
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
Log.i("connection","suspended");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i("Connection","Failed");
}
}
Here is my error-
java.lang.RuntimeException: Unable to start activity ComponentInfo{saksham.geofencing/saksham.geofencing.MapsActivity}: java.lang.IllegalStateException: GoogleApiClient is not connected yet.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Caused by: java.lang.IllegalStateException: GoogleApiClient is not connected yet.
at com.google.android.gms.common.api.internal.zzh.zzb(Unknown Source)
at com.google.android.gms.common.api.internal.zzl.zzb(Unknown Source)
at com.google.android.gms.common.api.internal.zzj.zzb(Unknown Source)
at com.google.android.gms.location.internal.zzd.requestLocationUpdates(Unknown Source)
at saksham.geofencing.MapsActivity.startLocationUpdates(MapsActivity.java:276)
at saksham.geofencing.MapsActivity.onCreate(MapsActivity.java:139)
at android.app.Activity.performCreate(Activity.java:6245)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
            at android.app.ActivityThread.-wrap11(ActivityThread.java)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5443)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
and my manifest file-
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="saksham.geofencing" >
<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" >
<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="#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>
<receiver android:name="com.aol.android.geofence.GeofenceReceiver"
android:exported="false">
<intent-filter >
<action android:name="com.aol.android.geofence.ACTION_RECEIVE_GEOFENCE"/>
</intent-filter>
</receiver>
</manifest>
Please help,i am newbie to android and i have been stuck at it for many days now even after searching countless blogs

In your onCreate method, you correctly configure the Google API Client and call onConnect:
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks((GoogleApiClient.ConnectionCallbacks) this)
.addOnConnectionFailedListener((GoogleApiClient.OnConnectionFailedListener) this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
Log.i("Api is",""+mGoogleApiClient);
}
However, several lines below this (still within the onCreate lifecycle method), you have the following code:
Location location = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
startLocationUpdates();
Log.i("Location is", location + "");
if (location != null) {
onLocationChanged(location);
}
My guess is that the first line of this section is causing the error - you are trying to retrieve a location but the Google API Client is still not connected at this point. Since you already have analogous code inside your onConnected callback, you should be able to just remove the second block of code I quoted above from your onCreate method to fix the issue.

Related

the current location does not appear on the map when i run my app to get user location

I am making an app to show user location on google map by put a marker in his/her current location when i run the app it only gives me the view of the map without doing any thing else , i searched too many but i do not find any thing to help me can anyone guide me through this.
thanks in advance.
MapsActivity.java
package com.example.android.getlocationtrial;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
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 java.io.IOException;
import java.util.List;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private LocationManager manager;
private LocationListener locationListener;
#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);
//get the location service
manager = (LocationManager) getSystemService(LOCATION_SERVICE);
//request the location update thru location manager
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,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//get the latitude and longitude from the location
double latitude = location.getLatitude();
double longitude = location.getLongitude();
//get the location name from latitude and longitude
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
List<Address> addresses =
geocoder.getFromLocation(latitude, longitude, 1);
String result = addresses.get(0).getSubLocality()+":";
result += addresses.get(0).getLocality()+":";
result += addresses.get(0).getCountryCode();
LatLng latLng = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(latLng).title(result));
mMap.setMaxZoomPreference(20);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0, 0, locationListener);
}
/**
* 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 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));
*/
}
#Override
protected void onPause() {
super.onPause();
manager.removeUpdates(locationListener);
Log.i("onPause...","paused");
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.getlocationtrial">
<!--
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.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<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="#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>
In order to show the current location marker you just call setMyLocationEnabled on your map object and pass true as its parameter.
Check the following code snippit:
private static final int LOCATION_REQUEST = 50;
private String[] LOCATION_PERMS = {android.Manifest.permission.ACCESS_FINE_LOCATION };
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Asking for location permission to request the last user location
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) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this,
LOCATION_PERMS,
LOCATION_REQUEST);
} else {
ActivityCompat.requestPermissions(this,
LOCATION_PERMS,
LOCATION_REQUEST);
}
} else {
//This will show the current user location marker
mMap.setMyLocationEnabled(true);
//Getting location updates and focus the camera with the latest location
FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
// ...
userCurrentLocation = new LatLng(location.getLatitude(), location.getLongitude());
CameraPosition cp = CameraPosition.builder().target(userCurrentLocation).zoom(25).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cp), 500, null);
}
}
});
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case LOCATION_REQUEST: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay!
onMapReady(mMap);
} else {
// permission denied,
// Ask again for the permission
Toast.makeText(this, R.string.location_permission_required_message, Toast.LENGTH_SHORT).show();
finish();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}

Location Permission on Android 5.1.1

In my app I need for location of users.
I realize that I must ask for permission, but how I can do this on Android 5.1.1 where user cannot change permission. I wrote the code that is everywhere but without result.
How must I proceed?
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.Manifest;
//import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.*;
//import com.google.android.gms.maps.model.LatLng;
//import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
//import com.google.android.gms.common.api.*;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback
, GoogleApiClient.ConnectionCallbacks
//, OnConnectionFailedListener
{
private GoogleMap mMap;
// public GoogleApiClient.Builder mGoogleApiClient = new GoogleApiClient.Builder(this);
private GoogleApiClient mGoogleApiClient;
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public double latitude;
public double longitude;
#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);
//mMainActivity.onConnected(bBundle);
Log.d("OnCreate", "enter 1");
mGoogleApiClient = new GoogleApiClient.Builder(this)
//.enableAutoManage(this /* FragmentActivity */,
// this /* OnConnectionFailedListener */)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
// .addApi(Places.GEO_DATA_API)
//.addApi(Places.PLACE_DETECTION_API)
.build()
;
mGoogleApiClient.connect();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
Log.d("OnCreate", "enter in if1 ");
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
Log.d("OnCreate", "enter in if2 ");
} else {
Log.d("OnCreate", "enter in else2 Request permission ");
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
} else {
//Request location updates: Popytka
//locationManager.requestLocationUpdates(provider, 400, 1, this);
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
Log.d("OnCreate", "enter mLastLocation " + String.valueOf(mLastLocation));
if (mLastLocation != null) {
Log.d("OnCreate", "enter2");
latitude = mLastLocation.getLatitude();
longitude = mLastLocation.getLongitude();
Log.d("OnCreate longitude", String.valueOf(longitude));
}
}
}
//public MainActivity mMainActivity = new MainActivity();
Bundle bBundle;
#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, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Request location updates:
//locationManager.requestLocationUpdates(provider, 400, 1, this);
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
Log.d("OnCreate", "enter mLastLocation " + String.valueOf(mLastLocation));
if (mLastLocation != null) {
Log.d("OnCreate","enter20");
latitude = mLastLocation.getLatitude();
longitude = mLastLocation.getLongitude();
Log.d("OnCreate longitude-0", String.valueOf(longitude));
}
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
//System.out.println("onMapReady in");
mMap = googleMap;
//latitude = -34;
//longitude = 151;
float zoom = 5;
double laRe = latitude, loRe = longitude+1;
// Add a marker in Sydney and move the camera
LatLng user = new LatLng(latitude, longitude), rest = new LatLng(laRe, loRe);
//LatLng rest = new LatLng(laRe, loRe);
mMap.addMarker(new MarkerOptions().position(user).title("Marker in USER"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(user, zoom));
mMap.addCircle(new CircleOptions()
.center(user)
.radius(200000)
.strokeColor(0)
.fillColor(0x4000ff00));
GroundOverlayOptions restPos = new GroundOverlayOptions()
.image(BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher))
.position(new LatLng(laRe, loRe), 200000f);
mMap.addGroundOverlay(restPos);
}
#Override
public void onConnected (Bundle bBundle){
}
protected void onStart() {
//mGoogleApiClient.connect();
super.onStart();
//mGoogleApiClient.ConnectionCallbacks; //(this);
}
protected void onStop() {
// mGoogleApiClient.disconnect();
super.onStop();
}
public void onConnectionSuspended(int i) {
}
//#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
<uses-permission android:name="android.permission.ACCESS_FINE_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" >
<!--
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=".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>
SDK 25
Runtime permission is required for Android 6.0+ but if you need here's the easiest code for requesting runtime permissions.
String [] permissions=new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.ACCESS_FINE_LOCATION
};
List<String> listPermissionsNeeded = new ArrayList<>();
for (String permission:permissions) {
if (ContextCompat.checkSelfPermission(this,permission )!= PackageManager.PERMISSION_GRANTED){
listPermissionsNeeded.add(permission);
}
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), 1);
}
UPDATE
Try this ->
First, create a LocationRequest object:
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
Then, make sure the user has granted permission to use location. If so, get the location from requestLocationUpdates as follows:
void getLocation() {
Location location = null;
if (ContextCompat.checkSelfPermission(activity, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
/*TODO!! INSERT CODE TO PROMPT USER TO GIVE PERMISSION*/
} else {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
mLastLocation = location;
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
}
Be sure to remove the updates if you only need one location without constant monitoring. This way, you will never get a null Location.

Android - Asking permission to see user location

I am trying to ask the user permission to access their location. This is my MainActivity but permission is not being asked when I run the app. I have entered the code for permissions at the end of the activity. What am I doing wrong?
package com.example.googlemapsadding;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import android.Manifest;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
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.LocationSource;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
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;
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener
{
private GoogleMap mMap;
private final String LOG_TAG = "LaurenceTestApp";
private TextView txtOutput;
private TextView latitude;
private TextView longitude;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
Marker curPosMarker;
#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);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
txtOutput = (TextView) findViewById(R.id.txtOutput);
latitude = (TextView) findViewById(R.id.latitude);
longitude = (TextView) findViewById(R.id.longitude);
}
/**
* 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 Sydney and move the camera
LatLng sydney = new LatLng(10,19);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
*/
}
#Override
public void onConnected(#Nullable Bundle bundle)
{
mLocationRequest = LocationRequest.create(); // Another way to write a new object
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(2 * 1000); // Always write in milliseconds
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;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i)
{
Log.i(LOG_TAG, "GoogleApiClient connection has been suspended");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult)
{
Log.i(LOG_TAG, "GoogleApiClient connection has failed");
}
#Override
public void onLocationChanged(Location location)
{
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
Log.i(LOG_TAG, location.toString());
double tempLat = location.getLatitude();
double tempLong = location.getLongitude();
// Make a marker
LatLng latlng = new LatLng(tempLat,tempLong);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
/*
MarkerOptions markerOptions = new MarkerOptions(); // MarkerOptions object to hold marker attributes
markerOptions.position(latlng);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
markerOptions.title("Current Position");
curPosMarker = mMap.addMarker(markerOptions); // Add marker with markerOptions options
mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
if (curPosMarker != null) // Keep only one marker for an object and delete past ones
{
mMap.clear();
}
curPosMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
*/
}
#Override
protected void onStart()
{
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop()
{
mGoogleApiClient.disconnect();
super.onStop();
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
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)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//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. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//if (mGoogleApiClient == null) {
// buildGoogleApiClient();
//}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other permissions this app might request.
// You can add here other case statements according to your requirement.
}
}
}
I think you should request GRANTED with ALL LOCATION PERMISSION
String mPerms[] = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
...
if (checkSelfPermission(mPerms[0]) == PackageManager.PERMISSION_DENIED
|| checkSelfPermission(mPerms[1]) == PackageManager.PERMISSION_DENIED) {
requestPermissions(mPerms, CODE_PERMISSION_LOCATION);
} else {
// TODO Location checker
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(resultCallback);
}
Try Google Utilities library to get location easily with permission..
locationHandler = new LocationHandler(this)
.setLocationListener(new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// Get the best known location
}
}).start();
For more details about location handler, read out wiki...
check the target version in your build.gradle file, it should be 23 or higher.
Solved. I completely erased my permission code and followed this tutorial from scratch - https://www.youtube.com/watch?v=z2JaVke71RY. Worked perfectly.

android.os.Looper android.content.Context.getMainLooper() on a null object reference

I'm following a tutorial to learn using Google maps but i keep getting errors.
This is is the link of the Tutorial:
Note : Testing on real device. HUAWEI TIT-U02 ANDROID 5.1 API 22
This is the Error i get.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.tw_location, PID: 24183
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.android.tw_location/com.example.android.tw_location.MapsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Looper android.content.Context.getMainLooper()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2444)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2619)
at android.app.ActivityThread.access$700(ActivityThread.java:183)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1485)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5668)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:963)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:758)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Looper android.content.Context.getMainLooper()' on a null object reference
at android.content.ContextWrapper.getMainLooper(ContextWrapper.java:101)
at com.google.android.gms.common.api.GoogleApiClient$Builder.<init>(Unknown Source)
at com.example.android.tw_location.MapsActivity.<init>(MapsActivity.java:46)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1071)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2434)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2619) 
at android.app.ActivityThread.access$700(ActivityThread.java:183) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1485) 
at android.os.Handler.dispatchMessage(Handler.java:111) 
at android.os.Looper.loop(Looper.java:194) 
at android.app.ActivityThread.main(ActivityThread.java:5668) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:963) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:758) 
This is MapsActivity.Java
package com.example.android.tw_location;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.location.LocationListener;
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.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;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener{
private GoogleMap mMap;
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);
}
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */,
this /* OnConnectionFailedListener */)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.setAccountName("aymanshaltut#gmail.com")
.build();
/**
* 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 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));
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
android.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 onConnected( Bundle bundle) {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed( ConnectionResult connectionResult) {
}
#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, this);
}
}
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{android.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,
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other permissions this app might request.
//You can add here other case statements according to your requirement.
}
}
}
This is Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.tw_location">
<!--
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="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
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="#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>
The GoogleApiClient initialization should be inside the onCreate method:
GoogleApiClient mGoogleApiClient;
#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);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */,
this /* OnConnectionFailedListener */)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.setAccountName("aymanshaltut#gmail.com")
.build();
}
Attempt to invoke virtual method android.os.Looper android.content.Context.getMainLooper() on a null object reference
is caused due to context passed mGoogleApiClient = new GoogleApiClient.Builder(getcontext()) is null ,which is trying to call getMainLooper() via context.
Check inside GoogleApiClient constructor .
Solution :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (getContext() == null) {
return;
}
}

Shows Location.getLatitude() a null object despite use of Request location updates?

I am a newbie to android programming and i have been attempting to use geofence to activate alaram services in my app. It worked fine until one day it showed Null pointer reference to double.getlatitude(). I have searched websites with no result. i have used requestLocationUpdates to get updates from the user location.
Here is my code-
package saksham.geofencing;
import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.location.Geofence;
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.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.ArrayList;
public class MapsActivity extends FragmentActivity implements LocationListener{
private GoogleMap googleMap; // Might be null if Google Play services APK is not available.
public SQLiteDatabase db;
ArrayList<Geofence> mGeofences;
public double latitude=77.80;
public double longitude=55.76;
Double valueindex=0.0;
private int request=0;
/**
* Geofence Coordinates
*/
ArrayList<LatLng> mGeofenceCoordinates;
/**
* Geofence Store
*/
private GeofenceStore mGeofenceStore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGeofences = new ArrayList<Geofence>();
mGeofenceCoordinates = new ArrayList<LatLng>();
db = openOrCreateDatabase("CoordsDB", Context.MODE_PRIVATE, null);
// db.execSQL("CREATE TABLE IF NOT EXISTS Coordinates(number DOUBLE,latitude DOUBLE,longitude DOUBLE);");
// db.execSQL("INSERT INTO Coordinates VALUES('Fixed', 28.61,77.20)");
setContentView(R.layout.activity_maps);
SupportMapFragment supportMapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
/**
* SupportMapFragment belongs to the v4 support library, contrary to the default MagFragment that is a native component in Android.
SupportMapFragment will support more Android versions, but it is also an additional library you have to add in your project,
so I think it really depends on the Android versions you are targeting:
• On recent versions, the default components should be enough
• On older versions you will need to install the v4 support library and maybe others
*
*/
googleMap = supportMapFragment.getMap();
Log.i("My activity", "maps=" + googleMap);
googleMap.setMyLocationEnabled(true);
/**
* setMyLocationEnabled(true/false) shows the true location when the GPS is switched on from the device. It is an inbuilt feature of the googlemaps .
*/
LocationManager locationManager = (LocationManager) getSystemService(Service.LOCATION_SERVICE);
// getting GPS status
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.i("My activity", "gps is" +isGPSEnabled);
// getting network status
boolean isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Log.i("My activity", "network is" +isNetworkEnabled);
Criteria crta = new Criteria();
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD) {
crta.setAccuracy(Criteria.ACCURACY_FINE);
}else{
crta.setAccuracy(Criteria.ACCURACY_MEDIUM);
}
/**
* we have used .setAccuracy as fine for higher SDks than gingerbread .Gingerbread is used as a reference because in apks lower
* than gingerbread there is very poor geofencing, with gingerbread google made it a lot easier for locationservices to be used for devleopers.
* it had improved set of tools for Location Services, which included geofencing and substantially improved location discovery.
*/
crta.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(crta, true);
/**
* It request Location updates after every 5 sec or if the user traveled 10m
*/
Log.i("My activity", "manager is " + locationManager);
Log.i("My activity", "provider is " + provider);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
MapsActivity.this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 100);
// 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;
}
}
Location location = locationManager.getLastKnownLocation(provider);
Log.i("Location is", location + "");
if (location != null) {
onLocationChanged(location);
}
else
{
locationManager.requestLocationUpdates(provider,
( 1000),0, this);
Log.i("REached here","here");
onLocationChanged(location);
}
/**
* the Permission is requested after every 5 sec or at a distance of 2 metres by the user.
*/
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 100: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Thanks for the permission", Toast.LENGTH_LONG).show();
// permission was granted, yay! do the
// calendar task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "You did not allow to access your current location", Toast.LENGTH_LONG).show();
}
}
// other 'switch' lines to check for other
// permissions this app might request
}
}
#Override
public void onLocationChanged(Location location) {
CameraPosition INIT =
new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(),location.getLongitude()))
.zoom( 17.5F )
.bearing( 300F) // orientation
.tilt( 50F) // viewing angle
.build();
// use GooggleMap mMap to move camera into position
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(INIT));
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
// mGeofenceStore.disconnect();
super.onStop();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
public void Add(View view) {
if (request <= 3) {
mGeofenceCoordinates.add(new LatLng(latitude, longitude));
Log.i("The id is", "" + valueindex);
mGeofences.add(new Geofence.Builder()
// The coordinates of the center of the geofence and the radius in meters.
.setRequestId("" + valueindex)
.setCircularRegion(latitude, longitude, 30)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
// Required when we use the transition type of GEOFENCE_TRANSITION_DWELL
.setLoiteringDelay(50000)
.setTransitionTypes(
Geofence.GEOFENCE_TRANSITION_ENTER
| Geofence.GEOFENCE_TRANSITION_DWELL
| Geofence.GEOFENCE_TRANSITION_EXIT).build());
mGeofenceStore = new GeofenceStore(this, mGeofences);
valueindex++;
request++;
// Cursor c = db.rawQuery("SELECT * FROM Coordinates WHERE Id='"+valueindex+"'", null);
googleMap.addMarker(new MarkerOptions().snippet("Radius:30m").draggable(false).title(valueindex + "").position(new LatLng(latitude,longitude)));
}
else{
Toast.makeText(this,"Maximum limit exceeded",Toast.LENGTH_LONG).show();
}
}
}
and here is my Logcat-
Process: saksham.geofencing, PID: 12102
java.lang.RuntimeException: Unable to start activity ComponentInfo{saksham.geofencing/saksham.geofencing.MapsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at saksham.geofencing.MapsActivity.onCreate(MapsActivity.java:122)
at android.app.Activity.performCreate(Activity.java:6245)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
            at android.app.ActivityThread.-wrap11(ActivityThread.java)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5443)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
01-24 02:11:14.268 12102-12102/saksham.geofencing I/Process﹕ Sending signal. PID: 12102 SIG: 9
please help!!!
Use the fused location api ... this is from an intent service so you will need to just pick out the pieces you need... also are you using the emulator? if so the last known location always used to give me trouble/null values.. are you telneting in and using geofix?
package geoimage.ret.geoimage;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
/**
* An {#link IntentService} subclass for handling asynchronous task requests in
* a service on a separate handler thread.
* <p/>
* TODO: Customize class - update intent actions, extra parameters and static
* helper methods.
*/
public class GetLocationService extends IntentService implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
// TODO: Rename actions, choose action names that describe tasks that this
// IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
private static final String ACTION_LOCATION = "location";
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
public GetLocationService() {
super("GetLocationService");
}
/**
* Starts this service to perform action Baz with the given parameters. If
* the service is already performing a task this action will be queued.
*
* #see IntentService
*/
// TODO: Customize helper method
public static void startGetLocation(Context context) {
Intent intent = new Intent(context, GetLocationService.class);
intent.setAction(ACTION_LOCATION);
context.startService(intent);
}
#Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_LOCATION.equals(action)) {
handleLocation();
}
}
}
/**
* Handle action Baz in the provided background thread with the provided
* parameters.
*/
private void handleLocation() {
// TODO: Handle action Baz
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mGoogleApiClient.connect();
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1);
mLocationRequest.setFastestInterval(1);
mLocationRequest.setNumUpdates(1);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
sendBroadcast(connectionResult.getErrorMessage());
}
#Override
public void onLocationChanged(Location location) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
App.setLat(location.getLatitude());
App.setLon(location.getLongitude());
mGoogleApiClient.disconnect();
sendBroadcast("LocationObtained");
}
private void sendBroadcast(String errStatus) {
Intent intent = new Intent("location");
intent.putExtra("status", errStatus);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
stopSelf();
}
}
You are manually calling onLocationChanged() with a null value in the else branch here:
if (location != null) {
onLocationChanged(location);
}
else
{
locationManager.requestLocationUpdates(provider,
( 1000),0, this);
Log.i("REached here","here");
// location is null here
onLocationChanged(location);
}
When you request location updates, the onLocationChanged callback will be called by the LocationManager.
The LocationListener which you're implementing is from the google api, that import is this:
import com.google.android.gms.location.LocationListener;
and not this:
import android.location.LocationListener;
It's also important that the LocationClient is connected before you do this. Also don't call it in the onCreate or onStart methods, but in onResume. For more detail go through: https://developer.android.com/training/location/index.html

Categories

Resources