Android谷歌地图空指针异常

时间:2014-11-26 07:43:07

标签: java android

最初我的应用程序中的地图运行得很好,但几周之后我再次检查出来,然后我收到了这个错误。我尝试了一切,到处寻找解决方案,但问题没有得到解决。

错误

11-26 20:07:56.975: E/AndroidRuntime(3708): FATAL EXCEPTION: main
11-26 20:07:56.975: E/AndroidRuntime(3708): Process: com.ntec_app, PID: 3708
11-26 20:07:56.975: E/AndroidRuntime(3708): java.lang.NullPointerException
11-26 20:07:56.975: E/AndroidRuntime(3708):     at com.ntec_app.Directionactivity.setUpMap(Directionactivity.java:109)
11-26 20:07:56.975: E/AndroidRuntime(3708):     at com.ntec_app.Directionactivity.setUpMapifNeeded(Directionactivity.java:82)
11-26 20:07:56.975: E/AndroidRuntime(3708):     at com.ntec_app.Directionactivity.onViewCreated(Directionactivity.java:64)
11-26 20:07:56.975: E/AndroidRuntime(3708):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:956)
11-26 20:07:56.975: E/AndroidRuntime(3708):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1121)
11-26 20:07:56.975: E/AndroidRuntime(3708):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
11-26 20:07:56.975: E/AndroidRuntime(3708):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1484)
11-26 20:07:56.975: E/AndroidRuntime(3708):     at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:450)
11-26 20:07:56.975: E/AndroidRuntime(3708):     at android.os.Handler.handleCallback(Handler.java:733)
11-26 20:07:56.975: E/AndroidRuntime(3708):     at android.os.Handler.dispatchMessage(Handler.java:95)
11-26 20:07:56.975: E/AndroidRuntime(3708):     at android.os.Looper.loop(Looper.java:157)
11-26 20:07:56.975: E/AndroidRuntime(3708):     at android.app.ActivityThread.main(ActivityThread.java:5506)
11-26 20:07:56.975: E/AndroidRuntime(3708):     at java.lang.reflect.Method.invokeNative(Native Method)
11-26 20:07:56.975: E/AndroidRuntime(3708):     at java.lang.reflect.Method.invoke(Method.java:515)
11-26 20:07:56.975: E/AndroidRuntime(3708):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
11-26 20:07:56.975: E/AndroidRuntime(3708):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
11-26 20:07:56.975: E/AndroidRuntime(3708):     at dalvik.system.NativeStart.main(Native Method)

JAVA文件

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
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 android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

/**
 * A simple {@link Fragment} subclass.
 * 
 */
public class Directionactivity extends Fragment implements OnInfoWindowClickListener {


    public static final String TAG = Directionactivity.class.getSimpleName();
     GoogleMap googlemap;
    MapView mv;
    Marker auckland,hasting,tauranga,cht;

    public Directionactivity() {
        // Required empty public constructor
    }

    public static Directionactivity newInstance() {
        // TODO Auto-generated method stub
        return new Directionactivity();
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v= inflater.inflate(R.layout.activity_direction, container, false);
        //setUpMapifNeeded();
        return v;
    }

    @Override
    public void onViewCreated(View view,  Bundle savedInstanceState)  {
        // TODO Auto-generated method stub
        super.onViewCreated(view, savedInstanceState);

            setUpMapifNeeded();

com.ntec_app.Directionactivity.onViewCreated(Directionactivity.java:64)

}

    private void setUpMapifNeeded() {
        // TODO Auto-generated method stub

            if(googlemap==null)
            {
                // try to get map from google services
                //googlemap=((SupportMapFragment).getSupportFragmentManager).findFragmentById(R.id.map)).getMap(); 
            googlemap = ((SupportMapFragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

            //GoogleMap.getUiSettings().setIndoorLevelPickerEnabled(boolean);
            }
            if(googlemap!=null)
            {
                // create map manually
                setUpMap();

com.ntec_app.Directionactivity.setUpMapifNeeded(Directionactivity.java:82)

            }



    }

    private void setUpMap() {
        // TODO Auto-generated method stub

        // enable my location
        googlemap.setMyLocationEnabled(true);
        googlemap.setBuildingsEnabled(true);
        // get location manager object from system services LOCATION_MANAGER
        LocationManager locationmanager=(LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);

        //create a criterie object to retirive provider
        Criteria criteria=new Criteria();

        String provider=locationmanager.getBestProvider(criteria, true);

        Location mylocation=locationmanager.getLastKnownLocation(provider);

    //googlemap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
        googlemap.setMapType(GoogleMap.MAP_TYPE_HYBRID);


        double latitude=mylocation.getLatitude();

        double longitude=mylocation.getLongitude();

        LatLng latlng=new LatLng(latitude, longitude);
        LatLng ack=new LatLng(-36.845432,174.763113);
        LatLng htg=new LatLng(-39.641638,176.850449);
        LatLng tag=new LatLng(-37.686336,176.167189);
        LatLng christ=new LatLng(-43.535969,172.541321);

        googlemap.moveCamera(CameraUpdateFactory.newLatLng(latlng));

        googlemap.moveCamera(CameraUpdateFactory.zoomTo(14));

        googlemap.getUiSettings().setZoomControlsEnabled(true);

        googlemap.getUiSettings().setScrollGesturesEnabled(true);

        googlemap.getUiSettings().setIndoorLevelPickerEnabled(true);

        googlemap.getUiSettings().setTiltGesturesEnabled(true);

        // to rotate the map
        googlemap.getUiSettings().setAllGesturesEnabled(true);

        // marker for my current locations
       googlemap.addMarker(new MarkerOptions().position(latlng).title("You are here").snippet(latlng.toString()).draggable(false));

        // setting Ntec hobson street marker
        auckland=googlemap.addMarker(new MarkerOptions().position(ack).title("HEAD OFFICE AND AUCKLAND CAMPUS").snippet("Ntec Tower:20 Hobson Street P.O.Box 911-312 Auckland").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));

        hasting=googlemap.addMarker(new MarkerOptions().position(htg).title("HASTINGS CAMPUS").snippet("304-308 Ellison Road,P.O. Box 4122 Hastings").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));

        tauranga=googlemap.addMarker(new MarkerOptions().position(tag).title("TAURANGA CAMPUS").snippet("Durham Court,146 Durham St,Tauranga 3110").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));

