Application Crashes While Finding current Location on Button Click - android

My Problem Is while the app to running. The onClick function should call my position from GPS by longitude, latitude. But the problem is the app crashes when the button is clicked. What is the solution for this? I have tried to follow instructions from older Stack questions, but the error persists.
Here's the debug message:
-----------------------------------------------------------------------------------------------------------------------------------
java.lang.NullPointerException: Attempt to
invoke virtual method 'void
com.google.android.gms.maps.GoogleMap.animateCamera(com.google.android.gms.maps.CameraUpdate)'
on a null object reference
at
com.booleandev.googlfind.MainActivity.onClick(MainActivity.java:97)
-----------------------------------------------------------------------------------------------------------------------------------
public void onClick(View v) {
if (v == koordinat) {
if (latitude != 0 && longitude != 0) {
Toast.makeText(getApplicationContext(), "Latitude : " + latitude + " Longitude : " + longitude, Toast.LENGTH_LONG).show();
}
}
if (v == posisi_user) {
LatLng user = new LatLng(latitude, longitude);
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
user, 12));
}
}
this is my full MainActivity.java
package com.booleandev.googlfind;
import android.*;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
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.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends FragmentActivity implements LocationListener, OnMapReadyCallback,View.OnClickListener {
GoogleMap googleMap;
double latitude;
double longitude;
Button koordinat;
Button posisi_user;
private final static int MY_PERMISSION_FINE_LOCATION = 101;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
koordinat = (Button) findViewById(R.id.koordinat);
posisi_user = (Button) findViewById(R.id.posisi_user);
koordinat.setOnClickListener(this);
posisi_user.setOnClickListener(this);
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
fm.getMapAsync(this);
CekGPS();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// googleMap.setMyLocationEnabled(true);
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_FINE_LOCATION);
}
}
if (latitude != 0 && longitude != 0) {
Toast.makeText(getApplicationContext(), "Latitude : " + latitude + " Longitude : " + longitude, Toast.LENGTH_LONG).show();
}
}
#Override
public void onClick(View v) {
if (v == koordinat) {
if (latitude != 0 && longitude != 0) {
Toast.makeText(getApplicationContext(), "Latitude : " + latitude + " Longitude : " + longitude, Toast.LENGTH_LONG).show();
}
}
if (v == posisi_user) {
LatLng user = new LatLng(latitude, longitude);
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
user, 12));
}
}
public void CekGPS() {
try {
/* pengecekan GPS hidup / tidak */
LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Info");
builder.setMessage("Anda akan mengaktifkan GPS?");
builder.setPositiveButton("Ya",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
Intent i = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
});
builder.setNegativeButton("Tidak",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
builder.create().show();
}
} catch (Exception e) {
}
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
// menampilkan status google play service
if (status != ConnectionResult.SUCCESS) {
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else {
// Google Play Services tersedia
try {
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Membuat kriteria untuk penampungan provider
Criteria criteria = new Criteria();
// Mencari provider terbaik
String provider = locationManager.getBestProvider(criteria,
true);
// Mendapatkan lokasi terakhir
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(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;
}
locationManager.requestLocationUpdates(provider, 5000, 0, this);
} catch (Exception e) {
}
}
}
#Override
public void onLocationChanged(Location lokasi) {
// TODO Auto-generated method stub
latitude =lokasi.getLatitude();
longitude = lokasi.getLongitude();
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onMapReady(GoogleMap googleMap) {
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setTrafficEnabled(true);
googleMap.setIndoorEnabled(true);
googleMap.setBuildingsEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSION_FINE_LOCATION:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
googleMap.setMyLocationEnabled(true);
}
}
else {
Toast.makeText(getApplicationContext(), "GPS TURN OFF", Toast.LENGTH_SHORT).show();
finish();
}
break;
}
}
}
my activity_main.xml too
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/home_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="10"
>
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="9"
android:name="com.google.android.gms.maps.SupportMapFragment"
class="com.google.android.gms.maps.SupportMapFragment"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal">
<Button
android:id="#+id/koordinat"
style="?android:attr/borderlessButtonStyle"
android:textStyle="bold"
android:layout_height="wrap_content"
android:text="Koordinat User"
android:layout_weight="1"
android:layout_width="0dp" />
<Button
style="?android:attr/borderlessButtonStyle"
android:id="#+id/posisi_user"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Posisi User"/>
</LinearLayout>
</LinearLayout>
the manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="">
<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="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="com.google.android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.google.android.permission.ACCESS_COARSE_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.
-->
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="Secret" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity android:name=".lokasi">
</activity>
<activity android:name=".spalsh">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

You have not initialized the googlemap variable in on map ready
Like this.googleMap=googleMap;
public void onMapReady(GoogleMap googleMap) {
this.googleMap=googleMap;
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setTrafficEnabled(true);
googleMap.setIndoorEnabled(true);
googleMap.setBuildingsEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
}
TRY THIS

Related

How do i get my code to give my current location?

