mainactivity - java.lang.NullPointerException

时间:2014-05-24 17:32:11

标签: android android-intent google-maps-android-api-2

我开发了一个简单的应用程序谷歌地图v2,它有一个按钮,可以看到具有特定坐标的城市..

我只想设置按钮来查看城市

这是我的主要活动:

package co.id.adhe.agmv2;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

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.model.LatLng;

public class MainActivity extends Activity {
private final LatLng LOCATION_CITY = new LatLng (-0.887415, 100.359654);

private GoogleMap map;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    map = ((MapFragment) 
                   getFragmentManager().findFragmentById(R.id.map)).getMap();

    if (savedInstanceState == null) {
        getFragmentManager().beginTransaction()
                .add(R.id.container, new 
                                    PlaceholderFragment()).commit();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container,
                false);
        return rootView;
    }
}

public void onClick_City(View v) {
    CameraUpdate update = CameraUpdateFactory.newLatLng (LOCATION_CITY);
    map.animateCamera(update);
}
public void onClick_Satelite(View v) {

}
public void onClick_Terrain(View v) {

 }
 }

my activity_main:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="co.id.adhe.agmv2.MainActivity"
tools:ignore="MergeRootFrame" />

my fragment_main:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="co.id.adhe.agmv2.MainActivity$PlaceholderFragment" >


<Button
    android:id="@+id/btnCity"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="onClick_City"
    android:text="@string/btnCity" />

<fragment
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.MapFragment"
    android:layout_below="@+id/btnCity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />

<Button
    android:id="@+id/btnsat"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/btnCity"
    android:layout_alignBottom="@+id/btnCity"
    android:layout_centerHorizontal="true"
    android:onClick="onClick_Satellite"
    android:text="@string/btnsat" />

<Button
    android:id="@+id/btnter"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/btnsat"
    android:layout_alignRight="@+id/map"
    android:onClick="onClick_Terrain"
    android:text="@string/btnter" />

</RelativeLayout>

这是我的androidmanifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="co.id.adhe.agmv2"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="19" />

<permission
    android:name="co.id.adhe.agmv2.permission.MAPS_RECEIVE"
    android:protectionLevel="signature"/>
<uses-permission android:name="co.id.adhe.agmv2.permission.MAPS_RECEIVE"/>

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission 
android:name="com.google.android.providers.gsf.permission.READ_GSERVICE"/>
<!-- the following two permission are not required to use google maps android API V2,
but are recommended -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="4452000"/>
        <meta-data 
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="myapikey"/>        

    <activity
        android:name="co.id.adhe.agmv2.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

我的logcat

05-25 00:10:46.000: E/AndroidRuntime(1802): FATAL EXCEPTION: main
05-25 00:10:46.000: E/AndroidRuntime(1802): java.lang.RuntimeException: Unable to start activity ComponentInfo{co.id.adhe.agmv2/co.id.adhe.agmv2.MainActivity}: java.lang.NullPointerException
05-25 00:10:46.000: E/AndroidRuntime(1802):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211) 
05-25 00:10:46.000: E/AndroidRuntime(1802):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
05-25 00:10:46.000: E/AndroidRuntime(1802):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
05-25 00:10:46.000: E/AndroidRuntime(1802):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
05-25 00:10:46.000: E/AndroidRuntime(1802):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-25 00:10:46.000: E/AndroidRuntime(1802):     at android.os.Looper.loop(Looper.java:137)
05-25 00:10:46.000: E/AndroidRuntime(1802):     at android.app.ActivityThread.main(ActivityThread.java:5103)
05-25 00:10:46.000: E/AndroidRuntime(1802):     at java.lang.reflect.Method.invokeNative(Native Method)
05-25 00:10:46.000: E/AndroidRuntime(1802):     at java.lang.reflect.Method.invoke(Method.java:525)
05-25 00:10:46.000: E/AndroidRuntime(1802):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
05-25 00:10:46.000: E/AndroidRuntime(1802):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
05-25 00:10:46.000: E/AndroidRuntime(1802):     at dalvik.system.NativeStart.main(Native Method)
05-25 00:10:46.000: E/AndroidRuntime(1802): Caused by: java.lang.NullPointerException
05-25 00:10:46.000: E/AndroidRuntime(1802):     at co.id.adhe.agmv2.MainActivity.onCreate(MainActivity.java:28)
05-25 00:10:46.000: E/AndroidRuntime(1802):     at android.app.Activity.performCreate(Activity.java:5133)
05-25 00:10:46.000: E/AndroidRuntime(1802):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)

任何人都可以解释为什么我会得到例外吗?

2 个答案:

答案 0 :(得分:0)

这是因为findFragmentByIdactivity_main布局中搜索,而地图位于片段的布局fragment_main中。

在片段的onCreateView()方法中移动该段代码:

//...
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
map=((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
//...

请注意,现在您可以通过rootView view访问它:

否则你会再次NullPointerException

因此,请按以下方式更改onCreateView()

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main, container,
            false);
    map=((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    return rootView;
}

答案 1 :(得分:0)

简答:
罪魁祸首是findFragmentById。它返回null,因为尚未加载布局fragment_main

答案很长:
Activity中加载xml后,请务必记住该视图的映射 您收到NullPointerException,因为您正在映射尚未加载的map fragment_main

fragment_view中加载onCreateView后移动代码:

View rootView = inflater.inflate(R.layout.fragment_main, container, false);
map=((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();