        cht=googlemap.addMarker(new MarkerOptions().position(christ).title("CHRISTCHURCH CAMPUS").snippet("3/60 Waterloo Road,Hornby,Christchurch 8042").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));


           googlemap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {

            @Override
            public void onInfoWindowClick(Marker arg0) {
                // TODO Auto-generated method stub
                if(arg0.getTitle().equals("HEAD OFFICE AND AUCKLAND CAMPUS")) // if marker source is clicked
                {
                     String uri = String.format(Locale.ENGLISH, "http://maps.google.com/maps?&daddr=%f,%f (%s)",-36.845432,174.763113, "HEAD OFFICE AND AUCKLAND CAMPUS");
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
                        intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
                        try
                        {
                            startActivity(intent);
                        }
                        catch(ActivityNotFoundException ex)
                        {
                            try
                            {
                                Intent unrestrictedIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
                                startActivity(unrestrictedIntent);
                            }
                            catch(ActivityNotFoundException innerEx)
                            {
                            }}
                }
                if(arg0.getTitle().equals("HASTINGS CAMPUS"))
                {
                     String uri = String.format(Locale.ENGLISH, "http://maps.google.com/maps?&daddr=%f,%f (%s)",-39.641638,176.850449, "HASTINGS CAMPUS");
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
                        intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
                        try
                        {
                            startActivity(intent);
                        }
                        catch(ActivityNotFoundException ex)
                        {
                            try
                            {
                                Intent unrestrictedIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
                                startActivity(unrestrictedIntent);
                            }
                            catch(ActivityNotFoundException innerEx)
                            {
                            }}
                }

                if(arg0.getTitle().equals("TAURANGA CAMPUS"))
                {
                        String uri = String.format(Locale.ENGLISH, "http://maps.google.com/maps?&daddr=%f,%f (%s)",-37.686336,176.167189, "TAURANGA CAMPUS");
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
                        intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
                        try
                        {
                            startActivity(intent);
                        }
                        catch(ActivityNotFoundException ex)
                        {
                            try
                            {
                                Intent unrestrictedIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
                                startActivity(unrestrictedIntent);
                            }
                            catch(ActivityNotFoundException innerEx)
                            {
                            }}
                }
                if(arg0.getTitle().equals("CHRISTCHURCH CAMPUS"))
                {
                        String uri = String.format(Locale.ENGLISH, "http://maps.google.com/maps?&daddr=%f,%f (%s)",-43.535969,172.541321, "CHRISTCHURCH CAMPUS");
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
                        intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
                        try
                        {
                            startActivity(intent);
                        }
                        catch(ActivityNotFoundException ex)
                        {
                            try
                            {
                                Intent unrestrictedIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
                                startActivity(unrestrictedIntent);
                            }
                            catch(ActivityNotFoundException innerEx)
                            {
                            }}
                        }
                }
           });      

         CameraPosition cameraPosition = new CameraPosition.Builder()
        .target(latlng)      // Sets the center of the map to Mountain View
        .bearing(90)                // Sets the orientation of the camera to east
        .tilt(15)                   // Sets the tilt of the camera to 30 degrees
        .build();                   // Creates a CameraPosition from the builder
        googlemap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
    }

    @Override
    public void onInfoWindowClick(Marker arg0) {
    }
}

XML文件

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:map="http://schemas.android.com/apk/res-auto"
  android:id="@+id/map"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  class="com.google.android.gms.maps.SupportMapFragment"
  map:cameraTargetLat="-33.796923"
  map:cameraTargetLng="150.922433"
  map:cameraTilt="30"
  map:cameraZoom="13"
  map:mapType="normal"
  map:uiCompass="false"
  map:uiRotateGestures="true"
  map:uiScrollGestures="false"
  map:uiTiltGestures="true"
  map:uiZoomControls="false"
  map:uiZoomGestures="true"/>

1 个答案:

答案 0 :(得分:0)

getLastKnownLocation如果没有好的最后位置,则可以返回null。在使用之前,您应该检查以确保mylocation不为空。

Location mylocation=locationmanager.getLastKnownLocation(provider);  
if(mylocation != null) {
     // other code related using mylocation...
 }
相关问题