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

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...