位置出现 NullPointerException

NullPointerException in location

我的 Android 应用程序中的位置变量有问题。在此屏幕上 GPSLocation 工作正常,但是当我将屏幕更改为 gpsLocation.getLastKnownLocation() 时,此方法始终 returns null.

第一个屏幕:

public class MainActivity extends ActionBarActivity {
private TextView text;
private GPSLocation gpsLocation;
private Location targetLocation;
private EditText editLatitude;
private EditText editLongitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    text = (TextView)findViewById(R.id.textView);
    gpsLocation = new GPSLocation(this);
    editLatitude = (EditText)findViewById(R.id.editDlugosc);
    editLongitude = (EditText)findViewById(R.id.editSzerokosc);
    targetLocation = new Location("Bosch");
}




@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_main, 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);
}

public void click_rozpocznij(View view) {
    targetLocation=gpsLocation.getLastKnownLocation();
    text.setText("Your location: \n" + gpsLocation.getLatitude() + "\n" + gpsLocation.getLongitude());
}
public void click_end(View view)
{
    gpsLocation.stopUsingGPS();
    text.setText("Your location:");
}

public void click_pointer(View view) {
    if(targetLocation !=null) {
        Intent nextScreen = new Intent(getApplicationContext(), Pointer.class);
        nextScreen.putExtra("location", targetLocation);
        startActivity(nextScreen);
    }
    else
    {

        targetLocation.setLongitude(0);
        targetLocation.setLatitude(0);
        Intent nextScreen = new Intent(getApplicationContext(), Pointer.class);
        nextScreen.putExtra("location", targetLocation);
        startActivity(nextScreen);
    }

}

public void click_show(View view) {
    gpsLocation.getLastKnownLocation();
    text.setText("Your location: \n" + gpsLocation.getLatitude() + "\n" + gpsLocation.getLongitude());
}

public void click_SaveTarget(View view) {
    if(targetLocation !=null)
    {
        try{
            targetLocation.setLatitude(Double.parseDouble(editLatitude.getText().toString()));
            targetLocation.setLongitude(Double.parseDouble(editLongitude.getText().toString()));
        }
        catch(Exception e)
        {
            targetLocation.setLatitude(0);
            targetLocation.setLongitude(0);
            editLatitude.setText("0");
            editLongitude.setText("0");
        }

    }

}

第二个屏幕:

public class Pointer extends ActionBarActivity implements SensorEventListener{
private Location cel;
private TextView textLocation;
private TextView textDistance;
private TextView textAngle;
private TextView textAccuracy;
private ImageView obrazek;
private SensorManager sensorManager;
private float[] lastCompass= new float[3];
private float[] lastAccelero = new float[3];
private float[] orientation = new float[3];
private boolean lastCompassSet = false;
private boolean lastAcceleroSet = false;
private float[] rotation = new float[9];
private float degree = 0f;
private Sensor compass;
private Sensor accelerometer;
private GPSLocation gpsLocation;
private Location locationFirst;
private Location locationNow;
private GeomagneticField magneticField;
private float azimuthDegress;
private float azimuthCel;
private Long timeStart;
private Long timeEnd;
private void sprawdzPolozenie()
{

    if (gpsLocation.location.distanceTo(locationFirst) > 10000)
    {
        magneticField = new GeomagneticField(Double.valueOf(gpsLocation.getLatitude()).floatValue(),Double.valueOf(gpsLocation.getLongitude()).floatValue(),Double.valueOf(gpsLocation.getAltitude()).floatValue(),System.currentTimeMillis());
        locationFirst = gpsLocation.getLastKnownLocation();
    }
    SensorManager.getRotationMatrix(rotation,null,lastAccelero,lastCompass);
    SensorManager.getOrientation(rotation,orientation);
    float azimuthRadians = orientation[0];
    azimuthDegress = (float)(Math.toDegrees(azimuthRadians));
    azimuthDegress += magneticField.getDeclination();
    azimuthCel= locationNow.bearingTo(cel);
    azimuthDegress=azimuthDegress-azimuthCel;
    RotateAnimation ra = new RotateAnimation(degree,-azimuthDegress, Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
    ra.setDuration(400);
    ra.setFillAfter(true);
    obrazek.startAnimation(ra);
    degree=-azimuthDegress;

}
@Override
public void onSensorChanged(SensorEvent event) {

    locationNow=gpsLocation.getLastKnownLocation();
    if(locationNow!=null) {
        if (event.sensor == compass) {
        /*event.values[0]=lastCompass[0];
        event.values[1]=lastCompass[1];
        event.values[2]=lastCompass[2];*/
            System.arraycopy(event.values, 0, lastCompass, 0, event.values.length);

            lastCompassSet = true;
        } else if (event.sensor == accelerometer) {
        /*event.values[0]=lastAccelero[0];
        event.values[1]=lastAccelero[1];
        event.values[2]=lastAccelero[2];*/
            System.arraycopy(event.values, 0, lastAccelero, 0, event.values.length);
            lastAcceleroSet = true;
        }
        if (lastCompassSet) {
            timeStart = System.currentTimeMillis();
            if (timeStart > timeEnd + 500) {
                sprawdzPolozenie();
                timeEnd = timeStart;
            }

        }
        textDistance.setText("Distanse: " + locationNow.distanceTo(cel));
        textAccuracy.setText("Accuracy: " + locationNow.getAccuracy());
        textAngle.setText("Angle: " + azimuthDegress);
    }
}
@Override
protected void onResume() {
    super.onResume();
    sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME);
    sensorManager.registerListener(this, compass, SensorManager.SENSOR_DELAY_GAME);
}

@Override
protected void onPause(){
    super.onPause();
    sensorManager.unregisterListener(this,accelerometer);
    sensorManager.unregisterListener(this,compass);

}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    gpsLocation = new GPSLocation(this);
    locationFirst = new Location("Bosch");
    locationNow = new Location("Bosch");
    cel = new Location("Bosch");
    locationNow=gpsLocation.getLastKnownLocation();
    locationFirst= gpsLocation.getLastKnownLocation();
    setContentView(R.layout.activity_wskaznik);
    timeEnd =System.currentTimeMillis();
    sensorManager = (SensorManager)this.getSystemService(Context.SENSOR_SERVICE);
    compass = sensorManager.getDefaultSensor(TYPE_MAGNETIC_FIELD);
    accelerometer = sensorManager.getDefaultSensor(TYPE_ACCELEROMETER);
    obrazek =(ImageView)findViewById(R.id.wskaznik_imageView);
    textLocation = (TextView)findViewById(R.id.wskaznikTekstCel);
    textDistance = (TextView)findViewById(R.id.wskaznikTekstOdleglosc);
    textAngle = (TextView)findViewById(R.id.wskaznikTekstKat);
    textAccuracy =(TextView)findViewById(R.id.wskaznikTekstDokladnosc);
    Bundle extras = getIntent().getExtras();
    magneticField = new GeomagneticField(Double.valueOf(gpsLocation.getLatitude()).floatValue(),Double.valueOf(gpsLocation.getLongitude()).floatValue(),Double.valueOf(gpsLocation.getAltitude()).floatValue(),System.currentTimeMillis());
    if(extras!=null)
    {
        cel = (Location)extras.get("location");
    }
    textLocation.setText(cel.getLatitude() + "," + cel.getLongitude());
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}

