Java 如何修复移动到google活动时的崩溃
我有这个问题已经有一段时间了,我有一个带有按钮的主活动,它会将用户带到另一个视图中有谷歌地图的活动,但是如果用户点击按钮,应用程序就会崩溃,并给出一条消息说“很遗憾,(应用程序名称)已停止。” 以下是谷歌地图的活动:Java 如何修复移动到google活动时的崩溃,java,android,google-maps,crash,Java,Android,Google Maps,Crash,我有这个问题已经有一段时间了,我有一个带有按钮的主活动,它会将用户带到另一个视图中有谷歌地图的活动,但是如果用户点击按钮,应用程序就会崩溃,并给出一条消息说“很遗憾,(应用程序名称)已停止。” 以下是谷歌地图的活动: package location.hive; import android.app.Dialog; import android.location.Address; import android.location.Geocoder; import android.os.Bundl
package location.hive;
import android.app.Dialog;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.List;
public class DetailActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final int DIALOG_REQUEST = 9001;
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_with_map);
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync();
String city = getIntent().getStringExtra("city");
setTitle(getString(R.string.landon_hotel) + ", " + city);
Hotel hotel = DataProvider.hotelMap.get(city);
if (hotel == null) {
Toast.makeText(this, getString(R.string.error_find_hotel) + ": "
+ city, Toast.LENGTH_SHORT).show();
return;
}
TextView cityText = (TextView) findViewById(R.id.cityText);
cityText.setText(hotel.getCity());
TextView neighborhoodText = (TextView) findViewById(R.id.neighborhoodText);
neighborhoodText.setText(hotel.getNeighborhood());
TextView descText = (TextView) findViewById(R.id.descriptionText);
descText.setText(hotel.getDescription() + "\n");
if (servicesOK() && initMap()) {
Geocoder gc = new Geocoder(this);
List<Address> list;
try {
list = gc.getFromLocationName(hotel.getAddress(), 1);
Address address = list.get(0);
double lat = address.getLatitude();
double lng = address.getLongitude();
LatLng latLong = new LatLng(lat, lng);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLong, 15);
mMap.moveCamera(update);
MarkerOptions options = new MarkerOptions()
.title(getString(R.string.landon_hotel) + ", " + city)
.position(new LatLng(lat, lng));
mMap.addMarker(options);
} catch (IOException e) {
Toast.makeText(this, getString(R.string.error_finding_hotel), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
Log.d(this.getLocalClassName(), e.getMessage());
}
}
}
public boolean servicesOK() {
int result = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (result == ConnectionResult.SUCCESS) {
return true;
} else if (GooglePlayServicesUtil.isUserRecoverableError(result)) {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(result, this, DIALOG_REQUEST);
dialog.show();
} else {
Toast.makeText(this, getString(R.string.error_connect_to_services), Toast.LENGTH_SHORT).show();
}
return false;
}
private boolean initMap() {
if (mMap == null) {
SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
}
return (mMap != null);
}
@Override
public void onMapReady(GoogleMap map) {
}
}
欢迎您提供各种帮助,如果您有任何建议,请与我们分享,
这是我第二次使用StackOverFlow,如果你对我下次如何改进我的问题有反馈的话,那么也欢迎使用下面的代码
<com.google.android.gms.maps.MapView
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
public class MapViewFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.location_fragment, container, false);
mMapView = (MapView) rootView.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap mMap) {
if(servicesOK()){
googleMap = mMap;
// For showing a move to my location button
googleMap.setMyLocationEnabled(true);
Geocoder gc = new Geocoder(this);
List<Address> list;
try {
list = gc.getFromLocationName(hotel.getAddress(), 1);
Address address = list.get(0);
double lat = address.getLatitude();
double lng = address.getLongitude();
LatLng latLong = new LatLng(lat, lng);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLong, 15);
googleMap.moveCamera(update);
MarkerOptions options = new MarkerOptions()
.title(getString(R.string.landon_hotel) + ", " + city)
.position(new LatLng(lat, lng));
googleMap.addMarker(options);
} catch (IOException e) {
Toast.makeText(this, getString(R.string.error_finding_hotel), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
Log.d(this.getLocalClassName(), e.getMessage());
}
}
}
});
return rootView;
}
@Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
public boolean servicesOK() {
int result = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (result == ConnectionResult.SUCCESS) {
return true;
} else if (GooglePlayServicesUtil.isUserRecoverableError(result)) {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(result, this, DIALOG_REQUEST);
dialog.show();
} else {
Toast.makeText(this, getString(R.string.error_connect_to_services),
Toast.LENGTH_SHORT).show();
}
return false;
}
}
公共类MapViewFragment扩展了片段{
地图视图;
私人谷歌地图谷歌地图;
@凌驾
CreateView上的公共视图(布局、充气机、视图组容器、捆绑包保存状态){
视图根视图=充气机。充气(R.layout.location\u碎片,容器,假);
mMapView=(MapView)rootView.findviewbyd(R.id.MapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();//需要立即显示地图
试一试{
初始化(getActivity().getApplicationContext());
}捕获(例外e){
e、 printStackTrace();
}
mMapView.getMapAsync(新的OnMapReadyCallback(){
@凌驾
4月1日公开作废(谷歌地图mMap){
if(servicesOK()){
谷歌地图=mMap;
//用于显示“移动到我的位置”按钮
googleMap.setMyLocationEnabled(true);
地理编码器gc=新地理编码器(本);
名单;
试一试{
list=gc.getFromLocationName(hotel.getAddress(),1);
地址=list.get(0);
双lat=地址。getLatitude();
double lng=address.getLongitude();
LatLng latLong=新LatLng(lat,lng);
CameraUpdate update=CameraUpdateFactory.newLatLngZoom(latLong,15);
谷歌地图。移动摄像机(更新);
MarkerOptions选项=新的MarkerOptions()
.title(getString(R.string.landon_hotel)+“,”+城市)
.位置(新LatLng(lat,lng));
googleMap.addMarker(选项);
}捕获(IOE异常){
Toast.makeText(this,getString(R.string.error\u finding\u hotel),Toast.LENGTH\u SHORT.show();
}捕获(例外e){
Toast.makeText(this,e.getMessage(),Toast.LENGTH_SHORT.show();
Log.d(this.getLocalClassName(),e.getMessage());
}
}
}
});
返回rootView;
}
@凌驾
恢复时公开作废(){
super.onResume();
mMapView.onResume();
}
@凌驾
公共无效暂停(){
super.onPause();
mMapView.onPause();
}
@凌驾
公共空间{
super.ondestory();
mMapView.onDestroy();
}
@凌驾
public void onLowMemory(){
super.onLowMemory();
mMapView.onLowMemory();
}
公共布尔服务sok(){
int result=GooglePlayServicesUtil.isGooglePlayServicesAvailable(此);
if(result==ConnectionResult.SUCCESS){
返回true;
}else if(GooglePlayServicesUtil.isUserRecoverableError(结果)){
Dialog Dialog=GooglePlayServicesUtil.getErrorDialog(结果、此对话框、请求);
dialog.show();
}否则{
Toast.makeText(这个,getString(R.string.error\u connect\u to\u services),
吐司。长度(短)。show();
}
返回false;
}
}
u是否可以添加gradle库的可能副本?哪个是上层类还是另一个?MapFragment MapFragment=(MapFragment)getFragmentManager().findFragmentById(R.id.map);“地图”id名称正确吗?abhi20392您能把您的答案写在下面吗?这样我就可以做出正确的答案,非常感谢您给我的所有帮助
02-26 14:45:07.452 27233-27233/location.hive W/System: ClassLoader referenced unknown path: /data/app/location.hive-1/lib/arm
02-26 14:45:07.472 27233-27233/location.hive I/FirebaseInitProvider: FirebaseApp initialization unsuccessful
02-26 14:45:07.472 27233-27233/location.hive I/InstantRun: starting instant run server: is main process
02-26 14:45:07.562 27233-27233/location.hive W/ResourcesManager: getTopLevelResources: /data/app/location.hive-1/base.apk / 1.0 running in location.hive rsrc of package null
02-26 14:45:07.572 27233-27233/location.hive W/ResourcesManager: getTopLevelResources: /data/app/location.hive-1/base.apk / 1.0 running in location.hive rsrc of package null
02-26 14:45:07.622 27233-27233/location.hive W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
02-26 14:45:07.792 27233-27233/location.hive D/TextView: setTypeface with style : 0
02-26 14:45:07.792 27233-27233/location.hive D/TextView: setTypeface with style : 0
02-26 14:45:07.822 27233-27233/location.hive D/AbsListView: Get MotionRecognitionManager
02-26 14:45:07.832 27233-27233/location.hive E/MotionRecognitionManager: mSContextService = android.hardware.scontext.ISContextService$Stub$Proxy@1c027fd
02-26 14:45:07.832 27233-27233/location.hive E/MotionRecognitionManager: motionService = com.samsung.android.motion.IMotionRecognitionService$Stub$Proxy@5ae4cf2
02-26 14:45:07.832 27233-27233/location.hive E/MotionRecognitionManager: motionService = com.samsung.android.motion.IMotionRecognitionService$Stub$Proxy@5ae4cf2
02-26 14:45:07.862 27233-27233/location.hive D/SecWifiDisplayUtil: Metadata value : none
02-26 14:45:07.872 27233-27233/location.hive D/ViewRootImpl: #1 mView = com.android.internal.policy.PhoneWindow$DecorView{7c739c0 I.E...... R.....ID 0,0-0,0}
02-26 14:45:07.872 27233-27276/location.hive D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
02-26 14:45:07.922 27233-27276/location.hive I/Adreno-EGL: <qeglDrvAPI_eglInitialize:379>: EGL 1.4 QUALCOMM build: (Ia10634f51b)
OpenGL ES Shader Compiler Version: E031.29.00.00
Build Date: 01/28/16 Thu
Local Branch: ss
Remote Branch:
Local Patches:
Reconstruct Branch:
02-26 14:45:07.922 27233-27276/location.hive D/libEGL: eglInitialize EGLDisplay = 0x9eb9a7c4
02-26 14:45:07.922 27233-27276/location.hive I/OpenGLRenderer: Initialized EGL, version 1.4
02-26 14:45:08.002 27233-27233/location.hive D/TextView: setTypeface with style : 0
02-26 14:45:08.002 27233-27233/location.hive D/TextView: setTypeface with style : 0
02-26 14:45:08.022 27233-27233/location.hive D/TextView: setTypeface with style : 0
02-26 14:45:08.022 27233-27233/location.hive D/TextView: setTypeface with style : 0
02-26 14:45:08.062 27233-27233/location.hive D/TextView: setTypeface with style : 0
02-26 14:45:08.072 27233-27233/location.hive D/TextView: setTypeface with style : 0
02-26 14:45:08.102 27233-27233/location.hive D/TextView: setTypeface with style : 0
02-26 14:45:08.102 27233-27233/location.hive D/TextView: setTypeface with style : 0
02-26 14:45:08.172 27233-27233/location.hive W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
02-26 14:45:08.192 27233-27233/location.hive W/DisplayListCanvas: DisplayListCanvas is started on unbinded RenderNode (without mOwningView)
02-26 14:45:08.382 27233-27233/location.hive D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 72 - 0, 0) vi=Rect(0, 72 - 0, 0) or=1
02-26 14:45:08.422 27233-27233/location.hive I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@bd4af43 time:97011894
02-26 14:45:10.632 27233-27233/location.hive D/ViewRootImpl: ViewPostImeInputStage processPointer 0
02-26 14:45:10.682 27233-27233/location.hive D/ViewRootImpl: ViewPostImeInputStage processPointer 1
02-26 14:45:10.752 27233-27233/location.hive I/Timeline: Timeline: Activity_launch_request id:location.hive time:97014225
02-26 14:45:10.822 27233-27233/location.hive W/ResourcesManager: getTopLevelResources: /data/app/location.hive-1/base.apk / 1.0 running in location.hive rsrc of package null
02-26 14:45:10.832 27233-27328/location.hive W/ResourceType: For resource 0x7f02005a, entry index(90) is beyond type entryCount(2)
02-26 14:45:10.832 27233-27328/location.hive W/ResourceType: Failure getting entry for 0x7f02005a (t=1 e=90) (error -75)
02-26 14:45:10.842 27233-27328/location.hive E/Resources: RunTimeException
android.content.res.Resources$NotFoundException: Resource ID #0x7f02005a
at android.content.res.Resources.getValue(Resources.java:2558)
at android.content.res.Resources.startRC(Resources.java:1116)
at android.app.ActivityThread$mRunnable.run(ActivityThread.java:3055)
at java.lang.Thread.run(Thread.java:818)
02-26 14:45:10.852 27233-27233/location.hive D/TextView: setTypeface with style : 0
02-26 14:45:10.852 27233-27233/location.hive D/TextView: setTypeface with style : 0
02-26 14:45:10.852 27233-27233/location.hive D/TextView: setTypeface with style : 0
02-26 14:45:10.852 27233-27233/location.hive D/TextView: setTypeface with style : 0
02-26 14:45:10.862 27233-27233/location.hive D/TextView: setTypeface with style : 0
02-26 14:45:10.922 27233-27233/location.hive I/zzbz: Making Creator dynamically
02-26 14:45:10.942 27233-27233/location.hive I/DynamiteModule: Considering local module com.google.android.gms.maps_dynamite:0 and remote module com.google.android.gms.maps_dynamite:18
02-26 14:45:10.942 27233-27233/location.hive I/DynamiteModule: Selected remote version of com.google.android.gms.maps_dynamite, version >= 18
02-26 14:45:10.952 27233-27233/location.hive W/ResourcesManager: getTopLevelResources: /data/app/com.google.android.gms-2/base.apk / 1.0 running in location.hive rsrc of package null
02-26 14:45:10.992 27233-27233/location.hive W/System: ClassLoader referenced unknown path: /data/data/com.google.android.gms/app_chimera/m/00000030/n/armeabi
02-26 14:45:11.002 27233-27233/location.hive W/ResourcesManager: getTopLevelResources: /data/data/com.google.android.gms/app_chimera/m/00000030/DynamiteModulesB_GmsCore_prodmnc_xxhdpi_release.apk / 1.0 running in location.hive rsrc of package null
02-26 14:45:11.012 27233-27233/location.hive W/ResourcesManager: getTopLevelResources: /data/data/com.google.android.gms/app_chimera/m/00000030/DynamiteModulesB_GmsCore_prodmnc_xxhdpi_release.apk / 1.0 running in location.hive rsrc of package null
02-26 14:45:11.112 27233-27233/location.hive I/Google Maps Android API: Google Play services client version: 11910000
02-26 14:45:11.132 27233-27233/location.hive I/Google Maps Android API: Google Play services package version: 11975438
02-26 14:45:11.352 27233-27233/location.hive W/System.err: remove failed: ENOENT (No such file or directory) : /data/user/0/location.hive/files/DATA_ServerControlledParametersManager.data.location.hive
02-26 14:45:11.492 27233-27233/location.hive D/AbsListView: Get MotionRecognitionManager
02-26 14:45:11.492 27233-27233/location.hive E/MotionRecognitionManager: mSContextService = android.hardware.scontext.ISContextService$Stub$Proxy@eb5cd14
02-26 14:45:11.492 27233-27233/location.hive E/MotionRecognitionManager: motionService = com.samsung.android.motion.IMotionRecognitionService$Stub$Proxy@95c99bd
02-26 14:45:11.492 27233-27233/location.hive E/MotionRecognitionManager: motionService = com.samsung.android.motion.IMotionRecognitionService$Stub$Proxy@95c99bd
02-26 14:45:11.522 27233-27233/location.hive W/System.err: mkdir failed: EEXIST (File exists) : /storage/emulated/0/Android/data/location.hive/cache/debug
02-26 14:45:11.522 27233-27233/location.hive W/System.err: mkdir failed: EEXIST (File exists) : /storage/emulated/0/Android/data/location.hive/cache
02-26 14:45:11.642 27233-27359/location.hive W/System.err: remove failed: ENOENT (No such file or directory) : /data/user/0/location.hive/files/event_store_v2_location.hive
02-26 14:45:11.652 27233-27233/location.hive D/AndroidRuntime: Shutting down VM
02-26 14:45:11.652 27233-27233/location.hive E/AndroidRuntime: FATAL EXCEPTION: main
Process: location.hive, PID: 27233
java.lang.RuntimeException: Unable to start activity ComponentInfo{location.hive/location.hive.DetailActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.MapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3253)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
at android.app.ActivityThread.access$1100(ActivityThread.java:221)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.MapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
at location.hive.DetailActivity.onCreate(DetailActivity.java:42)
at android.app.Activity.performCreate(Activity.java:6876)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3206)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
at android.app.ActivityThread.access$1100(ActivityThread.java:221)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
02-26 14:45:13.652 27233-27360/location.hive W/DynamiteModule: Local module descriptor class for com.google.android.gms.googlecertificates not found.
02-26 14:45:13.662 27233-27360/location.hive I/DynamiteModule: Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:4
02-26 14:45:13.662 27233-27360/location.hive I/DynamiteModule: Selected remote version of com.google.android.gms.googlecertificates, version >= 4
02-26 14:45:13.682 27233-27360/location.hive W/System: ClassLoader referenced unknown path: /data/data/com.google.android.gms/app_chimera/m/0000002e/n/armeabi-v7a
02-26 14:45:13.682 27233-27360/location.hive W/System: ClassLoader referenced unknown path: /data/data/com.google.android.gms/app_chimera/m/0000002e/n/armeabi
02-26 14:45:13.682 27233-27360/location.hive W/ResourcesManager: getTopLevelResources: /data/data/com.google.android.gms/app_chimera/m/0000002e/GoogleCertificates_GmsCore_prodmnc_xxhdpi_release.apk / 1.0 running in location.hive rsrc of package null
02-26 14:45:13.682 27233-27360/location.hive W/ResourcesManager: getTopLevelResources: /data/data/com.google.android.gms/app_chimera/m/0000002e/GoogleCertificates_GmsCore_prodmnc_xxhdpi_release.apk / 1.0 running in location.hive rsrc of package null
02-26 14:46:05.282 27233-27233/location.hive I/Process: Sending signal. PID: 27233 SIG: 9
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
applicationId "location.hive"
minSdkVersion 21
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile 'com.google.android.gms:play-services:11.8.0'
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation fileTree(dir: 'libs', include: ['*.jar'])
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
testImplementation 'junit:junit:4.12'
}
<com.google.android.gms.maps.MapView
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
public class MapViewFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.location_fragment, container, false);
mMapView = (MapView) rootView.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap mMap) {
if(servicesOK()){
googleMap = mMap;
// For showing a move to my location button
googleMap.setMyLocationEnabled(true);
Geocoder gc = new Geocoder(this);
List<Address> list;
try {
list = gc.getFromLocationName(hotel.getAddress(), 1);
Address address = list.get(0);
double lat = address.getLatitude();
double lng = address.getLongitude();
LatLng latLong = new LatLng(lat, lng);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLong, 15);
googleMap.moveCamera(update);
MarkerOptions options = new MarkerOptions()
.title(getString(R.string.landon_hotel) + ", " + city)
.position(new LatLng(lat, lng));
googleMap.addMarker(options);
} catch (IOException e) {
Toast.makeText(this, getString(R.string.error_finding_hotel), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
Log.d(this.getLocalClassName(), e.getMessage());
}
}
}
});
return rootView;
}
@Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
public boolean servicesOK() {
int result = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (result == ConnectionResult.SUCCESS) {
return true;
} else if (GooglePlayServicesUtil.isUserRecoverableError(result)) {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(result, this, DIALOG_REQUEST);
dialog.show();
} else {
Toast.makeText(this, getString(R.string.error_connect_to_services),
Toast.LENGTH_SHORT).show();
}
return false;
}
}