我做了一个显示谷歌地图的活动,但我想将其更改为“碎片”,当我这样做时,我会遇到很多错误。
initmap方法上的getMapAsync遇到问题。
public class TAXIActivity extends Fragment implements OnMapReadyCallback {
private GoogleMap mMap;
private MapView mapView;
ArrayList LatitudeList = new ArrayList();
ArrayList LongitudeList = new ArrayList();
private FusedLocationProviderClient mFusedLocationProviderClient;
private Boolean mLocationPermissionsGranted = false;
private static final float DEFAULT_ZOOM = 15f;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_taxi, container, false);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_taxi);
/*
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
*/
getLocationPermission();
//someMethod();
}
public void onViewCreated (View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initMap();
}
@Override
public void onMapReady(GoogleMap googleMap) {
Toast.makeText(getContext(), "Map is Ready", Toast.LENGTH_SHORT).show();
Log.d("TAXIActivity", "onMapReady: map is ready");
mMap = googleMap;
someMethod();
if (mLocationPermissionsGranted) {
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
//mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
//Log.d("TEST", "BBB");
//String LatMarkers = LatitudeList.toString();
//String LongMarkers = LongitudeList.toString();
//Log.d("TEST", "AAA");
/*
double latitude = Double.parseDouble(LatMarkers);
double longitude = Double.parseDouble(LongMarkers);
LatLng location = new LatLng(latitude, longitude);
//Log.d("TEST", "CCC");
mMap.addMarker(new MarkerOptions().position(location).title("Camera Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
*/
//Log.d("TEST", "DDD");
}
OkHttpClient client = new OkHttpClient();
void someMethod() {
try {
String jsonData = new TAXIAPI(client).execute().get();
JSONObject object = new JSONObject(jsonData);
JSONArray RunningArray = object.getJSONArray("value");
for (int i = 0; i < RunningArray.length(); ++i) {
JSONObject objectInner = new JSONObject(RunningArray.getString(i));
String Latitude = objectInner.getString("Latitude");
String Longitude = objectInner.getString("Longitude");
double lat = Double.parseDouble(Latitude);
double lng = Double.parseDouble(Longitude);
LatLng location = new LatLng(lat, lng);
mMap.addMarker(new MarkerOptions().position(location).title("Taxi Location"));
//mMap.moveCamera(CameraUpdateFactory.newLatLng(location));//this will make camera focus on the last marker location
//LatitudeList.add(Latitude);
//LongitudeList.add(Longitude);
Log.d("APIActivity", " " + Latitude + " " + Longitude);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void getDeviceLocation() {
Log.d("TAXIActivity", "getDeviceLocation: getting the devices current location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());
try {
if (mLocationPermissionsGranted) {
final Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()) {
Log.d("TAXIActivity", "onComplete: found location!");
Location currentLocation = (Location) task.getResult();
moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),
DEFAULT_ZOOM);
} else {
Log.d("TAXIActivity", "onComplete: current location is null");
Toast.makeText(getContext(), "unable to get current location", Toast.LENGTH_SHORT).show();
}
}
});
}
} catch (SecurityException e) {
Log.e("TAXIActivity", "getDeviceLocation: SecurityException: " + e.getMessage());
}
}
private void moveCamera(LatLng latLng, float zoom) {
Log.d("TAXIActivity", "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
private void initMap() {
Log.d("TAXIActivity", "initMap: initializing map");
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(TAXIActivity.this);
}
private void getLocationPermission() {
Log.d("TAXIActivity", "getLocationPermission: getting location permissions");
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
if (ContextCompat.checkSelfPermission(getActivity().getApplicationContext(),
FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(getActivity().getApplicationContext(),
COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionsGranted = true;
initMap();
} else {
ActivityCompat.requestPermissions(getActivity(),
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
} else {
ActivityCompat.requestPermissions(getActivity(),
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
Log.d("TAXIActivity", "onRequestPermissionsResult: called.");
mLocationPermissionsGranted = false;
switch (requestCode) {
case LOCATION_PERMISSION_REQUEST_CODE: {
if (grantResults.length > 0) {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
mLocationPermissionsGranted = false;
Log.d("TAXIActivity", "onRequestPermissionsResult: permission failed");
return;
}
}
Log.d("TAXIActivity", "onRequestPermissionsResult: permission granted");
mLocationPermissionsGranted = true;
//initialize our map
initMap();
}
}
}
}
}
错误:
原因:java.lang.NullPointerException:尝试在空对象上调用虚拟方法“ void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)”参考 在com.example.assignment1.TAXIActivity.initMap(TAXIActivity.java:199) 在com.example.assignment1.TAXIActivity.getLocationPermission(TAXIActivity.java:213) 在com.example.assignment1.TAXIActivity.onCreate(TAXIActivity.java:72)
答案 0 :(得分:0)
在创建片段视图之前,您正在获取Google地图片段。
现在您正在执行的操作,先依次是onCreate
和getLocationPermission
然后initMap
和.findFragmentById
。您的Google地图片段目前尚未初始化,这就是为什么在调用.getMapAsync
时会得到空指针异常的原因。
两种解决方案。将您getLocationPermission
移至onViewCreated
或从initMap
中删除getLocationPermission
。
我会做第二个,因为Google Map不需要位置许可。