public void click_wroc(View view) {
    finish();

}

GPSLocation 本身:

public class GPSLocation extends Service implements LocationListener {

private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
public boolean canGetLocation = false;
//czas i dystans pomiedzy pomiarami
private static final long MIN_DISTANCE = 10;
private static final long MIN_TIME = 1000 * 60 * 1;
double latitude;
double longitude;
double altitude;
public Location location;
protected LocationManager locationManager;

public GPSLocation(Context context)
{
    this.mContext = context;
    getLocation();
}
public void requestLocation() {
    //network
    if (isNetworkEnabled)
    {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
        if (locationManager != null) {
            location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }
        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            altitude = location.getAltitude();
        }

    }
    //gps
    if(isGPSEnabled)
    {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
        if(locationManager != null)
        {
            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        }
        if(location!=null)
        {
            latitude=location.getLatitude();
            longitude=location.getLongitude();
            altitude = location.getAltitude();
        }

    }
}
public Location getLastKnownLocation()
{
    try
    {
        isGPSEnabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if(!isGPSEnabled && !isNetworkEnabled)
        {
            this.canGetLocation=false;
            this.showSettingsAlert();
        }
        else
        {
            requestLocation();
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    return location;
}
public Location getLocation()
{
    try
    {
        locationManager=(LocationManager)mContext.getSystemService(LOCATION_SERVICE);
        isGPSEnabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if(!isGPSEnabled && !isNetworkEnabled)
        {
            this.canGetLocation=false;
            this.showSettingsAlert();
        }
        else
        {
            this.canGetLocation=true;
            requestLocation();

        }

    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    return location;
}
public double getLatitude()
{
    if(location!=null)
    {
        latitude = location.getLatitude();
    }
    return latitude;
}
public double getLongitude()
{
    if(location!=null)
    {
        latitude = location.getLatitude();
    }
    return longitude;
}
public double getAltitude(){
    if(location!=null)
    {
        latitude=location.getAltitude();
    }
    return altitude;
}
public void showSettingsAlert()
{
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
    alertDialog.setTitle("Przejdź do ustawień");
    alertDialog.setMessage("Lokalizacja wyłączona");
    // On pressing Settings button
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
        }
    });

    // on pressing cancel button
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });
    alertDialog.show();
}
public void stopUsingGPS()
{
    if(locationManager!=null)
    {
        locationManager.removeUpdates(GPSLocation.this);
    }
}
@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) {

}

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

我 运行 你的 Pointer Activity 代码是孤立的,它对我来说工作得很好。

看来您的主要问题是如何将 Location 通过 Intent 传递到 Pointer Activity 从 MainActivity

Location 实现了 Parcelable,因此您可以像您已经在做的那样通过 Intent 传递它,并像这样检索它:

if(extras!=null)
{
    //cel = (Location)extras.get("location"); //this is not correct
    cel = (Location) extras.getParcelable("location");

}
if (cel != null){
    textLocation.setText(cel.getLatitude() + "," + cel.getLongitude());
}

文档:http://developer.android.com/reference/android/os/Bundle.html#getParcelable(java.lang.String)

http://developer.android.com/reference/android/location/Location.html

对所有想帮助我解决问题的人表示抱歉。我自己解决了这个问题。 问题出在 GPSLocation class。我必须在开始时添加新的构造函数并更改从 locationManager

获取位置的方式
public GPSLocation(Context context)
{
    this.mContext = context;
    location = new Location("Bosch");
    getLocation();
}

当我使用此代码位置时保持空指针。 location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 但是从 locationManager 创建位置副本解决了问题。 location = new Location(locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)); 也许 locationManager 正在创建位置数据而不是 Location 本身,这导致创建了空指针。