0

I've been trying to add a Nav Drawer to my app. I have this MapsActivty which is my main activity.

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

public GoogleMap mMap;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    }


@SuppressWarnings("StatementWithEmptyBody")
public void onMapSearch(View view) {
    EditText locationSearch = (EditText) findViewById(R.id.editText);
    String location = locationSearch.getText().toString();
    List<Address> addressList = null;

    if (location != null || !location.equals("")) {
        Geocoder geocoder = new Geocoder(this);
        try {
            addressList = geocoder.getFromLocationName(location, 1);

        } catch (IOException e) {
            e.printStackTrace();
        }
        Address address = addressList.get(0);
        LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
        mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
        mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
    }
}

public void onNormalMap(View view) {
    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}

public void onSatelliteMap(View view) {
    mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
}

public void onTerrainMap(View view) {
    mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
}


public void onHybridMap(View view) {
    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
}
public static double lng;
public static double lat;
@Override
public void onMapReady(final GoogleMap googleMap) {
    mMap = googleMap;

    Button btn = (Button) findViewById(R.id.button);


    btn.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            Intent intent = new Intent (v.getContext(), RegistroInfo.class);
            intent.putExtra("longitud", String.valueOf(lng));
            intent.putExtra("latitud", String.valueOf(lat));
            startActivityForResult(intent, 0);
        } });
    //View v;

    mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {

        @Override
        public void onMapLongClick(LatLng point) {
            mMap.addMarker(new MarkerOptions().position(point).title("Custom location").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
            RegistroInfo regis = new RegistroInfo();
            lng = point.longitude;
            lat = point.latitude;

        }

    });

    // Add a marker in Sydney and move the camera
    LatLng cusco = new LatLng(-13.537733, -71.903838);
    mMap.addMarker(new MarkerOptions().position(cusco).title("Cusco, Peru"));
    float zoomLevel = 16; //This goes up to 21
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(cusco, zoomLevel));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(cusco));


    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
            android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
    {
        return;
    }
    mMap.getUiSettings().setMyLocationButtonEnabled(true);
    mMap.setMyLocationEnabled(true);
    mMap.getUiSettings().setMyLocationButtonEnabled(true);
    mMap.getUiSettings().setZoomControlsEnabled(true);
    mMap.getUiSettings().setIndoorLevelPickerEnabled(true);}}
  1. NOTICE that a use extends FragmentActivityand i saw that i could use extends MenuActivity from my MenuActivity I tried this post [Same Navigation Drawer in different Activities)

  2. From my Menu Activity i have some items, which are the MapsActivity( nav_MenuPrincipal ), PerfilActivity(another activity showing information of current user) nav_perfil, NormalMap(style of map) nav_normal, SatelliteMap(style of map) nav_satellite, TerrainMap(style of map)nav_terrainmap, HybridMap(style of map)nav_hybrid

Here goes the MenuActivity

    public class MenuActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_menu);
    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);
}

@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 boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu, 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();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

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

    if (id == R.id.nav_MenuPrincipal) {
        startActivity(new Intent(this, MapsActivity.class));
        return true;
    }
    else if (id == R.id.nav_perfil) {


    }
    else if (id == R.id.nav_suggestions) {


    } else if (id == R.id.nav_normalmap) {

    } else if (id == R.id.nav_satellitemap) {

    } else if (id == R.id.nav_terrainmap) {

    } else if (id == R.id.nav_hybridmap) {


    } else if (id == R.id.nav_aboutus) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}
}
  1. Notice that I've tried this if (id == R.id.nav_MenuPrincipal) { startActivity(new Intent(this, MapsActivity.class)); return true; }, it works but not showing the menu bar.

  2. For the items called Normal, Satellite, Terrain, Hybridi just want to change the style of the map for the MapsActivity

  3. Now I'm using a LoginActivity which is already connected to a DB on a Hosting, it has the intent filter. Then i want to show my MainActivity (MapsActivity) but with that Menu (NavigationDrawer)

Thank you very much. Sorry if I'm not very clear, its my first time here

Community
  • 1
  • 1
Metapoddd
  • 1
  • 1

1 Answers1

0

here is your solution

