I don't know why i'm getting null object reference on this code it seems fine but when i push the button and call the connect method it must give me the current location of user but it hangs and jump out, this is the code of my fragment class i already added the permissions to my Manifest file and the app has necessary permissions.
This is not a duplicated post i don't know why people here don't pay attention first in the duplicated post the answer is only for avoid the application to not hang even though here we already have the premission to access the location but it returns null.
public class GalleryFragment extends Fragment implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
private EditText searchinput;
private Button searchbtn;
private JSONArray jsonArray;
private GoogleApiClient mLocationClient;
Location currentLocation;
@SuppressLint("ValidFragment")
public GalleryFragment(JSONArray array) {
// Required empty public constructor
this.jsonArray = array;
}
public GalleryFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_gallery, container, false);
if (mLocationClient == null) {
mLocationClient = new GoogleApiClient.Builder(this.getContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
searchinput = (EditText) rootView.findViewById(R.id.searchfld);
searchbtn = (Button) rootView.findViewById(R.id.searchbtn);
searchbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String input = searchinput.getText().toString();
mLocationClient.connect();
}
});
return rootView;
}
@Override
public void onConnected(@Nullable Bundle bundle) {
Log.i("salam", " Connected");
if(ContextCompat.checkSelfPermission(this.getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
currentLocation = LocationServices.FusedLocationApi.getLastLocation(mLocationClient);
}
Log.i ("salam ", " " + currentLocation.getLongitude());
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
}
Log:
java.lang.NullPointerException: Attempt to invoke virtual method 'float android.location.Location.distanceTo(android.location.Location)' on a null object reference
Update: i fixed my problem by using the right way of access request
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) // grant the access from user when the activity created
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, // if the permission wasn't granted so ask for permission
PERMISSION_ACCESS_FINE_LOCATION);
} else { // if it was granted so get the location
getLocation();
}
}
Then:
@Override
public void onConnected(@Nullable Bundle bundle) { // this is an override method which will execute when we connect to client service of google
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { // if the permission was granted then get the location
LocationServices.FusedLocationApi.requestLocationUpdates( // update the location of user
mLocationClient, mLocationRequest, this);
// You need to ask the user to enable the permissions
LocationTracker tracker = new LocationTracker(getContext()) { // here we use a custom library name Location Tracer on github: https://github.com/quentin7b/android-location-tracker
@Override
public void onLocationFound(@NonNull Location location) {
currentLocation = location;
}
@Override
public void onTimeout() {
}
};
tracker.startListening();
if (currentLocation == null) {
currentLocation = LocationServices.FusedLocationApi.getLastLocation(mLocationClient);
}
} else {
Toast.makeText(getContext(),"The application need to access your location TURN ON the Location Service and Restart the application",Toast.LENGTH_LONG).show();
}
}
And finally manage the request by this method:
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
boolean allowed = true;
switch (requestCode) {
case PERMISSION_ACCESS_FINE_LOCATION:
// If request is cancelled, the result arrays are empty.
for (int res : grantResults) {
allowed = allowed && (res == PackageManager.PERMISSION_GRANTED);
}
break;
default:
allowed = false;
break;
}
if (allowed) {
getLocation();
} else {
Toast.makeText(getContext(),"You need to 'Enable' the location service", Toast.LENGTH_SHORT).show();
}
}
good luck and thanks