I am trying to get my code to zoom in and give me my exact location once I open the map activity, but instead, I get a map showing the map of Africa.
I have written some codes I got from tutorials online, but none has succeeded in giving what I want.
I tried to use this link
Also tried to use this YouTube video
MapActivity.java:
package com.kiki.doctorlocation;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
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.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.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class MapActivity extends FragmentActivity implements
OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
private GoogleMap mMap;;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setZoomGesturesEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
//Initialize Google Play Services
if (android.os.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);
}
}
private void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#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, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Showing Current Location Marker on Map
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(new Criteria(), true);
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
Location locations = locationManager.getLastKnownLocation(provider);
List<String> providerList = locationManager.getAllProviders();
if (null != locations && null != providerList && providerList.size() > 0) {
double longitude = locations.getLongitude();
double latitude = locations.getLatitude();
Geocoder geocoder = new Geocoder(getApplicationContext(),
Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(latitude,
longitude, 1);
if (null != listAddresses && listAddresses.size() > 0) {
String state = listAddresses.get(0).getAdminArea();
String country = listAddresses.get(0).getCountryName();
String subLocality = listAddresses.get(0).getSubLocality();
markerOptions.title("" + latLng + "," + subLocality + "," + state
+ "," + country);
}
} catch (IOException e) {
e.printStackTrace();
}
}
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
mCurrLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,
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},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
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, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(this, "permission denied",
Toast.LENGTH_LONG).show();
}
return;
}
}
}
}
I expect when I run my code, my map to zoom in and give my current exact location. The code has no errors, that is why I need help.
I will try and assist. I will assume you have all the requisite libraries in your gradle. Check if you have
implementation 'com.google.android.gms:play-services-maps:16.1.0'
implementation 'com.google.android.gms:play-services-location:16.0.0'
implementation 'com.google.android.libraries.places:places:1.0.0'
Also confirm if you have the following permissions (on top of the others you might have)
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
On newer Android Version, you might need to request the permissions on runtime. You can add the stub on your activity.
public static boolean hasPermissions(Context context, String... permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
//Invoking the above function
String[] PERMISSIONS = {Manifest.permission.INTERNET,Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.CAMERA };
if (!hasPermissions(this, PERMISSIONS)) {
ActivityCompat.requestPermissions(this, PERMISSIONS, 1);
}
Your activity could look like this.
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
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.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.api.model.TypeFilter;
import com.google.android.libraries.places.widget.AutocompleteSupportFragment;
import com.google.android.libraries.places.widget.listener.PlaceSelectionListener;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
public class SetPickUpLocation extends FragmentActivity implements OnMapReadyCallback {
SupportMapFragment mapFragment;
private GoogleMap mMap;
private GoogleMap.OnCameraIdleListener onCameraIdleListener;
private TextView resutText;
private FusedLocationProviderClient fusedLocationProviderClient;
private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 5445;
private Location currentLocation;
public static String latitude = null, longitude = null, location = null, area = null;
private boolean firstTimeFlag = true;
Button setLocation;
View mapView;
AutocompleteSupportFragment autocompleteFragment;
String TAG = "Google_Places";
int AUTOCOMPLETE_REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.set_pickup_location);
resutText = (TextView) findViewById(R.id.dragg_result);
setLocation = (Button) findViewById(R.id.setLocation);
autocompleteFragment = (AutocompleteSupportFragment)
getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mapView = mapFragment.getView();
Toast.makeText(SetPickUpLocation.this, ConstantValues.DRAG_MAP_MARKER, Toast.LENGTH_SHORT).show();
configureCameraIdle();
Places.initialize(getApplicationContext(), ConstantValues.GOOGLE_API_KEY);
setLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (latitude != null && longitude != null) {
//you can put your logic here
}else{
//you can put your logic here
}
}
});
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME , Place.Field.LAT_LNG));
//autocompleteFragment.setTypeFilter(TypeFilter.REGIONS);
autocompleteFragment.setCountry("KE");
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
//Log.d(TAG , place.getName() + ", " + place.getId());
if(mMap != null){
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(place.getLatLng(), 16);
mMap.animateCamera(cameraUpdate);
autocompleteFragment.setText("");
}
//
//mMap.mo
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.d(TAG , "An error occurred: " + status);
}
});
}
#Override
protected void onStop() {
super.onStop();
if (fusedLocationProviderClient != null)
fusedLocationProviderClient.removeLocationUpdates(mLocationCallback);
}
#Override
protected void onResume() {
super.onResume();
if (isGooglePlayServicesAvailable()) {
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
startCurrentLocationUpdates();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
fusedLocationProviderClient = null;
mMap = null;
}
private void configureCameraIdle() {
onCameraIdleListener = new GoogleMap.OnCameraIdleListener() {
#Override
public void onCameraIdle() {
LatLng latLng = mMap.getCameraPosition().target;
Geocoder geocoder = new Geocoder(SetPickUpLocation.this);
try {
List<Address> addressList = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
if (addressList != null && addressList.size() > 0) {
String locality = addressList.get(0).getAddressLine(0);
String country = addressList.get(0).getCountryName();
latitude = Double.toString(latLng.latitude);
longitude = Double.toString(latLng.longitude);
if (!locality.isEmpty() && !country.isEmpty()) {
resutText.setText(locality);
location = locality;
try{
String city = addressList.get(0).getAdminArea();
if(!city.isEmpty()){
area = city;
}
}catch (Exception e){
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnCameraIdleListener(onCameraIdleListener);
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;
}
mMap.setMyLocationEnabled(true);
if (mapView != null &&
mapView.findViewById(Integer.parseInt("1")) != null) {
// Get the button view
View locationButton = ((View) mapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
// and next place it, on bottom right (as Google Maps app)
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)
locationButton.getLayoutParams();
// position on right bottom
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
layoutParams.setMargins(0, 0, 100, 330);
}
}
private final LocationCallback mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
if (locationResult.getLastLocation() == null)
return;
currentLocation = locationResult.getLastLocation();
if (firstTimeFlag && mMap != null) {
animateCamera(currentLocation);
firstTimeFlag = false;
}
//showMarker(currentLocation);
}
};
private void startCurrentLocationUpdates() {
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(3000);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
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) {
ActivityCompat.requestPermissions(SetPickUpLocation.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
return;
}
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest, mLocationCallback, Looper.myLooper());
}
private boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int status = googleApiAvailability.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status)
return true;
else {
if (googleApiAvailability.isUserResolvableError(status))
Toast.makeText(this, "Please Install google play services to use this application", Toast.LENGTH_LONG).show();
}
return false;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION) {
if (grantResults[0] == PackageManager.PERMISSION_DENIED)
Toast.makeText(this, "Permission denied by uses", Toast.LENGTH_SHORT).show();
else if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
startCurrentLocationUpdates();
}
}
private void animateCamera(#NonNull Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(getCameraPositionWithBearing(latLng)));
}
#NonNull
private CameraPosition getCameraPositionWithBearing(LatLng latLng) {
return new CameraPosition.Builder().target(latLng).zoom(16).build();
}
}
The XML Layout (you can use your own ViewGroups)
<RelativeLayout 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:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".orders.SetPickUpLocation">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.v7.widget.CardView
android:id="#+id/idCardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
app:cardCornerRadius="4dp">
<fragment
android:id="#+id/autocomplete_fragment"
android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.v7.widget.CardView>
<ImageView
android:layout_width="36dp"
android:layout_height="36dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/ic_google_map_marker"
android:text="TextView" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#ffffff"
android:orientation="vertical"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="#dimen/activity_horizontal_margin"
android:paddingBottom="#dimen/activity_horizontal_margin"
android:weightSum="3">
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.2"
android:gravity="center_vertical"
android:src="#drawable/ic_google_map_marker" />
<TextView
android:id="#+id/dragg_result"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="2.8"
android:fontFamily="#font/museo"
android:gravity="left"
android:paddingLeft="3dp"
android:text="Select this location"
android:textColor="#000"
android:textSize="18dp" />
</LinearLayout>
<Button
android:id="#+id/setLocation"
style="?android:attr/borderlessButtonStyle"
android:layout_width="match_parent"
android:layout_height="65dp"
android:layout_marginBottom="#dimen/activity_horizontal_margin"
android:fontFamily="#font/museo"
android:text="Select this location"
android:textColor="#ffffff"
android:textSize="18sp"
android:textStyle="bold" />
</LinearLayout>
</RelativeLayout>
I hope this helps and also use your own icons/drawables as I have not included them here.
So the previous answer didn't work for me so i decide to sort another way out and this is the the code that is working for me
MapActivity.java
import android.app.Dialog;
import android.content.pm.PackageManager;
import android.location.Address;
imsport android.location.Geocoder;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
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.BitmapDescriptorFactory;
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 MapActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (GSA()) {
Toast.makeText(this, "Services perfect", Toast.LENGTH_SHORT).show();
setContentView(R.layout.activity_map);
initMap();
} else {
}
}
private void initMap() {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync((OnMapReadyCallback) this);
}
public boolean GSA() {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int isAvailable = googleApiAvailability.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS)
return true;
else if (googleApiAvailability.isUserResolvableError(isAvailable)) {
Dialog dialog = googleApiAvailability.getErrorDialog(this, isAvailable, 0);
dialog.show();
} else {
Toast.makeText(this, "Can't connect to Google services", Toast.LENGTH_SHORT).show();
}
return false;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// gotoLocationzoom(-1.276680, 36.904785, 15);
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
// Activity#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 Activity#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
// LatLng sydney = new LatLng(-1.276680, 36.904785);
// googleMap.addMarker(new MarkerOptions().position(sydney)
// .title("Marker in white hse"));
// googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
private void gotoLocationzoom (double lat, double lng, float zoom){
LatLng latLng = new LatLng(lat,lng);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng,zoom);
mMap.animateCamera(cameraUpdate);
}
public void search(View view) throws IOException {
EditText et = (EditText) findViewById(R.id.editText);
String location = et.getText().toString();
Geocoder geocoder = new Geocoder(this);
List<Address> list = geocoder.getFromLocationName(location,1);
Address address = list.get(0);
String locality = address.getLocality();
Toast.makeText(this, locality, Toast.LENGTH_SHORT).show();
double lat = address.getLatitude();
double lng = address.getLongitude();
gotoLocationzoom(lat,lng,15);
LatLng latLng = new LatLng(lat,lng);
mMap.addMarker(new MarkerOptions().position(latLng).title(location).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)));
}
}
activity_map.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".MapActivity">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="500dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="0dp"
tools:context="com.example.mapwithmarker.MapsMarkerActivity" />
<EditText
android:id="#+id/editText"
android:layout_width="291dp"
android:layout_height="59dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginEnd="115dp"
android:layout_marginRight="115dp"
android:ems="10"
android:hint="Enter your destination"
android:inputType="textPersonName" />
<Button
android:id="#+id/button"
android:layout_width="100dp"
android:layout_height="59dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginEnd="17dp"
android:layout_marginRight="17dp"
android:onClick="search"
android:text="search" />
</RelativeLayout>
permissions i added to my AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE.EXTERNAL.STORAGE"/>
<uses-permission android:name="com.google.androidproviders.gsf.permissions.READ.GSERVICES"/>
<uses-permission android:name="com.kiki.doctorlocation.permission.MAPS.RECEIVE"/>
<uses-feature android:glEsVersion="0x00020000" android:required="true"/>
<permission android:name="com.kiki.doctorlocation.permission.MAPS.RECEIVE" android:protectionLevel="signature"/>
This is the code that worked for me...Thanks for the insights though

