I want to show "hello" message on the screen but my app is not working.
What is causing "java.lang.NullPointerException"?
the debugger says value of longitude is null. Even if that is the case, shouldn’t my "hello" message still appear?
I have the following code:
package autogenie.maptrial;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Location location;
private Double latitude, longitude;
private LocationManager locationManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude=location.getLongitude();
latitude=location.getLatitude();
Context context = getApplicationContext();
String s="hello";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context,s, duration);
toast.show();
}
}
What debugger shows:
After that it crashes.