[英]Getting null when trying to access variables from another class, in Java
我有兩個類,我想將一個(地理點)變量從一個傳遞到另一個,這樣我就可以計算用戶當前位置和地理點之間的距離。
長話短說:
我的第一個類名為Session,第二個名為 - 它們位於同一個包中。
我在主類中聲明變量為public。 在觸摸時,我將用戶當前位置保存到名為userposition的(公共)地理點變量中。
然后在我使用的第二課
Session pass = new Session();
創建Session的實例。 之后我嘗試檢索用戶位置變量:
Geopoint position = pass.userposition;
但它繼續返回null並拋出異常,即使我在主類上測試變量並且工作得很好......我在這里缺少什么?
Session的主要代碼是:
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內的Gesture Detection onDoubleTap方法...類似於pass.onDoubleTap.userposition,因為這是我需要的變量,並且在該類中變量不是空的。 但是我怎么做呢?
我通過聲明變量static
來解決它,以便它可以在包中的所有類之間共享。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.