-2

what i am trying to do is create an instance of class "location" and calling methods-"getLongitude()" and " getLatitude()" to get latitude and longitude and show them using "toast" but i am getting errors.

Here is my code and the errors:

CODE

 package autogenie.maptrial;

 import android.content.Context;
 import android.location.Location;
 import android.support.v7.app.AppCompatActivity;
 import android.os.Bundle;
 import android.widget.Toast;

  public class MainActivity extends AppCompatActivity {
Location loc;
Double lon,lat;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    lon=loc.getLongitude();
    lat=loc.getLatitude();



    Context context = getApplicationContext();
    String s=String.valueOf(lon)+"  "+String.valueOf(lat);
    int duration = Toast.LENGTH_LONG;

    Toast toast = Toast.makeText(context,s, duration);
    toast.show();


}
}  

THE ERRORS:

java.lang.RuntimeException: Unable to start activity ComponentInfo{autogenie.maptrial/autogenie.maptrial.MainActivity}: java.lang.NullPointerException

and

java.lang.NullPointerException at autogenie.maptrial.MainActivity.onCreate

Haseeb Anser
  • 494
  • 1
  • 5
  • 19
mobimedia
  • 25
  • 5

2 Answers2

0

In that code you only defines object of Location that will return null because you have initiate it using

final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

For more information refer this How to get Latitude and Longitude of the mobile device in android?

Community
  • 1
  • 1
Mahesh Giri
  • 1,810
  • 19
  • 27
0

Update This:

@Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                loc = new Location("");

                lon=loc.getLongitude();
                lat=loc.getLatitude();


                Context context = getApplicationContext();
                String s=String.valueOf(lon)+"  "+String.valueOf(lat);
                int duration = Toast.LENGTH_LONG;

                Toast toast = Toast.makeText(context,s, duration);
                toast.show();


            } 
Suhas Bachewar
  • 1,230
  • 7
  • 21