Boa tarde pessoal.
Estou usando o Google Maps no meu app e estava fucionando antes mas parou de funcionar.
O app quebra enquanto o mapa está sendo carregado. Já pesquisei bastante na internet e nenhuma solução resolveu o problema.
Pelo o pouco que entendi é como se o app não estivesse conseguindo setar os pontos de localização no mapa mas não tenho certeza se é esse é o problema.
Tenho a Google Maps API key dentro do projeto.
Segue código e log abaixo.
Manifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_shop"
android:label="@string/app_name"
android:roundIcon="@mipmap/achei_aqui_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
>
<uses-library android:name="org.apache.http.legacy" android:required="false"/>
<activity android:name="com.acheiAqui.View.SplashScreenActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.acheiAqui.View.HomeActivity" />
<activity android:name="com.acheiAqui.Control.LoginActivity" />
<activity android:name="com.acheiAqui.Control.RegisterUserActivity"></activity>
<activity android:name="com.acheiAqui.Control.RegisterInfoShopActivity" />
<activity android:name="com.acheiAqui.Control.RegisterFoodListActivity" />
<activity android:name="com.acheiAqui.Control.RegisterLocationActivity" />
<activity android:name="com.acheiAqui.View.ProfileShopActivity" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />
</application>
build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 30
defaultConfig {
applicationId "acheiaqui.com.acheiaqui"
minSdkVersion 19
targetSdkVersion 30
versionCode 1
versionName "1.1"
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
vectorDrawables.useSupportLibrary = true
buildToolsVersion "29.0.2"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
implementation 'androidx.annotation:annotation:1.1.0'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation 'androidx.navigation:navigation-fragment:2.3.0'
implementation 'androidx.navigation:navigation-ui:2.3.0'
// implementation group: 'com.android.tools.build', name: 'gradle', version: '3.2.1'
implementation 'com.google.firebase:firebase-database:19.4.0'
implementation 'com.google.firebase:firebase-storage:19.2.0'
implementation 'com.google.firebase:firebase-auth:19.4.0'
implementation 'com.google.firebase:firebase-database:19.4.0'
implementation group: 'com.google.android.gms', name: 'play-services-maps', version: '17.0.0'
implementation group: 'com.google.android.gms', name: 'play-services-location', version: '17.0.0'
implementation group: 'com.google.android.gms', name: 'play-services-analytics', version: '17.0.0'
implementation group: 'com.google.android.gms', name: 'play-services-nearby', version: '17.0.0'
testImplementation 'junit:junit:4.13'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
//Picaso for Photos
implementation group: 'com.squareup.picasso', name: 'picasso', version: '2.8'
//Material Design
implementation 'com.google.android.material:material:1.3.0-alpha02'
}
apply plugin: 'com.google.gms.google-services'
HomeActivity.java
package com.acheiAqui.View;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.provider.Settings;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.acheiAqui.Control.LoginActivity;
import com.acheiAqui.Model.Shop;
import com.acheiAqui.Control.RegisterInfoShopActivity;
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.CameraPosition;
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 com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Map;
import acheiaqui.com.acheiAqui.R;
public class HomeActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
private Marker currentLocationMaker;
private LatLng currentLocationLatLong;
private DatabaseReference mDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mDatabase = FirebaseDatabase.getInstance().getReference();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
Intent intent = getIntent();
intent.getExtras();
if(intent.hasExtra("success")){
Toast.makeText(this, intent.getStringExtra("success"), Toast.LENGTH_SHORT).show();
}
mapFragment.getMapAsync(this);
startGettingLocations();
getMarkers();
}
//funcao que carrega o mapa quando o aplicativo e aberto
public void onMapReady(GoogleMap googleMap)
{
mMap = googleMap;
/*
MarkerOptions markerShop = new MarkerOptions();
markerShop.icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_shop));
MarkerOptions markerAtualLocation = new MarkerOptions();
markerAtualLocation.icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_shop_round));*/
}
//funcao que pega a localizacao atual do cliente, caso este permita que sua localizacao seja utilizada,
// plota um marcador no mapa e coloca foco do mapa nessa atual localizacao
public void onLocationChanged(Location location) {
//quando a localizacao atual do usuario mudar, ele retira o marcador anterior, caso tenha existido, e cria outro
if (currentLocationMaker != null) {
currentLocationMaker.remove();
}
//adiciona o marcador com a localizacao atual do usuario
currentLocationLatLong = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(currentLocationLatLong);
markerOptions.title("Localização atual");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
currentLocationMaker = mMap.addMarker(markerOptions);
currentLocationMaker.setDraggable(true); //permite que o marcador possa ser trocado de lugar
//quando a localizacao atual do usuario muda, o foco do mapa muda para o ponto atual do usuario e aumenta
//o zoom do mapa, mostrando mais detalhes do mesmo
CameraPosition cameraPosition = new CameraPosition.Builder().zoom(17).target(currentLocationLatLong).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
//Toast.makeText(this, "Localização atualizada", Toast.LENGTH_SHORT).show();
getMarkers();
}
private ArrayList<String> findUnAskedPermissions(ArrayList<String> wanted) {
ArrayList<String> result = new ArrayList<>();
for (String perm : wanted) {
if (!hasPermission(perm)) {
result.add(perm);
}
}
return result;
}
private boolean hasPermission(String permission) {
if (canAskPermission()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED);
}
}
return true;
}
//caso a versao do celular seja maior que a marshmallow, o aplicativo pergunta se pode usar a localizacao
//do usuario, caso contrario, ele ja tem essa informacao a partir das confifuracoes do arquivo do manifest
private boolean canAskPermission() {
return (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1);
}
//funcao que verifica se o GPS do usuario esta ativado, e caso nao esteja, perguna ao mesmo se deseja ativa-lo
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("GPS desativado!");
alertDialog.setMessage("Ativar GPS?");
alertDialog.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialog.setNegativeButton("Não", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
//funcao que pega a localizaao atual do usuario, via GPS ou via Internet
private void startGettingLocations() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean isGPS = false;
if (lm != null) {
isGPS = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
boolean isNetwork = false;
if (lm != null) {
isNetwork = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
boolean canGetLocation = true;
int ALL_PERMISSIONS_RESULT = 101;
long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;// Distance in meters
long MIN_TIME_BW_UPDATES = 1000 * 10;// Time in milliseconds
ArrayList<String> permissions = new ArrayList<>();
ArrayList<String> permissionsToRequest;
permissions.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
permissions.add(android.Manifest.permission.ACCESS_COARSE_LOCATION);
permissionsToRequest = findUnAskedPermissions(permissions);
//Verifica se o GPS ou Internet do usuario esta ligada, caso nao esteja, pergunta se o mesmo deseja ativa-la
if (!isGPS && !isNetwork) {
showSettingsAlert();
} else {
//verifica permissoes de uso do GPS para versoes anteriores ao marshmallow
//para versoes anteriores ao marshmallow, a localizacao ja pode ser adquirida a partir da
//configucao do arquivo do manifest
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (permissionsToRequest.size() > 0) {
requestPermissions(permissionsToRequest.toArray(new String[permissionsToRequest.size()]),
ALL_PERMISSIONS_RESULT);
canGetLocation = false;
}
}
}
//verfica se a permissao para utilizar a localizacao foi concedida
if (ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permissão negada", Toast.LENGTH_SHORT).show();
return;
}
//atualiza a localizacao do usuario, a partir do GPS ou Intenet
if (canGetLocation) {
if (isGPS) lm.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
else if (isNetwork) {
lm.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
}
} else {
Toast.makeText(this, "Não é possível obter a localização", Toast.LENGTH_SHORT).show();
}
}
private void getMarkers(){
mDatabase.child("shop").addListenerForSingleValueEvent(
new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Get map of users in datasnapshot
if (dataSnapshot.getValue() != null) {
getAllLocations((Map<String,Object>) dataSnapshot.getValue());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
//handle databaseError
}
});
}
private void getAllLocations(Map<String, Object> locations) {
for (Map.Entry<String, Object> entry : locations.entrySet()) {
Shop shop = new Shop();
Map singleLocation = (Map) entry.getValue();
shop.setName((String) singleLocation.get("name"));
shop.setInfo((String) singleLocation.get("info"));
shop.setId((String) singleLocation.get("id"));
shop.setReference((String) singleLocation.get("reference"));
shop.setFood((String) singleLocation.get("food"));
shop.setLatitude((Double) singleLocation.get("latitude"));
shop.setLongitude((Double) singleLocation.get("longitude"));
LatLng latLng = new LatLng(shop.getLatitude(), shop.getLongitude());
addGreenMarker(shop, latLng).setTag(shop);
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
@Override
public void onInfoWindowClick(Marker marker) {
Shop actualShop = (Shop) marker.getTag();
Intent intent = new Intent(HomeActivity.this, ProfileShopActivity.class);
intent.putExtra("name", actualShop.getName());
intent.putExtra("info", actualShop.getInfo());
intent.putExtra("id", actualShop.getId());
intent.putExtra("reference", actualShop.getReference());
intent.putExtra("food", actualShop.getFood());
startActivity(intent);
}
});
}
}
private Marker addGreenMarker(final Shop shop, LatLng latLng) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(shop.getName());
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_VIOLET));
Marker shopMarker = mMap.addMarker(markerOptions);
return shopMarker;
}
//funcoes padroes da classe LocationListerner. Nao foi necessario sobrescreve-las para manipular o mapa
//e a localizacao atual do usuario
@Override
public void onStatusChanged(String provider,int status, Bundle extras){
}
@Override
public void onProviderEnabled(String provider){
}
@Override
public void onProviderDisabled(String provider){
}
public void registerNewShop(View view){
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
}
Shop.java
package com.acheiAqui.Model;
import android.widget.TextView;
public class Shop
{
private String id;
private String name;
private String info;
private String reference;
private String food;
private double latitude;
private double longitude;
public Shop(String name, String info, String reference, String food, double latitude, double longitude)
{
this.name = name;
this.info = info;
this.reference = reference;
this.food = food;
this.latitude = latitude;
this.longitude = longitude;
}
public Shop(){
}
public String getFood() {
return food;
}
public void setFood(String food) {
this.food = food;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
}
activity_home.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.acheiAqui.View.HomeActivity">
<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.acheiAqui.View.HomeActivity" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/imageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_margin="30dp"
android:clickable="true"
android:onClick="registerNewShop"
android:rotation="0"
android:background="@android:color/background_dark"
app:srcCompat="@drawable/ic_input_add"
/>
</RelativeLayout>
Log do Android Studio
020-09-28 17:52:46.867 29307-29307/? E/cr_BTSPrefs: No data found for task id: 53
2020-09-28 17:52:46.868 29307-29307/? E/cr_BkgrdTaskScheduler: Task cannot be canceled because no data was found instorage or data was invalid
2020-09-28 17:52:55.538 22149-22149/? E/ActivityThread: Service com.android.providers.downloads.DownloadJobService has leaked ServiceConnection android.media.MediaScannerConnection@1695918 that was originally bound here
android.app.ServiceConnectionLeaked: Service com.android.providers.downloads.DownloadJobService has leaked ServiceConnection android.media.MediaScannerConnection@1695918 that was originally bound here
at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1619)
at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:1511)
at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1674)
at android.app.ContextImpl.bindService(ContextImpl.java:1627)
at android.content.ContextWrapper.bindService(ContextWrapper.java:698)
at android.media.MediaScannerConnection.connect(MediaScannerConnection.java:119)
at com.android.providers.downloads.DownloadScanner.requestScan(DownloadScanner.java:140)
at com.android.providers.downloads.DownloadScanner.requestScanBlocking(DownloadScanner.java:85)
at com.android.providers.downloads.DownloadThread.run(DownloadThread.java:434)
2020-09-28 17:52:55.570 22149-29482/? E/MediaScannerService: Exception in handleMessage
java.lang.NullPointerException: url
at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:128)
at android.content.ContentResolver.delete(ContentResolver.java:1677)
at com.android.providers.downloads.DownloadScanner.onScanCompleted(DownloadScanner.java:184)
at android.media.MediaScannerConnection$1.scanCompleted(MediaScannerConnection.java:53)
at com.android.providers.media.MediaScannerService$ServiceHandler.handleMessage(MediaScannerService.java:226)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at com.android.providers.media.MediaScannerService.run(MediaScannerService.java:162)
at java.lang.Thread.run(Thread.java:764)
2020-09-28 17:52:55.796 1126-1126/? E/lowmemorykiller: Error writing /proc/29376/oom_score_adj; errno=22
2020-09-28 17:52:55.797 1126-1126/? E/lowmemorykiller: Error writing /proc/29361/oom_score_adj; errno=22
2020-09-28 17:52:55.799 1126-1126/? E/lowmemorykiller: Error writing /proc/29361/oom_score_adj; errno=22android.media.MediaScannerConnection$1.scanCompleted(MediaScannerConnection.java:53)
at com.android.providers.media.MediaScannerService$ServiceHandler.handleMessage(MediaScannerService.java:226)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at com.android.providers.media.MediaScannerService.run(MediaScannerService.java:162)
at java.lang.Thread.run(Thread.java:764)
2020-09-28 17:52:55.796 1126-1126/? E/lowmemorykiller: Error writing /proc/29376/oom_score_adj; errno=22
2020-09-28 17:52:55.797 1126-1126/? E/lowmemorykiller: Error writing /proc/29361/oom_score_adj; errno=22
2020-09-28 17:52:55.799 1126-1126/? E/lowmemorykiller: Error writing /proc/29361/oom_score_adj; errno=22
2020-09-28 17:54:43.345 29792-29792/acheiaqui.com.acheiaqui E/AndroidRuntime: FATAL EXCEPTION: main
Process: acheiaqui.com.acheiaqui, PID: 29792
java.lang.NullPointerException: Attempt to invoke virtual method 'double java.lang.Double.doubleValue()' on a null object reference
at com.acheiAqui.View.HomeActivity.getAllLocations(HomeActivity.java:254)
at com.acheiAqui.View.HomeActivity.access$000(HomeActivity.java:43)
at com.acheiAqui.View.HomeActivity$3.onDataChange(HomeActivity.java:232)
at com.google.firebase.database.Query$1.onDataChange(Query.java:179)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6912)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:860)