2011-01-09 68 views
1

我試圖通過保存應用程序上下文的位置,所以我做了以下內容:的Android getApplicationContext NullPointerException異常

對myApp類:

進口android.app.Application;

import com.google.android.maps.GeoPoint;

public class myApp extends Application { 

    private GeoPoint Tunis = new GeoPoint(microdegrees(36.827589),microdegrees(10.171165)); 
    private GeoPoint myLocation=Tunis; 

    public GeoPoint getMyLocation(){ 
    return myLocation; 
    } 
    public void setMyLocation(GeoPoint s){ 
    myLocation = s; 
    } 
    private int microdegrees(double value){ 
    return (int)(value*1000000); 
    } 

} 

我的清單:

<application android:icon="@drawable/icon" android:label="@string/app_name" android:name=".myApp"> 
     <uses-library android:name="com.google.android.maps"/> 
     <activity android:name=".Main" 
        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> 

,在我的主要活動我這樣做:

myApp appState = ((myApp)getApplicationContext()); 

,這將導致一個NullPointerException當我啓動應用程序:(可以請你告訴我爲什麼會發生這種異常?我認爲在myApp類中,我將MyLocation初始化爲現有的GeoPoint?

個謝謝,

+1

沒有更多的源代碼和完整的堆棧跟蹤,沒有人可以幫助你。 – CommonsWare 2011-01-09 13:36:08

回答

1

我的打擾對不起,我解決了這個由: 1添加構造函數來對myApp:

public class myApp extends Application { 

    public GeoPoint Tunis = new GeoPoint(microdegrees(36.827589),microdegrees(10.171165)); 
    public GeoPoint myLocation; 

    public myApp(){ 
     super(); 
     myLocation=Tunis; 
    } 
    public GeoPoint getMyLocation(){ 
    return myLocation; 
    } 
    public void setMyLocation(GeoPoint s){ 
    myLocation = s; 
    } 
    private int microdegrees(double value){ 
     return (int)(value*1000000); 
    } 
} 

2-聲明在我的主要活動如下中的onCreate無效

appState = ((myApp)getApplicationContext()); 

這樣的:

public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     GeoPoint Tunis = new GeoPoint(microdegrees(36.827589),microdegrees(10.171165)); 
     MyMap=(MapView)findViewById(R.id.MyGMap); 
     MyMap.setBuiltInZoomControls(true); 
     MyController=MyMap.getController(); 
     MyController.setZoom(12); 
     MyController.setCenter(Tunis); 
     appState = ((myApp)getApplicationContext()); 

感謝

+10

更確切地說:問題是在創建Activity之前(即在調用onCreate之前)無法訪問getApplicationContext()。 – MasterScrat 2011-08-06 22:26:44

相關問題