2014-05-24 174 views
1

我開發了有一個按鈕,看看城市的具體座標的簡單應用谷歌地圖V2 ..mainactivity - 顯示java.lang.NullPointerException

我只是想設置按鈕來查看城市

這是我mainactivity:

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

} 
} 

我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" /> 

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

任何人都可以解釋爲什麼我得到異常?

+0

參見:http://stackoverflow.com/questions/23653778/nullpointerexception-accessing-views-in-oncreate – laalto

+0

見我的回答@ Ade06 – Lal

+0

我很驚訝這個代碼有效。您正在使用包含另一個片段的PlaceholderFragment充氣佈局。我在我的電腦上測試過它,它工作。奇怪的是,我已經準備了許多關於築巢碎片的帖子,說這是不可能的。 http://developer.android.com/about/versions/android-4.2.html#NestedFragments –

回答

0

這是因爲findFragmentById搜索activity_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; 
} 
+0

終於應用程序在模擬器中運行良好,感謝@ Lal的解釋,對不起,如果有點小事.. –

0

簡短的回答:
罪魁禍首是findFragmentById。它返回null,因爲佈局fragment_main尚未加載。

龍答:
永遠記住它在Activity被加載後,地圖視圖的XML。
您正在獲得NullPointerException,因爲您正在映射尚未加載的的map

fragment_view加載後移動代碼onCreateView

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

應用程序runinng以及模擬器謝謝@ aashish解釋] –

+0

接受並且贊成這個答案,如果它的工作,因爲它會幫助其他用戶。 –

+0

頂部的鏈接(「這個問題在這裏有答案」)是誤導性的。所提到的qs是相似的,但不相同。對於這個問題至少有兩種解決方案,其中之一在提及的答案中沒有提及。如果答案再次啓用,我可以提供他們兩個。 –

相關問題