2017-03-24 11 views
0

複数のアクティビティを持つadroidアプリを作りたいと思っています。その1つは自分の位置を取得して近くの場所を自動車ガソリンスタンドなどに表示するGoogleマップアクティビティです私がこの活動を開始しているときはいつでも、このエラーのためにアプリがクラッシュする(私はインターネット上で検索し、答えは見つけたが何も見つからなかったと言いたい)。Google Mapsアクティビティを起動するとエラーが発生する

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

} 
<?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> 

は、あなたが私を助けることを願っ:10} THIはAndroidManifes.XMLファイル

そしてある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()

これまでご onLocationChanged()修正コードでも
@Override 
public void onMapReady(GoogleMap googleMap) { 
    googleMap = googleMap; 
    googleMap.setMyLocationEnabled(true); 
} 

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

基本的な考え方は、GoogleマップonMapReady()ですが呼び出されます。その時間まではマップオブジェクトはnullになります。だからonMapReady()の機能でマップ関連の操作を行うのが最善です。

+0

ありがとうございました。)しかし、今では別のエラーが表示されます。メイン質問 –

+0

@BucurMihaiで編集を確認してください... – rafsanahmad007

+0

ありがとうございました。私に定義されている近くの場所を表示する方法、私は立ち往生したときに質問して戻ってくるだろう、多くのありがとう:) –

関連する問題