0

I am trying to build an app that gets the current location of the device. But it throws nullPointException on:- lat.setText(location.getLatitude()+""); as location object is always null. Please resolve this issue the following code is tested in Android-7.1.1

package in.technomenia.user.test;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    LocationManager locationManager;
    Location location;
    TextView lat, lng;
    Button getlocation;
    private boolean permission_granted = false;

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

        lat = (TextView) findViewById(R.id.lati);
        lng = (TextView) findViewById(R.id.longi);
        getlocation = (Button) findViewById(R.id.get_latlng);


        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locations();

    }

    public void locations() {
        Toast.makeText(getApplicationContext(), "permissions-> "+permission_granted, Toast.LENGTH_SHORT).show();

          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
                    if (permission_granted == false) {
                        requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 19);
                        Toast.makeText(getApplicationContext(), "Requires GPS Permission", Toast.LENGTH_SHORT).show();
                    }else{
                        if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
                            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        else
                            Toast.makeText(getApplicationContext(), "Enable Locaion", Toast.LENGTH_SHORT).show();
                    }
                }

            } else {
                permission_granted= true;
                Toast.makeText(getApplicationContext(), "less than android m", Toast.LENGTH_SHORT).show();

            }



        getlocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {



                if (permission_granted == true) {
                    Toast.makeText(getApplicationContext(), "permission granted", Toast.LENGTH_SHORT).show();
                    lat.setText(location.getLatitude()+"");
                    lng.setText(location.getLongitude()+"");
                }

            }
        });

    }




    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode ==19){
            if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
                permission_granted = true;
                locations();

            }else{
                permission_granted= false;

            }
        }
    }
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115

1 Answers1

1

The getLastKnownLocation() method returns the Location value collected after you call the requestLocationUpdates() method. If you try to get the last location without request an location update the return will be always null.

See this for implementation example
See this if your location still returns null after the location update request

Community
  • 1
  • 1
  • Thank you sir for your support but it is working fine in lollypop without calling requestLocationUpdates(). Then why is it not working in Android-N – Anirban Sarkar Jan 31 '17 at 18:18
  • On the checkSelfPermission() method you verify FINE and COARSE permissions, but on the requestPermissions you only asks for FINE. Try to use: {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_LOCATION_REQUEST_CODE); – Marcelo Ferracin Jan 31 '17 at 18:26