微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

长话短说:

我的第一个类名为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来解决它,以便它可以在包中的所有类之间共享.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