首页 > 解决方案 > 用户的位置始终返回 null,尽管已授予权限且 GPS 已打开

问题描述

我试图让我的应用程序获取用户的位置并将其保存到 GeoFire,但它总是只返回 null。我知道有很多这样的问题,但相信我,我已经尝试了很多。

似乎事情在 getLastKnownLocation 中,但我不知道如何更改它以返回当前位置。

实际上,我只需要在用户发布内容时保存位置,因此无需继续跟踪它。

这是我现在拥有的整个活动的代码

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;
}

}

标签: javaandroidgpslocationgeofire

解决方案


getLastLocation()经常退货null。您需要对传递给您的位置做出反应onLocationChanged()LocationListener对其进行处理。现在,您只是设置一个字段,这很好,但不会更新您的 UI、创建您的Post.


推荐阅读