Android getApplicationContext Nullpointerexception

时间:2011-01-09 12:30:33

标签: android nullpointerexception

我正在尝试通过应用程序上下文保存位置,因此我执行了以下操作:

myApp课程:

import android.app.Application;

导入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 个答案:

答案 0 :(得分: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 void

中的主要活动中声明以下内容
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());

谢谢