Error when trying to include a mapfragment in an Activity

Asked

Viewed 34 times

0

I have an Activity that should go up with the map (Googlemaps). But when implementing some methods, so that I can for example click and add a marker, it breaks, with the following error:

Attempt to invoke virtual method 'void com.google.android.gms.maps.MapFragment.getMapAsync(com.google.android.gms.maps.Onmapreadycallback)' on a null Object Reference

How can I resolve this issue?

Follows code:

package app.app_app.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.net.Uri;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.os.Bundle;
import android.support.v7.widget.ShareActionProvider;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
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.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.GoogleMap;
import com.google.android.gms.maps.GoogleMapOptions;
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.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.android.gms.maps.model.PolylineOptions;

import java.util.ArrayList;
import java.util.List;

import app.app_app.R;
import app.app_app.domain.MapCoo;
import app.app_app.persistence.SaveSharedPreferences;
import app.app_app.util.GPSUtils;

public class MapActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener, OnMapReadyCallback, GoogleMap.OnCameraChangeListener,
        GoogleMap.OnMapClickListener, GoogleMap.OnMyLocationButtonClickListener {

    Intent intent;
    private ShareActionProvider mShareActionProvider;
    public static MainActivity mainActivity;
    public static Boolean isVisible = false;
    private static final String TAG = "MainActivity";
    private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    SaveSharedPreferences saveSharedPreferences = new SaveSharedPreferences();
    static boolean status = false;

    protected static final String TAG_app = "app";
    private SupportMapFragment mapFragment;
    protected GoogleMap map;
    private LatLng ultimaLocation = null;
    private Acompanhamento acompanhamento = null;
    private PolylineOptions rota = null;
    private LatLng origem;
    private LatLng destino;
    private GPSUtils gpsUtils;
    private GoogleApiClient mGoogleApiClient;

    LocationRequest mLocationRequest;
    LatLng latLng;
    SupportMapFragment mFragment;
    Marker currLocationMarker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_prevencao);

        //Incluindo a toolbar
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        gpsUtils = GPSUtils.getInstance();

        MapFragment mapFragment = (MapFragment) getFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        GoogleMapOptions options = new GoogleMapOptions();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

/*        if (id == R.id.btn_tracar_rota) {
            intent = new Intent(MainActivity.this,RotaActivity.class);
            startActivity(intent);
            return true;
        }else */if (id == R.id.btn_notificacao){
            intent = new Intent(MapActivity.this,NotificacaoActivity.class);
            startActivity(intent);
        }else if (id == R.id.btn_call){
            String celular = saveSharedPreferences.getKeeperNumber(getContext());
            intent = new Intent(Intent.ACTION_CALL);
            intent.setData(Uri.parse("tel:"+celular));
            startActivity(intent);
        }else if (id == R.id.btn_favoritos){
            Intent intent = new Intent(this, FavoritosActivity.class);
            startActivity(intent);
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction t = fm.beginTransaction();

        if (id == R.id.nav_account) {
            intent = new Intent(MapActivity.this,AlterarContaActivity.class);
            startActivity(intent);
        } if (id == R.id.nav_favoritos) {
            intent = new Intent(MapActivity.this, FavoritosActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_keeper) {
            intent = new Intent(MapActivity.this,KeeperActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_prevencao) {
            if (getActivity(this) == this) {
                Toast("Já está na tela de Map");
            }
/*        } else if (id == R.id.nav_prevencao) {
            PrevencaoFragment f = new PrevencaoFragment();
            t.replace(R.id.layoutFrag, f, "PrevencaoFragment");
        } else if (id == R.id.nav_share) {
                // Fetch and store ShareActionProvider
                mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(item);
                Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
                sharingIntent.setType("text/plain");
                String shareBody = "www.app.com.br";
                sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Compartilhe o app!");
                sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
                startActivity(Intent.createChooser(sharingIntent, "Share via"));
                ConfiguracaoFragment f = new ConfiguracaoFragment();*/
        } else if (id == R.id.nav_configuracao) {
            Intent intent = new Intent(this, ConfiguracoesActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_logout) {
            SaveSharedPreferences.clearLoginPreferences(this);
            intent = new Intent(MapActivity.this,NewLoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);

        }
        t.addToBackStack(null);
        t.commit();

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        }else {
            super.onBackPressed();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        status = false;
    }

    @Override
    public void onStart() {
        super.onStart();
        status = true;
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        gpsUtils.stopLocationUpdates();
        //Cancela os agendamentos do handler
        handler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        googleMap.setOnCameraChangeListener(this);
        googleMap.setOnMapClickListener(this);
        googleMap.setOnMyLocationButtonClickListener(this);
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {

    }

    @Override
    public void onMapClick(LatLng latLng) {

    }

    @Override
    public boolean onMyLocationButtonClick() {
        return false;
    }
}

Follows XML:

<?xml version="1.0" encoding="utf-8"?>

<android.support.v4.widget.DrawerLayout 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:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start"
    android:background="@drawable/fundo">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <include
            layout="@layout/app_bar_main"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <android.support.design.widget.CoordinatorLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">


            <fragment
                android:id="@+id/map"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                class="com.google.android.gms.maps.SupportMapFragment" />


            <EditText
                android:id="@+id/rota_edt_quer_cia"
                android:layout_width="250dp"
                android:layout_height="34dp"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:layout_marginLeft="18dp"
                android:layout_marginTop="14dp"
                android:hint="@string/edt_Map_rota"
                android:textColor="@android:color/black"
                android:background="@android:color/white"/>

        </android.support.design.widget.CoordinatorLayout>
    </LinearLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer"/>

</android.support.v4.widget.DrawerLayout>

1 answer

1


In XML is SupportMapFragment and in your class is MapFragment.

In place of:

MapFragment mapFragment = (MapFragment) getFragmentManager()
                .findFragmentById(R.id.map);

Use:

SupportMapFragment mapFragment = (SupportMapFragment) ... 

See more details in the documentation.

  • really didn’t realize, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.