I have this code and it takes the location where the user pressed on the Google Map and it takes the longitude and latitude and I put the value in two variables. But it still gives me a NullPointerException. Why ?
And I did try the code before and it did work.
public boolean onTouchEvent(MotionEvent e, MapView mv) {
int i = e.getAction();
MainActivity test = new MainActivity();
switch(i) {
case MotionEvent.ACTION_UP:
// When your finger stop touching the screen
Log.d("ACTION UP", "Finger was removed from screen");
lng = (int) e.getX();
lat = (int) e.getY();
test.placePinFromTouch(lat, lng); // This is the NullPointerException line
break;
}
Where I commented in the code above is where I get the NullPointerException, but I wonder why in this touchEvent I’m getting this.
Your
testobject certainly isn’t null. However, we need to know what types lng and lat are. Sure, you are casting what you pass into them as an int, but java has a habit of autoboxing data. It could be the case that they are null. If they are of type int, then they are not null. However, if they are of type Integer, they might be.Finally we need to know if
placePinFromTouchwill explicitly throw a null pointer exception, especially on unusual values oflatandlng. Yes, that is not the appropriate thing to do there, but I’ve seen worse things done with exceptions.