How to Fetch a location?

I am using android studio 3.1.4 to learn to develop android apps.
I am trying to get gps location. But, it is not working. I have been trying this for whole day. Please, somebody help me through this.
My gpsTracker class
package com.prios.pratice;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
public class GPSTracker extends AppCompatActivity implements LocationListener
{
private LocationManager locationManager;
private String provider, LOCATION = "N/A";
public String getLocation() {
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
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 "Cannot Get Location!";
}
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
Log.d("Location:", "Not Available");
}
return LOCATION;
// Boolean isGPSenabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
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;
}
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
Log.d("Location:", lat+", "+lng);
LOCATION = lat + ", " + lng;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
And My Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.prios.practice">
<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"/>
<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>
When, I try to run this on device, it closes and doesn't show anything. Location is enabled in my device.
My HomeFragment Class:
package com.prios.practice;
import android.app.Activity;
import android.content.Context;
import android.location.OnNmeaMessageListener;
import android.os.Bundle;
//import android.support.v4.app.Fragment;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
/**
* A simple {#link Fragment} subclass.
*/
public class HomeFragment extends Fragment {
private Button;
private GPSTracker gpsTracker;
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
String location = gpsTracker.getLocation();
Toast.makeText(getActivity(), location, Toast.LENGTH_SHORT).show();
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
Activity activity = (Activity) context;
}
#Override
public void onResume() {
super.onResume();
}
}
You will need to request the permissions during runtime (from code) too.
Call the method ActivityCompat#requestPermissions() before using location related stuffs.
Read the documentation for more details: https://developer.android.com/training/permissions/requesting
Why GPSTracker inherits AppCompatActivity ? You can't use it like this in your fragment.
GPSTracker must be a Singleton, or something like that, but not related to Activity...
Have you read this guide ?
https://developer.android.com/training/location/receive-location-updates
It finally works.
package com.prios.practice;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
public class GPSTracker extends AppCompatActivity implements LocationListener {
private LocationManager locationManager;
private String provider, LOCATION="N/A";
private Context context;
private Activity activity;
public GPSTracker(Activity activity) {
this.context = activity.getApplicationContext();
this.activity = activity;
// Get the location manager
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
if (ActivityCompat.checkSelfPermission(context, 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.
ActivityCompat.requestPermissions(this.activity,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
99);
}
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
Log.e("TAG", "GPS is on");
LOCATION = location.getLatitude()+","+location.getLongitude();
}
else{
//This is what you need:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
}
}
public String getLocation() {
return LOCATION;
}
#Override
public void onLocationChanged(Location location) {
if(location!=null) {
locationManager.removeUpdates(this);
Double lat = (Double) (location.getLatitude());
Double lng = (Double) (location.getLongitude());
LOCATION = lat.toString() + "," + lng.toString();
// Toast.makeText(this, LOCATION, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// Toast.makeText(this, "Enabled new provider " + provider,
// Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
// Toast.makeText(this, "Disabled provider " + provider,
// Toast.LENGTH_SHORT).show();
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 99: {
// 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(context,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Request location updates:
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
}
}
}

onLocationChanged called only the first time i open the application, but not anymore if app becomes inactive and active again

i'm trying to build a GPS app with Android Studio. It's working okay on the first run but whenever i close the app and open it again or go to desktop and back into it, as i have figured until now, my LocationListener doesn't get called anymore.
Practically what happens is that it doesn't display my location as intended the second time. No error no anything.
Here's my code, thanks in advance if you can help. I've been searching a lot :(
package com.madnzz.googlemapsstuff;
import android.*;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Camera;
import android.graphics.drawable.BitmapDrawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.support.annotation.NonNull;
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.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
import com.google.android.gms.common.api.GoogleApiClient;
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.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.GroundOverlay;
import com.google.android.gms.maps.model.GroundOverlayOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.sql.Time;
import java.util.Random;
import com.google.android.gms.appindexing.AndroidAppUri;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import static com.madnzz.googlemapsstuff.R.id.activity_chooser_view_content;
import static com.madnzz.googlemapsstuff.R.id.repositionButton;
/*
TODO: Replace retard user icon with improved one
*IMPLEMENT the way the user is facing. http://android-coding.blogspot.ro/2012/03/create-our-android-compass.html
*
TODO: implement GPS routes https://www.youtube.com/watch?v=CCZPUeY94MU or http://wptrafficanalyzer.in/blog/drawing-driving-route-directions-between-two-locations-using-google-directions-in-google-map-android-api-v2/
*REPLACE consumed path with cookie crumb graphic
TODO: save path and able to share with others.
TODO later: Battery efficiency https://developer.android.com/guide/topics/location/strategies.html
*/
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
////////////////////////////////////////////////////////////////////////////////////
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startListening();
}
}
}
public void startListening() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
}
}
Random random=new Random();
GroundOverlayOptions[] c00kieCrumb=new GroundOverlayOptions[200];
int i=0;
///////////////////////////////////////////////////////////////////////////////
public void addCrumb(LatLng userLocation){
int randomCrumbBearing=random.nextInt(36)*10;
c00kieCrumb[i] = new GroundOverlayOptions()
.image(BitmapDescriptorFactory.fromResource(R.drawable.frateeeee))
.position(userLocation, 3,3).bearing(randomCrumbBearing);
c00kieCrumb[i].isVisible();
i++;
for (int j = 0; j < i; j++) {
mMap.addGroundOverlay(c00kieCrumb[j]);
}
}//adds new cookie crumb to user location
public void putCrumbConditions(LatLng userLocation){
for (int j = 0; j < i; j++) {
mMap.addGroundOverlay(c00kieCrumb[j]);
}
if (i == 0) {
addCrumb(userLocation);
} else {
if (Math.abs((c00kieCrumb[i - 1].getLocation().latitude - userLocation.latitude)) > 0.00003
|| Math.abs(c00kieCrumb[i - 1].getLocation().longitude - userLocation.longitude) > 0.00003) {
addCrumb(userLocation);
}
}
}//adds a new cookie crumb to the user location 4
// IF THE USER IS 0.00003 UNITS AWAY FROM LAST CRUMB PLACED
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("ZiciCinci created shit", "Am ajuns aici");
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
protected void onDestroy(Bundle savedInstanceState){
super.onDestroy();
}
LatLng [] locationCalibrator,savedUserLocation;
LatLng userLocation,previousUserLocation;
Boolean gpsCalibrationInProgress,tooClose,firstIteration,mapCenteredOnUserPosition,cameraFollowUserPosition;
int locationIteration=0,savedUserLocationPos;
ImageButton repositionButton;
#Override
public void onMapReady(GoogleMap googleMap) {
Log.i("ZiciPatru map is ready","Am ajuns aici");
mMap = googleMap;
c00kieCrumb[0] = new GroundOverlayOptions();
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationCalibrator = new LatLng[100];
gpsCalibrationInProgress = true;
locationIteration = 0;
i = 0;
savedUserLocation = new LatLng[3];
savedUserLocationPos = 0;
tooClose = true;
firstIteration = true;
mapCenteredOnUserPosition = true;
cameraFollowUserPosition = true;
previousUserLocation = new LatLng(0, 0);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.i("Zici3 gps calibration","Am ajuns aici");
userLocation = new LatLng(location.getLatitude(), location.getLongitude());
if (!gpsCalibrationInProgress) {
if (Math.abs(previousUserLocation.latitude - userLocation.latitude) > 0.000003 ||
Math.abs(previousUserLocation.latitude - userLocation.longitude) > 0.000003) {
mMap.clear();
mMap.addMarker(new MarkerOptions().position(userLocation).title("Your Location").icon(BitmapDescriptorFactory.fromResource(R.drawable.edytardin64x64)).rotation(0));
if (firstIteration) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
firstIteration = false;
}
LatLng userDestination = new LatLng(44.4187432, 26.1556372);
mMap.addMarker(new MarkerOptions().position(userDestination).title("COOOOKIESTUFF").icon(BitmapDescriptorFactory.fromResource(R.drawable.c00ki3_marker_128x128)));
putCrumbConditions(userLocation);
}
} else {
Toast.makeText(getApplicationContext(), "Calibrating gps, please stand still", Toast.LENGTH_SHORT).show();
locationCalibrator[locationIteration] = userLocation;
locationIteration++;
if (locationIteration >= 2) {
if (Math.abs(locationCalibrator[locationIteration - 1].latitude - userLocation.latitude) < 0.0001
&& Math.abs(locationCalibrator[locationIteration - 1].longitude - userLocation.longitude) < 0.0001
&& Math.abs(locationCalibrator[locationIteration - 2].latitude - userLocation.latitude) < 0.0001
&& Math.abs(locationCalibrator[locationIteration - 2].latitude - userLocation.latitude) < 0.0001) {
gpsCalibrationInProgress = false;
}
}
}
previousUserLocation = userLocation;
repositionButton = (ImageButton) findViewById(R.id.repositionButton);
repositionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("rarara","q");
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
repositionButton.setBackgroundResource(R.drawable.location_centered);
mapCenteredOnUserPosition = true;
cameraFollowUserPosition = true;
}
});
if (mapCenteredOnUserPosition) {
mMap.setOnCameraMoveStartedListener(new GoogleMap.OnCameraMoveStartedListener() {
#Override
public void onCameraMoveStarted(int reason) {
if (reason == GoogleMap.OnCameraMoveStartedListener.REASON_GESTURE) {
repositionButton.setBackgroundResource(R.drawable.location_not_centered);
mapCenteredOnUserPosition = false;
cameraFollowUserPosition = false;
}
}
});
}
if (cameraFollowUserPosition) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
repositionButton.setBackgroundResource(R.drawable.location_centered);
}
LocationServices.FusedLocationApi.removeLocationUpdates(GoogleApiClient,this)
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Toast.makeText(getApplicationContext(), "Please activate your location", Toast.LENGTH_SHORT);
}
};
if (Build.VERSION.SDK_INT < 23) {
startListening();
} else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastKnownLocation != null) {
LatLng userLocation = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
if (!tooClose) {
mMap.clear();
mMap.addMarker(new MarkerOptions().position(userLocation).title("Your Location").icon(BitmapDescriptorFactory.fromResource(R.drawable.edytardin64x64)));
}
tooClose = false;
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
}
}
}
My android manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.madnzz.googlemapsstuff">
<!--
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" />
<application
android:allowBackup="true"
android:exported="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<!--
android:roundIcon="#mipmap/ic_launcher_round"
-->
<!--
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>
And layout file:
<RelativeLayout 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=".MapsActivity" >
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.madnzz.googlemapsstuff.MapsActivity"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<ImageButton
android:id="#+id/repositionButton"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="40dp"
android:layout_marginEnd="30dp"/>
<!--android:onClick="repositionMap"-->
android:background="#drawable/location_not_centered" />
</RelativeLayout>
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastKnownLocation != null) {
LatLng userLocation = new LatLng(lastKnownLocation.getLatitude(),
lastKnownLocation.getLongitude());
if (!tooClose) {
mMap.clear();
mMap.addMarker(new MarkerOptions().position(userLocation).title("Your Location").icon(BitmapDescriptorFactory.fromResource(R.drawable.edytardin64x64)));
}
tooClose = false;
} else {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
The problematic part of the your code(and also scenario),
You did make location request if lastKnownLocationis null. After receiving new location one time(onLocationChanged), getLastKnownLocationwill not return null, and location request will not be called for later starts(except boot)
As a result, onLocationChanged called only one time.
getLastKnownLocation will give you the latest location obtained from given provider.It's possible to get null. You just used GPS_PROVIDER but could also try NETWORK_PROVIDER too
mGpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
mNetworkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
With this you can increase chance of getting a location. If both of them null then make location request provider(s) (sorry there is no magic, you must, like others do)

How get location by COARSE location

I'm trying to develo an app that get location by COARSE location. This app must run on Android 6 too than i've implemented permission request on run time, start the map but i can't get my current location... any tips?
This is my main activity:
package com.luca.fontanelle;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.location.LocationListener;
import android.Manifest;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
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.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;
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.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
final static int REQUEST_LOCATION = 199;
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private String providerNetwork = LocationManager.NETWORK_PROVIDER;
private Location mCurrentLocation;
private LocationRequest mLocationRequest;
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(AppIndex.API).build();
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_LOW_POWER)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
// 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);
}
protected void onStart() {
super.onStart();
}
protected void onResume() {
super.onResume();
mGoogleApiClient.connect();
}
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
protected void onStop() {
super.onStop();}
protected void onDestroy() {
super.onDestroy();
}
public void onLocationChanged(Location location) {
mCurrentLocation = location;
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
mMap.animateCamera(cameraUpdate);
locationManager.removeUpdates(this);
mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude())));
mMap.moveCamera(CameraUpdateFactory.zoomTo(15.0f));
}
public void onConnected(Bundle bundle) {
if (controllaPermessi()) {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient,
builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
//final LocationSettingsStates state = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can initialize location
// requests here.
//...
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the user
// a dialog.
Intent gpsOptionsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
//...
break;
}
}
});
/* 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;
}*/
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mCurrentLocation == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}else{
richiestaPermessi();
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
//Log.d("MapsActivity", "Connessione fallita. Codice di errore: " + connectionResult.getErrorCode());
}
}
private boolean controllaPermessi(){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void richiestaPermessi(){
if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION)){
Toast.makeText(getApplicationContext(), "Attiva la localizzazione per usufruire dell'app.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
}
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getApplicationContext(), "Permessi accettati. Puoi usare tutte le funzionalità.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Permessi non accettati. Non puoi accedere alle funzionalità del GPS.", Toast.LENGTH_LONG).show();
}
break;
}
}
#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"));
}
}
Manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.luca.fontanelle">
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="23" />
<permission
android:name="com.luca.fontanelle.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission-sdk-23 android:name="android.permission.INTERNET" />
<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 you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<!--
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" />
<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" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Try this code with google fused location api
1) MainActivity.class
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleMap mMap;
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
protected final static String LOCATION_KEY = "location-key";
protected final static String LAST_UPDATED_TIME_STRING_KEY = "last-updated-time-string-key";
protected GoogleApiClient mGoogleApiClient;
protected LocationRequest mLocationRequest;
protected Location mCurrentLocation;
protected String mLastUpdateTime;
private boolean mycheck, chrckonce;
private LocationManager manager;
private Double lat, lng;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = MainActivity.this;
chrckonce = true;
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLastUpdateTime = "";
updateValuesFromBundle(savedInstanceState);
}
#Override
protected void onStart() {
super.onStart();
if (!manager.isProviderEnabled((LocationManager.GPS_PROVIDER))) {
//GPS is not available show alert
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS SETTINGS");
alertDialog.setMessage("GPS is not enable! Want to go to settings menu?");
alertDialog.setCancelable(false);
alertDialog.setPositiveButton(" Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
finish();
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
finish();
}
});
alertDialog.show();
} else {
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
mycheck = true;
buildGoogleApiClient();
mGoogleApiClient.connect();
mMap.setMyLocationEnabled(true);
}
}
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
lat = location.getLatitude();
lng = location.getLongitude();
if (chrckonce) {
mMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(lat, lng)), 2000, null);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 18));
mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
chrckonce = false;
}
}
//Update location from google fused api
private void updateValuesFromBundle(Bundle savedInstanceState) {
if (savedInstanceState != null) {
if (savedInstanceState.keySet().contains(LOCATION_KEY)) {
mCurrentLocation = savedInstanceState.getParcelable(LOCATION_KEY);
}
if (savedInstanceState.keySet().contains(LAST_UPDATED_TIME_STRING_KEY)) {
mLastUpdateTime = savedInstanceState.getString(LAST_UPDATED_TIME_STRING_KEY);
}
}
}
//synchronized google fused location api
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
//create location request
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
//on resume activity
#Override
public void onResume() {
super.onResume();
if (mycheck == true) {
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
}
}
}
//when activity goes on pause
#Override
protected void onPause() {
super.onPause();
if (mycheck == true) {
if (mGoogleApiClient.isConnected()) {
stopLocationUpdates();
}
}
}
//when activity stops
#Override
protected void onStop() {
if (mycheck == true) {
mGoogleApiClient.disconnect();
}
super.onStop();
}
#Override
public void onConnected(Bundle bundle) {
if (mCurrentLocation == null) {
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
}
startLocationUpdates();
}
//check connection suspended
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
//Location update
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
//location update close when activity closed
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
2) activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent">
</fragment>
</LinearLayout>
In Manifest permissions
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Showing Error ---java.lang.NoClassDefFoundError

