Getting null when trying to access variables from another class, in Java
I have two classes and I want to pass a (geo-point) variable on touch from one to the other, so that I can calculate the distance between user current location and the geo-point.
Long story short:
My first class is named Session and the second Calculation - they are in the same package.
I declare the variables as public in the main class. On touch, I save the users current location into the (public) geo-point variable called userposition.
Then in the second class I use
Session pass = new Session();
to create an instance of the Session. After which I try to retrieve the userposition variable:
Geopoint position = pass.userposition;
But it keeps returning null and throws exception even if I tested the variable on the main class and works great ... What am I missing here??
The main code for Session is:
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();
}
});
}
And for my Calculation class:
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) {
// T开发者_Go百科ODO 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;
}
And then I get the null pointer exception.
What I noticed (I'm not so good at Java so I will try to explain) is that I can pass a variable like an integer (I tried it) from the main class Session. The thing is that to pass the geo-point, I need to pass the variable into the Gesture Detection onDoubleTap method inside the Session ... something like pass.onDoubleTap.userposition because that is the variable I need, and in that class the variable is not null. But how I go about doing that??
I solved it by declaring the variable static
, so that it can be shared across all classes in the package.
精彩评论