Location isalways null

I am building a speedometer application and to do that I am using location getSpeed() command. I have more or less followed this tutorial : https://www.youtube.com/watch?v=ua4jY0lBvCA&list=FLEK0r5UuT755jVeeb70m_tg&index=2&t=0s

The app installs in my phone, and opens, asks for permissions ,etc. but dosen’t update speed. I am guessing that the problem is here because I see “-.- km/hr” in my text view where I want speed:

    @Override
public void onLocationChanged(Location location) {
    //Set up the text view with the location and getSpeed()
    TextView txt = (TextView) this.findViewById(R.id.textView);

    if (location == null) {
        txt.setText("-.- km/hr");
    } else {
        float nCurrentSpeed = location.getSpeed() * 3.6f;
        txt.setText(String.format("%.2f", nCurrentSpeed) + " km/hr");
    }
}

Also, it says “Waiting for GPS signal which I have mentioned here:

    //Custom function for setting up location manager
private void doStuff() {
    LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    if (lm == null) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1000);
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1001);
            return;
        }
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
    } else {
        Toast.makeText(this,"Waiting for GPS signal",Toast.LENGTH_SHORT).show();
    }
}

If you don’t see a problem in the snippets above, here is the full MainActivity.java

//implement LocationListener and apply its methods
public class MainActivity extends AppCompatActivity implements LocationListener {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    //checks permission, goes to onRequestPermissionsResult
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // If permission is not granted,
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1000);
    } else {

        //starts the program if permission is granted
        doStuff();
    }
    this.onLocationChanged(null);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

//Code for checking permissions
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == 1000) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            doStuff();
        }
        finish();
    }

}

@Override
public void onLocationChanged(Location location) {
    //Set up the text view with the location and getSpeed()
    TextView txt = (TextView) this.findViewById(R.id.textView);

    if (location == null) {
        txt.setText("-.- km/hr");
    } else {
        float nCurrentSpeed = location.getSpeed() * 3.6f;
        txt.setText(String.format("%.2f", nCurrentSpeed) + " km/hr");
    }
}

//Custom function for setting up location manager
private void doStuff() {
    LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    if (lm == null) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1000);
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1001);
            return;
        }
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
    } else {
        Toast.makeText(this,"Waiting for GPS signal",Toast.LENGTH_SHORT).show();
    }
}

    @Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}
}

I am a very new programmer, you could say this is my first app I am making, so there’s quite a chance this is a newbie mistake. Please help.

Answer

The only moment when you request locations update is in your doStuff function, when lm==null… You should request them when lm!=null instead.

Leave a Reply

Your email address will not be published. Required fields are marked *