Question

I'm facing a new problem with the GoogleMap use. After putting in place a NavigationDrawer, I created a new Fragment for GoogleMap, which is called from the Drawer menu.

I did implement the KeyDown procedure to switch the Map view type from Hybrid to Normal, and vice versa, using the volume buttons.

So when I click on these latters to switch, the application crash, even on my smartphone.

Do you have please any idea about this kind of problem.

Best regards.

logcat :

    04-24 10:52:47.101: I/dalvikvm(627): threadid=3: reacting to signal 3
04-24 10:52:47.161: I/dalvikvm(627): Wrote stack traces to '/data/anr/traces.txt'
04-24 10:52:47.311: D/libEGL(627): loaded /system/lib/egl/libGLES_android.so
04-24 10:52:47.321: I/dalvikvm(627): threadid=3: reacting to signal 3
04-24 10:52:47.391: D/libEGL(627): loaded /system/lib/egl/libEGL_emulation.so
04-24 10:52:47.401: D/(627): HostConnection::get() New Host Connection established 0x13a9f8, tid 627
04-24 10:52:47.401: I/dalvikvm(627): Wrote stack traces to '/data/anr/traces.txt'
04-24 10:52:47.413: D/libEGL(627): loaded /system/lib/egl/libGLESv1_CM_emulation.so
04-24 10:52:47.413: D/libEGL(627): loaded /system/lib/egl/libGLESv2_emulation.so
04-24 10:52:47.642: W/EGL_emulation(627): eglSurfaceAttrib not implemented
04-24 10:52:47.661: D/OpenGLRenderer(627): Enabling debug mode 0
04-24 10:52:47.946: I/dalvikvm(627): threadid=3: reacting to signal 3
04-24 10:52:47.951: I/dalvikvm(627): Wrote stack traces to '/data/anr/traces.txt'
04-24 10:52:48.281: I/dalvikvm(627): threadid=3: reacting to signal 3
04-24 10:52:48.321: I/dalvikvm(627): Wrote stack traces to '/data/anr/traces.txt'
04-24 10:53:04.621: W/GooglePlayServicesUtil(627): Google Play services is missing.
04-24 10:53:04.631: W/GooglePlayServicesUtil(627): Google Play services is missing.
04-24 10:53:04.631: W/GooglePlayServicesUtil(627): Google Play services is missing.
04-24 10:53:04.641: W/GooglePlayServicesUtil(627): Google Play services is missing.
04-24 10:53:04.651: W/GooglePlayServicesUtil(627): Google Play services is missing.
04-24 10:53:04.661: W/GooglePlayServicesUtil(627): Google Play services is missing.
04-24 10:53:04.671: W/GooglePlayServicesUtil(627): Google Play services is missing.
04-24 10:53:04.671: W/GooglePlayServicesUtil(627): Google Play services is missing.
04-24 10:53:04.681: W/GooglePlayServicesUtil(627): Google Play services is missing.
04-24 10:53:04.701: W/GooglePlayServicesUtil(627): Google Play services is missing.
04-24 10:53:04.711: W/GooglePlayServicesUtil(627): Google Play services is missing.
04-24 10:53:04.721: W/GooglePlayServicesUtil(627): Google Play services is missing.
04-24 10:53:04.732: W/GooglePlayServicesUtil(627): Google Play services is missing.
04-24 10:53:04.732: W/System.err(627): java.lang.NullPointerException
04-24 10:53:04.741: W/System.err(627):  at app.track.map.MainActivity$GoogleMapFragment.initilizeMap(MainActivity.java:258)
04-24 10:53:04.741: W/System.err(627):  at app.track.map.MainActivity$GoogleMapFragment.onCreateView(MainActivity.java:241)
04-24 10:53:04.741: W/System.err(627):  at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:828)
04-24 10:53:04.741: W/System.err(627):  at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1032)
04-24 10:53:04.751: W/System.err(627):  at android.app.BackStackRecord.run(BackStackRecord.java:622)
04-24 10:53:04.751: W/System.err(627):  at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1382)
04-24 10:53:04.751: W/System.err(627):  at android.app.FragmentManagerImpl$1.run(FragmentManager.java:426)
04-24 10:53:04.751: W/System.err(627):  at android.os.Handler.handleCallback(Handler.java:605)
04-24 10:53:04.751: W/System.err(627):  at android.os.Handler.dispatchMessage(Handler.java:92)
04-24 10:53:04.751: W/System.err(627):  at android.os.Looper.loop(Looper.java:137)
04-24 10:53:04.751: W/System.err(627):  at android.app.ActivityThread.main(ActivityThread.java:4424)
04-24 10:53:04.761: W/System.err(627):  at java.lang.reflect.Method.invokeNative(Native Method)
04-24 10:53:04.761: W/System.err(627):  at java.lang.reflect.Method.invoke(Method.java:511)
04-24 10:53:04.761: W/System.err(627):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-24 10:53:04.761: W/System.err(627):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-24 10:53:04.771: W/System.err(627):  at dalvik.system.NativeStart.main(Native Method)
04-24 10:53:07.231: D/AndroidRuntime(627): Shutting down VM
04-24 10:53:07.231: W/dalvikvm(627): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
04-24 10:53:07.331: E/AndroidRuntime(627): FATAL EXCEPTION: main
04-24 10:53:07.331: E/AndroidRuntime(627): java.lang.NullPointerException
04-24 10:53:07.331: E/AndroidRuntime(627):  at app.track.map.MainActivity.onKeyDown(MainActivity.java:219)
04-24 10:53:07.331: E/AndroidRuntime(627):  at android.view.KeyEvent.dispatch(KeyEvent.java:2551)
04-24 10:53:07.331: E/AndroidRuntime(627):  at android.app.Activity.dispatchKeyEvent(Activity.java:2329)
04-24 10:53:07.331: E/AndroidRuntime(627):  at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1806)
04-24 10:53:07.331: E/AndroidRuntime(627):  at android.view.ViewRootImpl.deliverKeyEventPostIme(ViewRootImpl.java:3327)
04-24 10:53:07.331: E/AndroidRuntime(627):  at android.view.ViewRootImpl.handleFinishedEvent(ViewRootImpl.java:3300)
04-24 10:53:07.331: E/AndroidRuntime(627):  at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2460)
04-24 10:53:07.331: E/AndroidRuntime(627):  at android.os.Handler.dispatchMessage(Handler.java:99)
04-24 10:53:07.331: E/AndroidRuntime(627):  at android.os.Looper.loop(Looper.java:137)
04-24 10:53:07.331: E/AndroidRuntime(627):  at android.app.ActivityThread.main(ActivityThread.java:4424)
04-24 10:53:07.331: E/AndroidRuntime(627):  at java.lang.reflect.Method.invokeNative(Native Method)
04-24 10:53:07.331: E/AndroidRuntime(627):  at java.lang.reflect.Method.invoke(Method.java:511)
04-24 10:53:07.331: E/AndroidRuntime(627):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-24 10:53:07.331: E/AndroidRuntime(627):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-24 10:53:07.331: E/AndroidRuntime(627):  at dalvik.system.NativeStart.main(Native Method)
04-24 10:53:07.561: D/dalvikvm(627): GC_CONCURRENT freed 206K, 4% free 9300K/9607K, paused 4ms+6ms
04-24 10:53:07.982: I/dalvikvm(627): threadid=3: reacting to signal 3
04-24 10:53:08.011: I/dalvikvm(627): Wrote stack traces to '/data/anr/traces.txt'
04-24 10:53:09.441: I/Process(627): Sending signal. PID: 627 SIG: 9

