2011-01-09 53 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

相关问题