2015-04-12 56 views
0

我的Android應用程序中的Location變量存在問題。在這個屏幕上GPSLocation工作正常,但是當我將屏幕更改爲gpsLocation.getLastKnownLocation()時,此方法始終返回null。位置中的NullPointerException

第一屏:

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; 
} 
+0

@Tomek我們不會調試你的代碼 –

+0

我知道我只是不知道爲什麼這不起作用,兩個活動中的功能相同。我想有人可以幫助我。 –

回答

0

我跑你Pointer活動代碼隔離,這對我來說工作得很好。

它看起來像你的主要問題是你如何通過Location通過IntentPointer活動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

0

索裏爲大家誰想要幫助我解決問題。我自己解決了這個問題。 問題出在GPSLocation類中。我不得不在開始添加新的構造函數和的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正在創建位置數據,而不是位置本身,這導致了創建空指針。

相關問題