在空对象引用上加倍android.location.Location.getLatitude()'

时间:2017-03-29 14:20:26

标签: android google-maps

我再次问这个问题的唯一原因是,因为我已经尝试了所有的答案而且它不适合我,我正在尝试获取当前的用户位置,但它不起作用所以这就是我一直以来尝试做,顺便说一句,我已经设置了所有权限,我继续得到双重android的location.getlatitude空对象引用错误和致命的execption主,pleaaase帮助我 这是我的GPSTRACKER Java类代码:

package com.example.nefissa.androidtest;

 import android.*;
 import android.Manifest;
 import android.app.Service;
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.PackageManager;
 import android.location.Location;
 import android.location.LocationListener;
 import android.location.LocationManager;
 import android.os.Bundle;
 import android.os.IBinder;
 import android.support.annotation.Nullable;
 import android.support.v4.content.ContextCompat;


public class GPSTracker extends Service implements LocationListener{

private final Context context;

boolean isGPSEnabled =false;
boolean isNetworkEnabled =false;
boolean canGetLocation =false;

Location location;
protected LocationManager locationManager;



  public GPSTracker(Context context){
   this.context=context;
  }

// create a GetLocation Method //

public Location getLocation(){

    try{
        locationManager=(LocationManager) context.getSystemService(LOCATION_SERVICE);
        isGPSEnabled = locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);
        isNetworkEnabled=locationManager.isProviderEnabled(locationManager.NETWORK_PROVIDER);

        if(ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
        || ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED ){


            if(isGPSEnabled){
                if(location==null){
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,100000,10,this);
                    if(locationManager!=null){
                          location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    }
                  }
            }
               // if location is not found from GPS then it will found from network //
            if(location==null){
                if(isNetworkEnabled){
                           locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,100000,10,this);
                        if(locationManager!=null){
                              location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        }
                    }

            }
        }

    }catch(Exception e){

    }
    return location;
}




@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onLocationChanged(Location location) {

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}
}

和我的主要活动代码:

package com.example.nefissa.androidtest;

 import android.location.Location;
 import android.support.v4.app.FragmentActivity;
  import android.os.Bundle;

 import com.google.android.gms.maps.CameraUpdateFactory;
 import com.google.android.gms.maps.GoogleMap;
  import com.google.android.gms.maps.OnMapReadyCallback;
   import com.google.android.gms.maps.SupportMapFragment;
   import com.google.android.gms.maps.model.LatLng;
 import com.google.android.gms.maps.model.MarkerOptions;

 public class MapsActivity extends FragmentActivity implements     OnMapReadyCallback {

private GoogleMap mMap;
private GPSTracker gpsTracker;
private Location mLocation;
double latitude;
double longitude;


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

    gpsTracker= new GPSTracker(getApplicationContext());
    mLocation=gpsTracker.getLocation();
    latitude= mLocation.getLatitude();
    longitude= mLocation.getLongitude();


    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}


/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(latitude,longitude);
    mMap.addMarker(new MarkerOptions().position(sydney).title("you are here"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
  }
 }

2 个答案:

答案 0 :(得分:0)

调用onMapReady后,最好初始化gpsTracker。

   gpsTracker= new GPSTracker(getApplicationContext());

   if(gpsTracker!=null){
       mLocation=gpsTracker.getLocation();
       latitude= mLocation.getLatitude();
       longitude= mLocation.getLongitude();
   }

我认为gpsTracker.getLocation必须改为逻辑。 请阅读android gps指南。

答案 1 :(得分:-1)

尝试使用

GPS追踪器

//
gps = new GPSTracker(SignUpActivity.this);
        if (gps.canGetLocation) {
            lat = String.valueOf(gps.getLatitude());
            lng = String.valueOf(gps.getLongitude());
        }

也来自活动呼叫

的onCreate

class Program
{
    static void Main(string[] args)
    {
        XDocument gbConfig = XDocument.Parse(@"<TradingBlocConfiguration>
                                             <GreatBritain xmlns=""GB"">
                                               <Country/>
                                               <Countries>
                                                  <Country/>
                                                  <Country/>                                                                        
                                                </Countries>
                                              </GreatBritain>                                                                     </TradingBlocConfiguration>");


        XDocument euConfig = XDocument.Parse(@"<TradingBlocConfiguration>
                                             <EuropeanUnion xmlns=""EU"">
                                               <Country/>
                                               <Countries>
                                                  <Country/>
                                                  <Country/>                                                                        
                                                </Countries>
                                              </EuropeanUnion>                                                                     </TradingBlocConfiguration>");

        var greatBritainConfiguration = BuildConfig<TradingBlocConfiguration>(gbConfig);

        // A single 'Country' is always deserialized correctly..
        Console.WriteLine("Great Britain Country Type   " + greatBritainConfiguration.TradingBlocConfig.MemberCountry.GetType());

        // A List of 'Country' is deserialized to the wrong type, depending on what '[XmlElement]' tag is listed first.
        Console.WriteLine("Great Britain Countries Type " + greatBritainConfiguration.TradingBlocConfig.MemberCountries[0].GetType());

        var euConfiguration = BuildConfig<TradingBlocConfiguration>(euConfig);
        Console.WriteLine("EU Country Type              " + euConfiguration.TradingBlocConfig.MemberCountry.GetType());
        Console.WriteLine("EU Countries Type            " + euConfiguration.TradingBlocConfig.MemberCountries[0].GetType());

        Console.ReadLine();
    }

    private static T BuildConfig<T>(XDocument doc) where T : class
    {
        var stream = new MemoryStream();
        doc.Save(stream);

        T result;
        using (var reader = new StreamReader(stream))
        {
            stream.Position = 0;
            var xs = new XmlSerializer(typeof(T), new Type[] { typeof(GB.GreatBritain.Country) });
            result = (T)xs.Deserialize(reader);
        }

        return result;
    }
}

[XmlRoot("TradingBlocConfiguration")]
public sealed class TradingBlocConfiguration
{
    [XmlElement("GreatBritain", typeof(GB.GreatBritain), Namespace = "GB")]
    [XmlElement("EuropeanUnion", typeof(EU.EuropeanUnion), Namespace = "EU")]
    public TradingBloc TradingBlocConfig { get; set; }
}

[XmlRoot]
[XmlInclude(typeof(GB.GreatBritain))]
[XmlInclude(typeof(EU.EuropeanUnion))]
public class BaseCountry { }

public abstract class TradingBloc
{
    [XmlIgnore]
    public abstract List<BaseCountry> MemberCountries { get; set; }

    [XmlIgnore]
    public abstract BaseCountry MemberCountry { get; set; }
}

namespace GB
{
    [XmlRoot("GreatBritain")]
    public class GreatBritain : TradingBloc
    {
        [XmlElement("Country", typeof(Country))]
        public override BaseCountry MemberCountry { get; set; }

        [XmlArray("Countries")]
        [XmlArrayItem("Country", typeof(Country))]

        public override List<BaseCountry> MemberCountries { get; set; }

        [XmlRoot(Namespace = "GB")]
        public class Country : BaseCountry { }
    }
}

namespace EU
{
    [XmlRoot("EuropeanUnion")]
    public class EuropeanUnion : TradingBloc
    {
        [XmlElement("Country", typeof(Country))]
        public override BaseCountry MemberCountry { get; set; }

        [XmlArray("Countries")]
        [XmlArrayItem("Country", typeof(Country))]
        public override List<BaseCountry> MemberCountries { get; set; }

        [XmlRoot(Namespace = "EU")]
        public class Country : BaseCountry { }
    }
}

如果您仍然遇到问题,请在下方发表评论