MainActivity :

/*
 * Copyright 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package app.track.map;

import java.util.Locale;

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.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    private String[] mPlanetTitles;

    // Google Map
    private GoogleMap googleMap;
    private static String SelectedMenuPosition;

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

        mTitle = mDrawerTitle = getTitle();
        mPlanetTitles = getResources().getStringArray(R.array.drawer_array);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        // set a custom shadow that overlays the main content when the drawer opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        // set up the drawer's list view with items and click listener
        mDrawerList.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_list_item, mPlanetTitles));
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        // enable ActionBar app icon to behave as action to toggle nav drawer
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the sliding drawer and the action bar app icon
        mDrawerToggle = new ActionBarDrawerToggle(
                this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                R.drawable.ic_drawer,  /* nav drawer image to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description for accessibility */
                R.string.drawer_close  /* "close drawer" description for accessibility */
                ) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            selectItem(0);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.map, menu);
        return super.onCreateOptionsMenu(menu);
    }

    /* Called whenever we call invalidateOptionsMenu() */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // If the nav drawer is open, hide action items related to the content view
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
         // The action bar home/up action should open or close the drawer.
         // ActionBarDrawerToggle will take care of this.
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action buttons
        switch(item.getItemId()) {
        case R.id.action_websearch:
            // create intent to perform web search for this planet
            Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
            intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
            // catch event that there's no activity to handle intent
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivity(intent);
            } else {
                Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
            }
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    /* The click listner for ListView in the navigation drawer */
    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
        }
    }

    private void selectItem(int position) {
        SelectedMenuPosition = getResources().getStringArray(R.array.drawer_array)[position];
        // update the main content by replacing fragments
        if ( position == 2){
            Fragment fragment = new GoogleMapFragment();

            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            setTitle(mPlanetTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        }
        else if( position == 3){
            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            setTitle(mPlanetTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        }
        else
            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            setTitle(mPlanetTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(SelectedMenuPosition.equals("Navigate")){
            if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
                googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
                return true;
            } 
            else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
                googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

GoogleMapFragment

    public static class GoogleMapFragment extends Fragment {
        // Google Map
        private GoogleMap googleMap;

        public GoogleMapFragment() {
            // Empty constructor required for fragment subclasses
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_map, container, false);

            try {
                // Loading map
                initilizeMap();

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

            getActivity().setTitle(SelectedMenuPosition);

            return rootView;
        }

        /**
         * function to load map. If map is not created it will create it for you
         * */
        private void initilizeMap() {
            if (googleMap == null) {
                googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
                googleMap.getUiSettings().setCompassEnabled(true);
                googleMap.getUiSettings().setRotateGesturesEnabled(true);
                googleMap.getUiSettings().setMyLocationButtonEnabled(true);
                googleMap.setMyLocationEnabled(true);

                LatLng sydney = new LatLng(-33.867, 151.206);

                googleMap.setMyLocationEnabled(true);
                googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13));

                googleMap.addMarker(new MarkerOptions()
                        .title("Sydney")
                        .snippet("The most populous city in Australia.")
                        .position(sydney));

                // check if map is created successfully or not
                if (googleMap == null) {
                    //Toast.makeText(getApplicationContext(),"Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
                }
            }
        }

    }
}
Was it helpful?

Solution

You are getting NullPointer error in your onKeyDown method in which you are trying to set the type of the GoogleMap. Whereas you forget to initialize your GoogleMap in your onCreate() method that is why the app is crashing.

Just initialize your GoogleMap googleMap in your class.

OTHER TIPS

Add this in manifest

      <meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top