我想制作一个有多项活动的adroid应用程序,其中一个是谷歌地图活动,我想让它来获取你的位置并显示附近的地方作为汽车加油站等(如果你能告诉我如何制作此请()),每当我启动此活动时,应用程序因此错误而崩溃(我想提到我在互联网上搜索并在这里寻找答案但未找到任何内容):
03-24 14:22:24.737 12970-12970/com.mihai_bucur.happycar E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mihai_bucur.happycar, PID: 12970
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mihai_bucur.happycar/com.mihai_bucur.happycar.GooglePlacesActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.setMyLocationEnabled(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2702)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.setMyLocationEnabled(boolean)' on a null object reference
at com.mihai_bucur.happycar.GooglePlacesActivity.onCreate(GooglePlacesActivity.java:65)
at android.app.Activity.performCreate(Activity.java:6289)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2655)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
这是活动代码:
package com.mihai_bucur.happycar;
/**
* Created by Mihai on 18.12.2016.
*/
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
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;
public class GooglePlacesActivity extends android.support.v4.app.FragmentActivity implements LocationListener, OnMapReadyCallback {
private static final String GOOGLE_API_KEY = "AIzaSyDCS0BtucuGB4nDRV15NYbT6fqLHtWgtQs";
GoogleMap googleMap;
EditText placeText;
double latitude = 0;
double longitude = 0;
private int PROXIMITY_RADIUS = 5000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//show error dialog if GoolglePlayServices not available
if (!checkPlayServices()) {
finish();
}
setContentView(R.layout.activity_google_places);
placeText = (EditText) findViewById(R.id.placeText);
Button btnFind = (Button) findViewById(R.id.btnFind);
SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
fragment.getMapAsync(this);
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 locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Criteria criteria = new Criteria();
// String provider = locationManager.getBestProvider(criteria, true);
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
btnFind.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String type = placeText.getText().toString();
StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlacesUrl.append("location=" + latitude + "," + longitude);
googlePlacesUrl.append("&radius=" + PROXIMITY_RADIUS);
googlePlacesUrl.append("&types=" + type);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key=" + GOOGLE_API_KEY);
GooglePlacesReadTask googlePlacesReadTask = new GooglePlacesReadTask();
Object[] toPass = new Object[2];
toPass[0] = googleMap;
toPass[1] = googlePlacesUrl.toString();
googlePlacesReadTask.execute(toPass);
}
});
}
public boolean checkPlayServices() {
final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if(result != ConnectionResult.SUCCESS) {
if(googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
}
return false;
}
return true;
}
@Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onMapReady(GoogleMap googleMap) {
}
}
这是AndroidManifes.XML文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mihai_bucur.happycar">
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
<!--Pentru a vedea daca telefonul e conectat la vreo retea, folosim -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<!-- Daca suntem sau nu conectati la net -->
<uses-permission android:name="android.permission.INTERNET"/>
<!-- Pentru a determina locatia aproximativa cu wifi sau date mobile -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<!-- Pnt -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:name=".RemindMe"
android:allowBackup="true"
android:icon="@mipmap/camaro_laucher"
android:background="@android:color/transparent"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.AppCompat.NoActionBar">
<activity android:name=".splash">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Meniu"
android:label="@string/title_activity_meniu"
android:windowSoftInputMode="stateHidden">
android:theme="@style/Theme.AppCompat.NoActionBar">
</activity>
<activity android:name=".Setari" />
<activity android:name=".Documente" />
<activity android:name=".AddAlarmActivity" />
<activity android:name=".GooglePlacesActivity"/>
<receiver android:name=".AlarmSetter">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<receiver android:name=".AlarmReceiver" />
<service android:name=".AlarmService" />
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />
</application>
希望你能帮助我:D
更新:
03-24 15:00:49.576 4339-4339/com.mihai_bucur.happycar E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mihai_bucur.happycar, PID: 4339
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mihai_bucur.happycar/com.mihai_bucur.happycar.GooglePlacesActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.moveCamera(com.google.android.gms.maps.CameraUpdate)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2702)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.moveCamera(com.google.android.gms.maps.CameraUpdate)' on a null object reference
at com.mihai_bucur.happycar.GooglePlacesActivity.onLocationChanged(GooglePlacesActivity.java:143)
at com.mihai_bucur.happycar.GooglePlacesActivity.onCreate(GooglePlacesActivity.java:71)
at android.app.Activity.performCreate(Activity.java:6289)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2655)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
03-24 15:00:50.367 4339-4346/com.mihai_bucur.happycar W/art: Suspending all threads took: 130.004ms
答案 0 :(得分:0)
在googleMap.setMyLocationEnabled(true);
onMapReady()
@Override
public void onMapReady(GoogleMap googleMap) {
googleMap = googleMap;
googleMap.setMyLocationEnabled(true);
}
同样在您的onLocationChanged()
修改代码中:
@Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
if(googleMap != null){
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
}
基本思路是在Map对象正确初始化时调用GoogleMap onMapReady()
。在此之前,您的地图对象将为null。因此,最好在onMapReady()
函数中执行与地图相关的操作。