android上的GeoPoint中的空指针异常

时间:2011-05-30 13:13:59

标签: java android

在我的应用程序中,我将列表中的纬度和经度存储为GeoPoint,如下所示:

List<GeoPoint>geo;

这里我将纬度和经度转换为GeoPoint并存储在列表中。

GeoPoint tmp;

new GeoPoint((int) ( 9.909228086471558 * 1E6), (int) ( 78.10081958770752 * 1E6)); 
geo.add(tmp); // i get null pointer exception . Line no:42

logcat的

  05-30 18:33:25.203: ERROR/AndroidRuntime(6363): Caused by: java.lang.NullPointerException
  05-30 18:33:25.203: ERROR/AndroidRuntime(6363):     at net.learn2develop.GoogleMaps.main.onCreate(main.java:42)
  05-30 18:33:25.203: ERROR/AndroidRuntime(6363):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1132)
  05-30 18:33:25.203: ERROR/AndroidRuntime(6363):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2231)

如何清除空指针异常。请帮帮我。

1 个答案:

答案 0 :(得分:3)

// if you don't do this, it could cause your NPE
List<GeoPoint>geo = new ArrayList<GeoPoint>();

此外,这样看起来更好:

GeoPoint tmp = new GeoPoint((int) ( 9.909228086471558 * 1E6), (int) ( 78.10081958770752 * 1E6)); 
geo.add(tmp);

建议不要使用.iterator()

for(GeoPoint point : geo){
    // use the `point` object as you would in a interator
}