When I press the button btnlocation it should go to the Mapsactivity
but it is giving me the error:
java.lang.NoClassDefFoundError
I also added MapsActivity in manifest as usual .. .but why this error? I need the solution.Can any one help me please...
package com.mamun.tasktest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
public class FragmentB extends Fragment implements OnClickListener {
private Button btnLocation;
private LocationManager manager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_b, null, false);
btnLocation = (Button) view.findViewById(R.id.btnLocation);
btnLocation.setOnClickListener(this);
manager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("GPS is currently disabled");
builder.setMessage("Please enable GPS for better view of your location.\nWould you like to change these settings now?");
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
getActivity();
}
});
builder.create().show();
}
return view;
}
#Override
public void onClick(View v) {
if(isMapAvailalble()){
/////////////////////////////
/*
// */
//////////////////////////
Intent in = new Intent(getActivity(),MapsActivity.class);
startActivity(in);
}
}
/*Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE"); intent.putExtra("enabled", false);
sendBroadcast(intent);*/
//if googleplayservis or play store is not available/updated or user recoverable problem occured.
public boolean isMapAvailalble()
{
// to test if there is no googleplayservise
//int resultcode=ConnectionResult.SERVICE_MISSING;
int resultcode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
if(ConnectionResult.SUCCESS==resultcode)
{
return true;
}
else if(GooglePlayServicesUtil.isUserRecoverableError(resultcode))
{
Dialog d = GooglePlayServicesUtil.getErrorDialog(resultcode, getActivity(), 1);
d.show();
}
else
{
Toast.makeText(getActivity()," Google Map API is not supported in your device",Toast.LENGTH_LONG).show();
}
return false;
}
/*public void turnGPSOn()
{
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
((Context) this.ctx).sendBroadcast(intent);
#SuppressWarnings("deprecation")
String provider = Settings.Secure.getString(((Context) ctx).getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
((Context) this.ctx).sendBroadcast(poke);
}*/
}
Manifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mamun.tasktest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="16" />
<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" />
<uses-permission android:name="com.mamun.tasktest.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-library android:name="com.google.android.maps"/>
<permission
android:name="com.mamun.tasktest.permission.MAPS_RECEIVE"
android:protectionLevel="signature" >
</permission>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.mamun.tasktest.MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<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.maps.v2.API_KEY"
android:value="AIzaSyCgGng3iaqbTxJ3B_lYemZBEqXOonUtFEI" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity android:name="MapsActivity"></activity>
</application>
</manifest>
MapsActivity
package com.mamun.tasktest;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.maps.MapActivity;
public class MapsActivity<GeoPoint, OverlayItem> extends MapActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {
MapView mapView;
com.google.android.maps.GeoPoint p;
private LocationManager manager;
private TextView tvAddress;
private Button btnSearch;
private EditText etSearch;
private LocationClient locationClient;
private GoogleMap googleMap;
private MapFragment mapFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
manager = (LocationManager) getSystemService(LOCATION_SERVICE);
tvAddress = (TextView) findViewById(R.id.tvaddress);
btnSearch = (Button) findViewById(R.id.btnSearch);
etSearch = (EditText) findViewById(R.id.etSearch);
mapFragment = (MapFragment) getFragmentManager().findFragmentById(
R.id.maps);
googleMap = mapFragment.getMap();
locationClient = new LocationClient(this, this, this);
}
public void onSearch(View v) {
// Getting user input location
String location = etSearch.getText().toString();
if (location != null && !location.equals("")) {
new GeocoderTask().execute(location);
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
locationClient.connect();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
locationClient.disconnect();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult result) {
}
#Override
public void onConnected(Bundle connectionHint) {
try {
Location currentLocation = locationClient.getLastLocation();
double lat = currentLocation.getLatitude();
double lng = currentLocation.getLongitude();
// txtLocation.setText(lat + ", " + lng);
Geocoder geocoder = new Geocoder(this);
ArrayList<Address> address = (ArrayList<Address>) geocoder
.getFromLocation(currentLocation.getLatitude(),
currentLocation.getLongitude(), 5);
Address addr = address.get(0);
String currentAddress = (addr.getAddressLine(0) + "-"
+ addr.getAdminArea() + "-" + addr.getLocality() + "-"
+ addr.getPostalCode() + "-" + addr.getCountryCode());
MarkerOptions options = new MarkerOptions();
options.position(new LatLng(lat, lng));
options.title(currentAddress);
options.snippet("Current location");
options.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
if (googleMap != null) {
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(lat, lng), 14.0f));
googleMap.addMarker(options);
} else {
Toast.makeText(getApplicationContext(), "Map is null",
Toast.LENGTH_LONG).show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
// An AsyncTask class for accessing the GeoCoding Web Service
private class GeocoderTask extends
AsyncTask<String, Void, ArrayList<Address>> {
#Override
protected ArrayList<Address> doInBackground(String... locationName) {
// Creating an instance of Geocoder class
Geocoder geocoder = new Geocoder(getBaseContext());
ArrayList<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = (ArrayList<Address>) geocoder.getFromLocationName(
locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
#Override
protected void onPostExecute(ArrayList<Address> addresses) {
if (addresses == null || addresses.size() == 0) {
Toast.makeText(getBaseContext(), "No Location found",
Toast.LENGTH_SHORT).show();
return;
}
// Clears all the existing markers on the map
googleMap.clear();
// Adding Markers on Google Map for each matching address
for (int i = 0; i < addresses.size(); i++) {
Address address = (Address) addresses.get(i);
// Creating an instance of GeoPoint, to display in Google Map
LatLng latLng;
latLng = new LatLng(address.getLatitude(),
address.getLongitude());
String addressText = String.format(
"%s, %s",
address.getMaxAddressLineIndex() > 0 ? address
.getAddressLine(0) : "", address
.getCountryName());
MarkerOptions markerOptions = new MarkerOptions();
// markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(addressText);
googleMap.addMarker(markerOptions);
// Locate the first location
if (i == 0)
googleMap.animateCamera(CameraUpdateFactory
.newLatLng(latLng));
}
}
}
class MapOverlay extends com.google.android.maps.Overlay {
#Override
public void draw(Canvas canvas, com.google.android.maps.MapView mapView,
boolean shadow) {
// TODO Auto-generated method stub
super.draw(canvas, mapView, shadow);
Point screenPts = new Point();
mapView.getProjection().toPixels(p, screenPts);
}
#Override
public boolean onTouchEvent(MotionEvent e,
com.google.android.maps.MapView mapView) {
// TODO Auto-generated method stub
if (e.getAction() == 1) {
com.google.android.maps.GeoPoint p = mapView.getProjection().fromPixels(
(int) e.getX(), (int) e.getY());
Toast.makeText(
getBaseContext(),
"Lat: " + p.getLatitudeE6() / 1E6 + ", Lon: "
+ p.getLongitudeE6() / 1E6, Toast.LENGTH_SHORT)
.show();
}
return false;
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
Add Activity into your manifest.xml because you need to give all path if your Activity located into different package.
<activity
android:name="com.mamun.tasktest.MapsActivity"
android:label="MapActivity" >
</activity>
And/or is your Activity belong to the same package then add simply
<activity android:name=".MapsActivity"></activity>
For more information go to:http://developer.android.com/guide/topics/manifest/manifest-intro.html
This is incorrect:
<activity android:name="MapsActivity"></activity>
You need to give full or relative path like this:
<activity android:name="com.mamun.tasktest.MapsActivity"></activity>
or
<activity android:name=".MapsActivity"></activity>
Replace your this tag in manifest
<activity android:name="MapsActivity"></activity>
by :
<activity android:name=".MapsActivity"></activity>
you should specify your full package name while declaring your activity into manifets.
See this link for reference:-
Add a new activity to the AndroidManifest?
You just forget to place a DOt (.) before MapsActivity. So, without that Dot (.) your class path looks like...
com.mamun.tasktestMapsActivity.java
But, it should be as....
com.mamun.tasktest.MapsActivity.java
Now, change this line of your Manifest...
<activity android:name="MapsActivity"></activity>
to...
<activity android:name=".MapsActivity"></activity>
I got the solution....The line "" should be inside application not inside directly on manifest.Like as below....

Categories

Resources