我在尝试在空对象引用上调用虚方法NullPointerException
时获得double android.location.Location.getLatitude()
。
我正在使用解析服务器(back4app.com)。花费数小时试图找出问题可以帮到任何人。
提前谢谢
package carsharing.com.carre;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
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;
import com.parse.FindCallback;
import com.parse.ParseACL;
import com.parse.ParseException;
import com.parse.ParseGeoPoint;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import static carsharing.com.carre.R.id.map;
public class YourLocation extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
LocationManager locationManager;
String provider;
TextView information;
Location location;
Button requestRide;
Boolean requestActive = false;
Handler handler = new Handler();
ParseGeoPoint driverLocation = new ParseGeoPoint(0, 0);
Double lat;
Double lng;
String driverUsername = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_your_location);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(map);
mapFragment.getMapAsync(this);
information = (TextView) findViewById(R.id.information);
requestRide = (Button) findViewById(R.id.requestRide);
//Use the location manager and provider to determine the users location accurate to 1 meter, updated 400 miliseconds
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(new Criteria(), false);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
public void updateUserLocation(final Location location) {
lat = location.getLatitude();
lng = location.getLongitude();
mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat, lng)).title("Your location"));
mMap.animateCamera(CameraUpdateFactory
.newLatLngZoom(new LatLng(lat, lng), 10));
if (!requestActive) {
ParseQuery<ParseObject> query = new ParseQuery<>("requests");
query.whereEqualTo("riderUsername", ParseUser.getCurrentUser().getUsername());
query.findInBackground(new FindCallback<ParseObject>() {
@Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
if (objects.size() > 0) {
for (ParseObject object : objects) {
requestActive = true;
information.setText(R.string.findingDriver);
requestRide.setText(R.string.cancelR);
if (object.get("driverUsername") != null) {
driverUsername = object.getString("driverUsername");
information.setText(R.string.onTheWay);
Log.i("AppInfo", driverUsername);
}
}
}
}
}
});
}
if (requestActive) {
if (!driverUsername.equals("")) {
ParseQuery<ParseUser> userQuery = ParseUser.getQuery();
userQuery.whereEqualTo("username", driverUsername);
userQuery.findInBackground(new FindCallback<ParseUser>() {
@Override
public void done(List<ParseUser> objects, ParseException e) {
if (e == null) {
if (objects.size() > 0) {
for (ParseUser driver : objects) {
driverLocation = driver.getParseGeoPoint("location");
}
}
}
}
});
if (driverLocation.getLatitude() != 0 && driverLocation.getLongitude() != 0) {
Log.i("AppInfo", driverLocation.toString());
}
}
final ParseGeoPoint userLocation = new ParseGeoPoint(lat, lng);
ParseQuery<ParseObject> query = new ParseQuery<>("requests");
query.whereEqualTo("riderUsername", ParseUser.getCurrentUser().getUsername());
query.findInBackground(new FindCallback<ParseObject>() {
@Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
if (objects.size() > 0) {
for (ParseObject object : objects) {
object.put("riderLocation", userLocation);
object.saveInBackground();
}
}
}
}
});
}
/*
Causes the Runnable in this thread to be run each 2000 milliseconds, updating location.
*/
handler.postDelayed(new Runnable() {
@Override
public void run() {
updateUserLocation(location);
}
}, 2000);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
updateUserLocation(location);
}
@Override
protected void onResume() {
super.onResume();
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
//pauses location search when the user closes the app to save on battery
@Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
@Override
public void onLocationChanged(Location location) {
/*if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
lat = location.getLatitude();
lng = location.getLongitude();
mMap.clear();
updateUserLocation(location);
getAddress();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
public void getAddress() {
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(lat, lng, 1);
if (listAddresses != null && listAddresses.size() > 0) {
Log.i("Location Info:", listAddresses.get(0).toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
//when request ride
public void requestRide(View view) {
//Allows the user to create a request
if (!requestActive) {
final ParseObject request = new ParseObject("requests");
request.put("riderUsername", ParseUser.getCurrentUser().getUsername());
ParseACL parseACL = new ParseACL();
parseACL.setPublicWriteAccess(true);
parseACL.setPublicReadAccess(true);
request.setACL(parseACL);
request.saveInBackground(new SaveCallback() {
@Override
public void done(ParseException e) {
if (e == null) {
updateUserLocation(location);
information.setText(R.string.info);
requestRide.setText(R.string.rideRequest);
requestActive = true;
}
}
});
} else {
ParseQuery<ParseObject> query = new ParseQuery<>("requests");
query.whereEqualTo("riderUsername", ParseUser.getCurrentUser().getUsername());
query.findInBackground(new FindCallback<ParseObject>() {
@Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
if (objects.size() > 0) {
for (ParseObject object : objects) {
object.deleteInBackground();
}
}
}
}
});
information.setText(R.string.infoCancelR);
requestRide.setTeenter code herext(R.string.RequestRide);
requestActive = false;
}
}
}
除外的原因
public void updateUserLocation(final location location){ lat = location.getLatitude(); lng = location.getLongitude();
mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat, lng)).title("Your location"));
mMap.animateCamera(CameraUpdateFactory
.newLatLngZoom(new LatLng(lat, lng), 10));
if (!requestActive) {
ParseQuery<ParseObject> query = new ParseQuery<>("requests");
query.whereEqualTo("riderUsername", ParseUser.getCurrentUser().getUsername());
query.findInBackground(new FindCallback<ParseObject>() {
@Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
if (objects.size() > 0) {
for (ParseObject object : objects) {
requestActive = true;
information.setText(R.string.findingDriver);
requestRide.setText(R.string.cancelR);
if (object.get("driverUsername") != null) {
driverUsername = object.getString("driverUsername");
information.setText(R.string.onTheWay);
Log.i("AppInfo", driverUsername);
}
}
}
}
}
});
}
if (requestActive) {
if (!driverUsername.equals("")) {
ParseQuery<ParseUser> userQuery = ParseUser.getQuery();
userQuery.whereEqualTo("username", driverUsername);
userQuery.findInBackground(new FindCallback<ParseUser>() {
@Override
public void done(List<ParseUser> objects, ParseException e) {
if (e == null) {
if (objects.size() > 0) {
for (ParseUser driver : objects) {
driverLocation = driver.getParseGeoPoint("location");
}
}
}
}
});
if (driverLocation.getLatitude() != 0 && driverLocation.getLongitude() != 0) {
Log.i("AppInfo", driverLocation.toString());
}
}
final ParseGeoPoint userLocation = new ParseGeoPoint(lat, lng);
ParseQuery<ParseObject> query = new ParseQuery<>("requests");
query.whereEqualTo("riderUsername", ParseUser.getCurrentUser().getUsername());
query.findInBackground(new FindCallback<ParseObject>() {
@Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
if (objects.size() > 0) {
for (ParseObject object : objects) {
object.put("riderLocation", userLocation);
object.saveInBackground();
}
}
}
}
});
}
/*
Causes the Runnable in this thread to be run each 2000 milliseconds, updating location.
*/
handler.postDelayed(new Runnable() {
@Override
public void run() {
updateUserLocation(location);
}
}, 2000);
}
logcat的
答案 0 :(得分:1)
没有初始化位置尝试在
中初始化它 @Override
public void onLocationChanged(Location location) {
this.location=location;
}
答案 1 :(得分:1)
您正在尝试访问未初始化或为空的位置。在 updateUserLocation()
中添加另一个空指针检查public void updateUserLocation(final Location location) {
if (location.getLatitude()!=null && location.getLongitude()!=null)
{
lat = location.getLatitude();
lng = location.getLongitude();
}
}