2017-03-24 83 views
0

我想製作一個包含多個活動的Adroid應用程序,其中一個是Google地圖活動,我想讓它獲取您的位置並顯示附近的自定義地點作爲汽車加油站等如果你能告訴我如何使這個),並且每當我啓動這個活動時,應用程序崩潰,由於這個錯誤(我想提到,我在互聯網上搜索和這裏的答案,但沒有發現任何東西):啓動Google地圖活動時出錯

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) { 

} 

}

而且THI是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

UPDATE:

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

移動這個googleMap.setMyLocationEnabled(true);onMapReady()

@Override 
public void onMapReady(GoogleMap googleMap) { 
    googleMap = googleMap; 
    googleMap.setMyLocationEnabled(true); 
} 

而且在onLocationChanged()修改代碼以這樣的:當Map對象正確初始化

@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)); 
    } 
} 

基本思路是GoogleMap的onMapReady()將被調用。在此之前,您的地圖對象將爲空。所以最好在onMapReady()函數中做你的Map相關操作。

+0

感謝的人,它工作的第一次:)),但現在它給出了另一個錯誤,我將它添加在主要問題 –

+0

@BucurMihai檢查編輯... – rafsanahmad007

+0

謝謝男人,現在它的作品,現在我會弄清楚如何讓我看到附近的地方,我定義,我會回來的時候遇到問題,當我卡住了,非常感謝:) –