Domagoj Lipušić Domagoj Lipušić - 1 month ago 15
Android Question

My app crashes when I press my Get Location button

I copied code to get coordinates in my app from here http://rdcworld-android.blogspot.hr/2012/01/get-current-location-coordinates-city.html
anyway when I press "Get Location" button, app crashes and exits.

MainActivity.java

package com.lipa.flashlight;

import android.*;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.ParcelFileDescriptor;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.view.View.OnClickListener;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class Main2Activity extends AppCompatActivity implements OnClickListener {


private LocationManager locationManager = null;
private LocationListener locationListener = null;

private Button location = null;
private EditText editLocation = null;
private ProgressBar pb =null;

private static final String TAG = "Debug";
private Boolean flag = false;

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

pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);

editLocation = (EditText) findViewById(R.id.editTextLocation);
location = (Button) findViewById(R.id.location);
location.setOnClickListener(this);
}




@Override
public void onClick(View v) {
flag = displayGpsStatus();
if (flag) {
Log.v(TAG, "onClick");
editLocation.setText("Please! move your device to" +
" see the changes in coordinates." + "\nWait...");

pb.setVisibility(View.VISIBLE);
locationListener = new MyLocationListener();

if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {

return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);

} else {
alertbox("GPS STATUS!!", "Your GPS is: OFF");
}
}

private Boolean displayGpsStatus(){
ContentResolver contentResolver = getBaseContext().getContentResolver();
boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(contentResolver, LocationManager.GPS_PROVIDER);
if(gpsStatus){
return true;

}else{
return false;
}

}

protected void alertbox(String title, String mymessage){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your Device's GPS is disabled")
.setCancelable(false)
.setTitle("** Gps Status **")
.setPositiveButton("Gps On", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id) {
Intent myIntent = new Intent(
Settings.ACTION_SECURITY_SETTINGS);
startActivity(myIntent);
dialog.cancel();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}

private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location loc){


editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(),"Location changed: Lat: "+
loc.getLatitude()+" Lng: " + loc.getLongitude(), Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " +loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
Log.v(TAG, latitude);

String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(),
Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc
.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}

String s = longitude+"\n"+latitude +
"\n\nMy Currrent City is: "+cityName;
editLocation.setText(s);

}

@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}

@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}

@Override
public void onStatusChanged(String provider,
int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}


XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Get Current Location and City Name"
android:layout_weight="0.20"
android:gravity="center"
android:textSize="20sp" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.33"
android:id="@+id/editTextLocation"
android:editable="false">
<requestFocus></requestFocus>
</EditText>
<LinearLayout
android:id="@+id/layButtonH"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:gravity="center"
android:layout_weight="0.15">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Location"
android:id="@+id/location"></Button>
</LinearLayout>
<LinearLayout
android:id="@+id/layloadingH"
android:layout_height="wrap_content"
android:layout_weight="0.20"
android:layout_width="fill_parent"
android:gravity="center">
<ProgressBar
android:layout_width="wrap_content"
android:id="@+id/progressBar1"
android:layout_height="wrap_content"></ProgressBar>
</LinearLayout>
</LinearLayout>

Answer
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
    ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED) {

    return;
}

Does the app has permission ? if not, requestLocationUpdates will not be reached in your code.

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);

The minDistance parameter can also be used to control the frequency of location updates. If it is greater than 0 then the location provider will only send your application an update when the location has changed by at least minDistance meters, AND at least minTime milliseconds have passed

Consider this part at least minDistance meters, AND at least minTime milliseconds have passed from LocationManager documentation