我正在开发移动应用程序,而且我还是Android Studio新手。在这个应用程序中,我需要使用谷歌地图。该应用程序在我的智能手机上正常运行,但当我点击按钮导航到谷歌地图页面时,会弹出一条消息,提示我的应用程序已停止。有人可以帮我解决这个问题吗?
MapsActivity.java
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
private GoogleApiClient client;
private LocationRequest locationRequest;
private Location lastlocation;
private Marker currentLocationMarker;
public static final int REQUEST_LOCATION_CODE = 99;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
checkLocationPermission();
}
// 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);
setUpMapIfNeeded();
}
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch(requestCode)
{
case REQUEST_LOCATION_CODE:
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
//permission is granted
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
if(client == null)
{
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
}
else //permission is denied
{
Toast.makeText(this, "Permission Denied!", Toast.LENGTH_LONG).show();
}
return;
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
//DO WHATEVER YOU WANT WITH GOOGLEMAP
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//mMap.setMyLocationEnabled(true);
mMap.setTrafficEnabled(true);
mMap.setIndoorEnabled(true);
mMap.setBuildingsEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
setUpMap();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
SupportMapFragment mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map));
mMap.getMapAsync(this);
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(3.188426, 101.682027)).title("This is my first marker"));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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,
//
mMap.setMyLocationEnabled(true); //int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
}
protected synchronized void buildGoogleApiClient()
{
client = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
client.connect();
}
@Override
public void onLocationChanged(Location location) {
// latitude = location.getLatitude();
//longiude = location.getLongitude();
lastlocation = location;
if (currentLocationMarker != null)
{
currentLocationMarker.remove();
}
LatLng latlng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latlng);
markerOptions.title("Current Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
currentLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
mMap.animateCamera(CameraUpdateFactory.zoomBy(10));
if (client != null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(client, this);
}
}
/*@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}*/
public void onClick (View v)
{
if(v.getId() == R.id.searchbtn)
{
EditText userlocation = (EditText)findViewById(R.id.userLocation);
String location = userlocation.getText().toString();
List<Address> addressList = null;
MarkerOptions mo = new MarkerOptions();
if( !location.equals(""))
{
Geocoder geocoder = new Geocoder(this);
try
{
addressList = geocoder.getFromLocationName(location, 5);
}
catch (IOException e)
{
e.printStackTrace();
}
for(int i=0; i<addressList.size(); i++)
{
Address myAddress = addressList.get(i);
LatLng latLng = new LatLng(myAddress.getLatitude(), myAddress.getLongitude());
mo.position(latLng);
mo.title("Your Search Result");
mMap.addMarker(mo);
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
}
}
@Override
public void onConnected(@Nullable Bundle bundle) {
locationRequest = new LocationRequest();
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);
}
}
public boolean checkLocationPermission()
{
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_CODE);
}
else
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_CODE);
}
return false;
}
else
return true;
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
}
的AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.asus.autocare">
<!-- To auto-complete the email text field in the login form with the user's
emails -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name =
"com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity" />
<activity android:name=".LoginActivity" />
<activity android:name=".RegisterActivity" />
<activity android:name=".SplashScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="@string/title_activity_maps" />
<activity android:name=".ChooseActivity"></activity>
</application> </manifest>
这是我得到的错误:
05-02 21:11:10.236 30445-30445/? E/Zygote: v2
05-02 21:11:10.238 30445-30445/? E/Zygote: accessInfo : 0
05-02 21:11:12.271 30445-30445/com.example.asus.autocare E/BoostFramework:
BoostFramework() : Exception_1 = java.lang.ClassNotFoundException: Didn't
find class "com.qualcomm.qti.Performance" on path:
DexPathList[[],nativeLibraryDirectories=[/system/lib, /vendor/lib]]
05-02 21:11:30.904 30445-30445/com.example.asus.autocare E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.example.asus.autocare, PID: 30445
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.asus.autocare/com.example.asus.autocare.MapsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2984)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
at com.example.asus.autocare.MapsActivity.setUpMap(MapsActivity.java:147)
at com.example.asus.autocare.MapsActivity.setUpMapIfNeeded(MapsActivity.java:140)
at com.example.asus.autocare.MapsActivity.onCreate(MapsActivity.java:64)
at android.app.Activity.performCreate(Activity.java:6955)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
答案 0 :(得分:0)
尝试将这些行移到onMapLoaded()上。
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));