public class MapsActivity extends AppCompatActivity implements
        OnMapReadyCallback, NavigationView.OnNavigationItemSelectedListener,
        OnClickListener {

    private GoogleMap mMap;
    private NavigationView mDrawer;
    private DrawerLayout mDrawerLayout;
    SupportMapFragment mMapFragment;
    private ActionBarDrawerToggle mDrawerToggle;
    private Button search;
    int PLACE_PICKER_REQUEST = 1;
    String placeName, address;
    private static final float ALPHA_DIM_VALUE = 0.1f;

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

        mMapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);

        try {
            manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(myIntent);
                overridePendingTransition(R.anim.push_up_in,
                        R.anim.push_up_out);
            } else {
                mMapFragment.getMapAsync(this);
                overridePendingTransition(R.anim.push_up_out,
                        R.anim.push_up_in);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        setupDrawer();

        mDrawerLayout.addDrawerListener(mDrawerToggle);
        mDrawerLayout.post(new Runnable() {
            @Override
            public void run() {
                mDrawerToggle.syncState();
            }
        });

    private void showErrorToast() {
        Toast.makeText(getApplicationContext(), getApplicationContext().getString(R.string.Toast_Error), Toast.LENGTH_SHORT).show();
    }

    private void setupDrawer() {
        assert getSupportActionBar() != null;
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        mDrawer = (NavigationView) findViewById(R.id.mNavDrawer);
        assert mDrawer != null;
        mDrawer.setNavigationItemSelectedListener(this);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.string.DrawerOpen,
                R.string.DrawerClose) {
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };

        mDrawerLayout.addDrawerListener(mDrawerToggle);
        mDrawerToggle.syncState();
    }


    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        Intent intent = null;
        if (item.getItemId() == R.id.navigation_item_1) {
            mDrawerLayout.closeDrawer(GravityCompat.START);
            intent = new Intent(this, LocationList.class);
            startActivity(intent);
            overridePendingTransition(R.anim.push_up_in,
                    R.anim.push_up_out);
            finish();
            return true;
        }
        if (item.getItemId() == R.id.navigation_item_2) {
            mDrawerLayout.closeDrawer(GravityCompat.START);
            intent = new Intent(this, MapsActivity.class);
            startActivity(intent);
            overridePendingTransition(R.anim.push_up_in,
                    R.anim.push_up_out);
            finish();
            return true;
        }
        mDrawerLayout.closeDrawers();
        return true;
    }

    @Override
    protected void onPostCreate(@Nullable Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

   @Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();
    if (mDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }
    if (id == android.R.id.home) {
        mDrawerLayout.openDrawer(GravityCompat.START);
        return true;
    }
    return super.onOptionsItemSelected(item);
  }
}

just copy reliable code.. and have any doubt about Map then ask me.. i have all your solution regarding map.

Sagar Chavada
  • 5,169
  • 7
  • 40
  • 67
  • thanks for the answer, but still have so many errors. Maybe you can help me more with the MapsActivity. There are so many libraries that maybe I'm not exporting. – Metapoddd Jul 12 '16 at 02:38
  • What library..? There is no library for map activity – Sagar Chavada Jul 12 '16 at 03:47
  • but yes.. you have to add compile 'com.google.android.gms:play-services:8.4.0' this dependency – Sagar Chavada Jul 12 '16 at 05:01
  • Well is calling me like an unimplemented methods this: `AddGeofenceFragment.AddGeofenceFragmentListener, OnShowcaseEventListener()` Also is giving me errors this: `initialize()` – Metapoddd Jul 12 '16 at 10:32
  • its seems you are pure newbie.. i m updating my answer now., just remove those things.. that is not usable for you.. i already told you just copy reliable code. – Sagar Chavada Jul 12 '16 at 10:51
  • Really is, It's my first app. :( – Metapoddd Jul 12 '16 at 11:52
  • Error `MapsActivity}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.` – Metapoddd Jul 12 '16 at 12:09
  • bcz you are already using toolbar, and in my code i m also providing you getSupportActionBar. look in my setupDrawer() method. so just remove your toolbar code.. – Sagar Chavada Jul 12 '16 at 12:16
  • What might be the toolbar code on my MapsActivity code? I couldn't found it. – Metapoddd Jul 12 '16 at 12:42
  • http://stackoverflow.com/questions/26515058/this-activity-already-has-an-action-bar-supplied-by-the-window-decor just see this link.. and try to figure out your style.xml – Sagar Chavada Jul 12 '16 at 12:48