0

I'm trying to create a small app which can locate the x and y coordinates the user is currently at. The problem is I just keep getting a null pointer exception at line 143.

double lon = loc.getLongitude();

I think my getLastKnownLocation() is returning null. I'm running it through a virtual device. Code below.

package com.team23.profilebuilder;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.util.Log;
import android.location.LocationManager;

import java.util.List;

public class FindLocationActivity extends CustomActivity
{

// Buttons to be used
private Button locButton, saveButton;
// Textview to be displayed / used
private TextView locText, latText, longText, latVal, longVal;
// Location objects
private LocationManager locMan;
private LocationListener locLis;
private Location loc;

private static final String TAG = "FindLocationActivity";


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

    // Initialise all elements
    initialiseUIElements();
    initialiseOtherElements();

    // Set button listeners
    setListeners();
}

private void initialiseUIElements()
{
    locButton = (Button) findViewById(R.id.locButton);
    saveButton = (Button) findViewById(R.id.saveButton);
    locText = (TextView) findViewById(R.id.locText);
    latText = (TextView) findViewById(R.id.latText);
    longText = (TextView) findViewById(R.id.longText);
    latVal = (TextView) findViewById(R.id.latVal);
    longVal = (TextView) findViewById(R.id.longVal);
}

private void initialiseOtherElements()
{
    // Acquire a reference to the system LocationManager
    locMan = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    // Define a listener which responds to location updates
    locLis = new LocationListener()
    {
        // Method called when a new location is found
        @Override
        public void onLocationChanged(Location location)
        {
            loc = location;
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle)
        {

        }

        @Override
        public void onProviderEnabled(String s)
        {

        }

        @Override
        public void onProviderDisabled(String s)
        {

        }
    };
    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;
    }
    // Register the listener with Location Manager to receive updates
    locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locLis);
}

private void setListeners()
{
    locButton.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            findLocation();
        }
    });
    saveButton.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            saveLocation();
        }
    });
}

private void findLocation()
{
    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;
    }
    // Retrieve last known location
    loc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

    // Retrieve values
    double lon = loc.getLongitude();
    double lat = loc.getLatitude();

    // Set TextView values
    longVal.setText(Double.toString(lon));
    latVal.setText(Double.toString(lat));
}

private void saveLocation()
{
    Log.v(TAG, "SaveLocation Method");
}
}
Ankita Shah
  • 1,866
  • 16
  • 31
  • Check null like this,if(location!=null){ double latitude = location.getLatitude(); double longitude = location.getLongitude(); } – Mujammil Ahamed Nov 14 '16 at 11:56
  • The problem is that it IS null, I want it to actually find the location, i already know it is null because that's what is causing my exception. – user7085794 Nov 14 '16 at 11:57
  • Follow this tutorial http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/ – Mujammil Ahamed Nov 14 '16 at 11:58
  • I've followed a few tutorials which has led me to this point but I'm looking for specific help now regarding my issues, I've read 3-4 different tutorials which have all explained it differently, I've been stuck with this for days. – user7085794 Nov 14 '16 at 12:01
  • The Android Hive example is bad as is explained [here](http://gabesechansoftware.com/location-tracking/). And the latest location can be null as is explained [here](http://stackoverflow.com/questions/10689372/android-getlastknownlocation-returns-null#answer-10689593) and [here](http://stackoverflow.com/questions/30664878/getlastknownlocation-returns-null). And especially on a virtual device it will be null unless that virtual device has some sort of a mock location provider. – Markus Kauppinen Nov 14 '16 at 12:15

1 Answers1

0

I tested the Below source code without runtime permission with target 22, it works fine for me.

Check null for Location,and check the GPS is turned On in your device..

package com.team23.profilebuilder;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.util.Log;
import android.location.LocationManager;

import java.util.List;

public class FindLocationActivity extends CustomActivity
{

// Buttons to be used
private Button locButton, saveButton;
// Textview to be displayed / used
private TextView locText, latText, longText, latVal, longVal;
// Location objects
private LocationManager locMan;
private LocationListener locLis;
private Location loc;

private static final String TAG = "FindLocationActivity";


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

    // Initialise all elements
    initialiseUIElements();
    initialiseOtherElements();

    // Set button listeners
    setListeners();
}

private void initialiseUIElements()
{
    locButton = (Button) findViewById(R.id.locButton);
    saveButton = (Button) findViewById(R.id.saveButton);
    locText = (TextView) findViewById(R.id.locText);
    latText = (TextView) findViewById(R.id.latText);
    longText = (TextView) findViewById(R.id.longText);
    latVal = (TextView) findViewById(R.id.latVal);
    longVal = (TextView) findViewById(R.id.longVal);
}

private void initialiseOtherElements()
{
    // Acquire a reference to the system LocationManager
    locMan = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    // Define a listener which responds to location updates
    locLis = new LocationListener()
    {
        // Method called when a new location is found
        @Override
        public void onLocationChanged(Location location)
        {
            loc = location;
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle)
        {

        }

        @Override
        public void onProviderEnabled(String s)
        {

        }

        @Override
        public void onProviderDisabled(String s)
        {

        }
    };
    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;
    }
    // Register the listener with Location Manager to receive updates
    locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locLis);
}

private void setListeners()
{
    locButton.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            findLocation();
        }
    });
    saveButton.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            saveLocation();
        }
    });
}

private void findLocation()
{
    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;
    }
    // Retrieve last known location
    loc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

   if (loc!=null) {
        // Retrieve values
        double lon = loc.getLongitude();
        double lat = loc.getLatitude();
        // Set TextView values
        longVal.setText(Double.toString(lon));
        latVal.setText(Double.toString(lat));
    }
}

private void saveLocation()
{
    Log.v(TAG, "SaveLocation Method");
}
}
Mujammil Ahamed
  • 1,454
  • 4
  • 24
  • 50