在Java中尝试从另一个类访问变量时获取null

use*_*813 3 java null android

我有两个类,我想将一个(地理点)变量从一个传递到另一个,这样我就可以计算用户当前位置和地理点之间的距离.

长话短说:

我的第一个类名为Session,第二个名为 - 它们位于同一个包中.

我在主类中声明变量为public.在触摸时,我将用户当前位置保存到名为userposition的(公共)地理点变量中.

然后在我使用的第二课

Session pass = new Session();
Run Code Online (Sandbox Code Playgroud)

创建Session的实例.之后我尝试检索用户位置变量:

Geopoint position = pass.userposition;
Run Code Online (Sandbox Code Playgroud)

但它继续返回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();
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

而对于我的计算类:

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;
}
Run Code Online (Sandbox Code Playgroud)

然后我得到空指针异常.

我注意到的(我不太擅长Java所以我会尝试解释)是我可以从主类Session中传递一个变量(我试过它).问题是,为了传递地理点,我需要将变量传递到Session内的Gesture Detection onDoubleTap方法...类似于pass.onDoubleTap.userposition,因为这是我需要的变量,并且在该类中变量不是空的.但是我怎么做呢?

use*_*813 6

我通过声明变量来解决它static,以便它可以在包中的所有类之间共享.