简体   繁体   中英

User's location always returns null although the permission is given and GPS is turned on

I'm trying to make my app take user's location and save it to GeoFire but it always just returns null. I know there are lots of questions like this, but trust me I've tried a lot.

It seems like the thing is in getLastKnownLocation but I don't know how to change it to return current location.

Actually I need to save location only when user posts something so there is no need in keeping tracking it.

Here is the code of the whole activity which I have now

public class GetHelpActivity extends AppCompatActivity {
Button postBT;
EditText editHeading;
EditText editInfo;
EditText editAddress;
Location mLocation;
protected Context context;
double latitude;
double longitude;
Post post;
DatabaseReference myDB;
FirebaseUser currentUser;
FirebaseAuth mAuth;
String postID;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_get_help);

    postBT = findViewById(R.id.postBT);
    editHeading = findViewById(R.id.editHeading);
    editInfo = findViewById(R.id.editInfo);
    editAddress = findViewById(R.id.editAddress);

    final LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            mLocation = location;
            Log.d("Location Changes", location.toString());
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            Log.d("Status Changed", String.valueOf(status));
        }

        @Override
        public void onProviderEnabled(String provider) {
            Log.d("Provider Enabled", provider);
        }

        @Override
        public void onProviderDisabled(String provider) {
            Log.d("Provider Disabled", provider);
        }
    };

    final Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);

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

    final Looper looper = null;


    myDB = FirebaseDatabase.getInstance().getReference();
    final GeoFire geoFire = new GeoFire(myDB.child("postLocation"));

    postID = myDB.child("posts").push().getKey();

    mAuth = FirebaseAuth.getInstance();
    currentUser = mAuth.getCurrentUser();

    final String userID = currentUser.getUid();

    postBT.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String heading = editHeading.getText().toString();
            String info = editInfo.getText().toString();
            String address = editAddress.getText().toString();


            if (ActivityCompat.checkSelfPermission(GetHelpActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(GetHelpActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
                return;
            }

            locationManager.requestSingleUpdate(criteria, locationListener, looper);
            mLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

            if (mLocation == null) {
                Toast.makeText(GetHelpActivity.this, "Location is null", Toast.LENGTH_LONG).show();
                return;
            }

            if (valid(heading, info, address)) {

                post = new Post(userID, heading, info, address, latitude, longitude);

                latitude = mLocation.getLatitude();
                longitude = mLocation.getLongitude();

                myDB.child("posts").push().setValue(post);

                String key = geoFire.getDatabaseReference().push().getKey();

                geoFire.setLocation(key, new GeoLocation(latitude, longitude));
            }
        }
    });
}

private boolean valid(String heading, String info, String address) {
    if (heading.length() == 0) {
        Toast.makeText(GetHelpActivity.this, "Please, fill in the heading of your post", Toast.LENGTH_LONG).show();
        return false;
    }
    if (heading.length() > 25) {
        Toast.makeText(GetHelpActivity.this, "Your heading should be shorter (up to 25 characters)", Toast.LENGTH_LONG).show();
        return false;
    }
    if (info.length() == 0) {
        Toast.makeText(GetHelpActivity.this, "Please, fill in the info about your post, so volunteers will be able to understand it clearly", Toast.LENGTH_LONG).show();
        return false;
    }
    if (info.length() > 300) {
        Toast.makeText(GetHelpActivity.this, "Post's info should be no longer than 300 characters", Toast.LENGTH_LONG).show();
        return false;
    }
    if (address.length() == 0) {
        Toast.makeText(GetHelpActivity.this, "Please, fill in the address, so volunteer will be able to find you quickly", Toast.LENGTH_LONG).show();
        return false;
    }
    return true;
}

}

getLastLocation() frequently returns null . You need to react to the location being handed to your onLocationChanged() in your LocationListener and do something with it. Right now, you are just setting a field, which is fine but is not going to update your UI, create your Post , or anything else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM