вызов getMap() внутри onStart() в MapFragment дает исключение nullpointerexception

Я пытаюсь реализовать Карты v2 на вкладках панели действий. Вкладка карты — это фрагмент, унаследованный от MapFragment. Приложение принудительно закрывается после нажатия на вкладку карты. Это дает исключение нулевого указателя внутри метода onStart, где был вызван getMap(). Вот код. Пожалуйста, скажите, где я не прав.

    public class MapActivity extends MapFragment implements LocationListener  {
int mNum;
GoogleMap googleMap;  


public static MapActivity newInstance() {
    MapActivity f = new MapActivity();

    // Supply num input as an argument.
    Bundle args = new Bundle();
    //args.putInt("num", num);
    //f.setArguments(args);

    return f;
}

/**
 * When creating, retrieve this instance's number from its arguments.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

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

    return v;
}


/**
 * The Fragment's UI is just a simple text view showing its
 * instance number.
 */
public void onStart(){
    super.onStart();

    googleMap=getMap();

    // Enabling MyLocation Layer of Google Map
            googleMap.setMyLocationEnabled(true);               


             getActivity();
            // Getting LocationManager object from System Service LOCATION_SERVICE
            LocationManager locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);

            // Creating a criteria object to retrieve provider
            Criteria criteria = new Criteria();

            // Getting the name of the best provider
            String provider = locationManager.getBestProvider(criteria, true);

            // Getting Current Location
            Location location = locationManager.getLastKnownLocation(provider);

            if(location!=null){
                    onLocationChanged(location);
            }

            locationManager.requestLocationUpdates(provider, 20000, 0, this);


         // Setting a click event handler for the map
            googleMap.setOnMapClickListener(new OnMapClickListener() {

                @Override
                public void onMapClick(LatLng latLng) {

                    // Creating a marker
                    MarkerOptions markerOptions = new MarkerOptions();

                    // Setting the position for the marker
                    markerOptions.position(latLng);

                    // Setting the title for the marker.
                    // This will be displayed on taping the marker
                    markerOptions.title(latLng.latitude + " : " + latLng.longitude);

                    // Clears the previously touched position
                    //googleMap.clear();

                    // Animating to the touched position
                    googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));

                    // Placing a marker on the touched position
                    googleMap.addMarker(markerOptions);
                }
            });


        }


        @Override
        public void onLocationChanged(Location location) {

            TextView tvLocation = (TextView) getActivity().findViewById(R.id.tv_location);

            // Getting latitude of the current location
            double latitude = location.getLatitude();

            // Getting longitude of the current location
            double longitude = location.getLongitude();     

            // Creating a LatLng object for the current location
            LatLng latLng = new LatLng(latitude, longitude);

            // Showing the current location in Google Map
            googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

            // Zoom in the Google Map
            googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

            // Setting latitude and longitude in the TextView tv_location
            tvLocation.setText("Latitude:" +  latitude  + ", Longitude:"+ longitude );      

        }

        @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      
        }       

}

Редактировать: я думаю, что этот код не должен быть написан в методе onStart, потому что тогда карта не отображается. Как узнать, что карта загружена, чтобы получить ее объект?


person user1961213    schedule 24.02.2013    source источник


Ответы (1)


Получение нулевой карты в OnStart означает, что API сервисов Google еще не запущен.

Часто это происходит из-за отсутствия разрешений, недопустимого ключа API Google или сервисов Google Play, которые не активированы на хост-устройстве.

Вы можете получить больше информации, опубликовав свой AndroidManifest, а также свой файл maplayout.xml.

И прежде чем запускать свою картографическую активность, следует позаботиться о значении:

GooglePlayServicesUtil.isGooglePlayServicesAvailable(anyActivity)

Что вернет указание о состоянии Google Play Services

person Thibault D.    schedule 24.02.2013
comment
Хороший призыв к необходимости проверить, установлены ли игровые сервисы, все приложения должны обрабатывать это, потому что на новом телефоне это не будет установлено. - person deepwinter; 24.04.2013