【发布时间】:2014-12-05 13:05:27
【问题描述】:
我在 Android Lollipop 中启动应用时发现了一个错误。 Logcat 说:
java.lang.NullPointerException:
Attempt to invoke virtual method 'com.google.android.gms.maps.GoogleMap.
com.google.android.gms.maps.MapFragment.getMap()' on a null object reference
此错误仅在 Android Lollipop 中显示,exact same 应用在其他设备上运行时没有问题*。
代码如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="@+id/map_side_holder"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/BlueGreyL3"
android:orientation="horizontal"
android:weightSum="100">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/map_margin_left_24dp"
android:layout_marginStart="@dimen/map_margin_left_24dp"
android:layout_weight="8"
android:orientation="vertical">
<!-- MAP -->
<fragment
android:id="@+id/location_map"
class="com.google.android.gms.maps.MapFragment"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
<!-- Ads -->
<LinearLayout
android:id="@+id/linlay_wrb"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
</LinearLayout>
</RelativeLayout>
Google Map v2 Fragment 通过调用加载到我的班级LocationFragments.java
// View
try {
mView = inflater.inflate(R.layout.location_fragment, container, false);
sMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.location_map)).getMap();
mSideHolder = (LinearLayout) mView.findViewById(R.id.map_side_holder);
我用的是AndroidStudio所以这里是build.gradle:
android {
compileSdkVersion 21
buildToolsVersion "21.1.1"
defaultConfig {
minSdkVersion 15
targetSdkVersion 21
}
[...]
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:support-v13:21.0.0'
compile 'com.android.support:support-v4:21.0.0'
compile 'com.google.android.gms:play-services:5.0.89'
}
和清单:
<!-- Google Play -->
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version"/>
<!-- Maps -->
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value=""/>
我不明白,我做错了什么..问题可能是由棒棒糖本身引起的吗?
提前致谢,
马丁
*测试设备:
- HTC One M8 - 4.4.4 (GPE / API 19) -> 工作
- 三星 S4 Mini - 4.4.2 (CM11 / API 19) -> 工作
- 三星 S2 - 4.0.3 (ICS / API 15) -> 工作
- HTC One M8 - 5.0 (LL / API 20) -> 加载地图时出错
- Nexus 5 - 5.0 (LL / API 20) -> 加载地图时出错
【问题讨论】:
-
尝试将
getMap代码移动到onResume -
有效!非常感谢,拯救了我的周末;)但这是为什么呢? ART 对 Maps Fragment 的实例化不如老 Dalvik 快吗?如果你愿意,我会接受你的回答。
-
很高兴为您提供帮助 :) 我已尽力解释我在回答中不知道的内容,哈哈
-
编辑:遗憾的是它不起作用。我刚刚监督了一次尝试捕获... getMap() 上仍然存在相同的错误...我将阅读此内容:stackoverflow.com/questions/13722192/…
-
是的,尝试更新您的
google play services。我用最新的onResume并且错误再也没有发生过
标签: android google-maps android-fragments android-5.0-lollipop