2011-08-04 32 views
2

我有兩個類,我想通過一個觸摸傳遞一個(地理點)變量到另一個,以便我可以計算用戶當前的距離位置和地理位置。當嘗試訪問另一個類的變量時獲得null,在Java中

長話短說:

我的第一類被命名爲會議和第二計算 - 他們是在同一個包。

我在主類中聲明變量是公共的。觸摸時,我將用戶當前位置保存到名爲用戶位置的(公共)地理點變量中。

然後在第二類我用

Session pass = new Session(); 

創建會話的一個實例。這之後,我嘗試檢索userposition變量:

Geopoint position = pass.userposition; 

但它一直返回null,並拋出異常,即使我測試的變量上的主類和偉大工程......我在想什麼?在這裏

會話的主要代碼:

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.maps); 
    // Blah blah blah 

    // And here i declare the GestureDetector...I working with google maps. 
    Gest = new GestureDetector(new SimpleOnGestureListener()); 

    mapView.getOverlays().add(new Overlay() { 
     @Override 
     public boolean onTouchEvent(MotionEvent e, MapView mapView) { 
      Gest.onTouchEvent(e); 
      return super.onTouchEvent(e, mapView); 
     } 
    }); 

    Gest.setOnDoubleTapListener(new OnDoubleTapListener() { 

     @Override 
     public boolean onDoubleTap(MotionEvent e) { 
      // and in here i set the variable which works fine i tested it 
      // in a textView 
      userposition = myLocationOverlay.getMyLocation(); 
     } 
    }); 
} 

而對於我的計算類:

public Overlays(Drawable defaultMarker, Context context) { 
    super(boundCenterBottom(defaultMarker)); 
    mContext = context; 
} 

public void addOverlay(OverlayItem overlay) { 
    mOverlays.add(overlay); 
    populate(); 
} 

@Override 
protected OverlayItem createItem(int i) { 
    // TODO Auto-generated method stub 
    return mOverlays.get(i); 
} 

@Override 
public int size() { 
    // TODO Auto-generated method stub 
    return mOverlays.size(); 
} 

@Override 
public boolean onTap(int index) { 
    // and here i try to get the variable by taping a marker on map (its a 
    // lot of code no need to post works fine too) 

    Session pass = new Session(); 
    Geopoint position = pass.userposition; 
} 

然後我得到空指針異常。

我注意到(我不太擅長Java,所以我會試着解釋一下)是我可以從主類Session傳遞一個類似於整數的變量(我試過了)。問題是要傳遞地理點,我需要將變量傳遞給Session中的手勢檢測onDoubleTap方法...類似於pass.onDoubleTap.userposition,因爲這是我需要的變量,並且在該類中變量不爲null。但我怎麼去做呢?

+0

主要方法是靜態的?所以也許變量是靜態的?你可以發佈代碼嗎? – SnowyTracks

+0

是用戶位置的靜態變量?如果它是一個實例變量,則嘗試使用getter/setter來設置/獲取該值。另外,你可以發佈你的代碼嗎? – sap

+0

這似乎沒有工作....不知何故該變量隱藏在聲明中,其實際價值隱藏到其他類... – user878813

回答

5

我通過聲明變量static來解決它,以便它可以在包中的所有類上共享。

相關問題