位置(经度,纬度)返回0

时间:2016-10-10 18:39:55

标签: android google-maps firebase google-api firebase-realtime-database

我尝试获取当前位置的经度和纬度,并将其保存在Firebase数据库中。源代码工作正常,但经度和纬度保存为0.0

this is how it looks like in the database.

如何修复此问题并获取正确的当前位置?不要介意几十个导入类,我还没有删除任何东西。

如果这是一个重复的问题,我真的很抱歉。

public class Register extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
    EditText edtemail, edtpass, edtnumber;
    Button btnRegister, btnLogin, forgotpwdbtn;
    private FirebaseAuth auth;
    private DatabaseReference mDatabase;


    private GoogleApiClient googleApiClient;
    private Location location;
    private double longitude;
    private double latitude;
    String mUserId;


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


        btnRegister = (Button) findViewById(R.id.btnRegister);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        forgotpwdbtn = (Button) findViewById(R.id.forgotpwdbtn);

        btnRegister.setOnClickListener(this);
        btnLogin.setOnClickListener(this);
        forgotpwdbtn.setOnClickListener(this);
        auth = FirebaseAuth.getInstance();


        mDatabase = FirebaseDatabase.getInstance().getReference();
        mUserId = FirebaseAuth.getInstance().getCurrentUser().getUid();

        edtemail = (EditText) findViewById(R.id.edtemail);
        edtpass = (EditText) findViewById(R.id.edtpass);
        edtnumber = (EditText) findViewById(R.id.edtnumber);


    }


    public void onClick(View view) {

        switch (view.getId()) {

            case R.id.forgotpwdbtn:
                Intent passwordIntent = new Intent(Register.this, ForgotPasswordActivity.class);
                startActivity(passwordIntent);
                break;
            case R.id.btnLogin:
                Intent intent = new Intent(Register.this, LoginActivity.class);
                startActivity(intent);
                break;
            case R.id.btnRegister:
                googleApiClient = new GoogleApiClient.Builder(this)
                        .addConnectionCallbacks(this)
                        .addOnConnectionFailedListener(this)
                        .addApi(LocationServices.API)
                        .build();

                final String key = mDatabase.child("data").push().getKey();
                final String email = edtemail.getText().toString().trim();
                final String password = edtpass.getText().toString().trim();
                final String number = edtnumber.getText().toString().trim();
                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) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
                location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
                if (location != null) {
                    //Getting longitude and latitude
                    longitude = location.getLongitude();
                    latitude = location.getLatitude();
                }

                String lon = String.valueOf(longitude);
                String lat = String.valueOf(latitude);

                Item newItem = new Item(email, password, number, lon, lat);
                Map<String, Object> itemValues = newItem.toMap();
                Map<String, Object> childUpdates = new HashMap<>();
                childUpdates.put("/data/" + mUserId + "/" + key, itemValues);
                mDatabase.updateChildren(childUpdates);

                    auth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(Register.this, new OnCompleteListener<AuthResult>() {


                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {

                            if (task.isSuccessful()) {

                                Toast.makeText(Register.this, "Registration success", Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(Register.this, LoginActivity.class);
                                startActivity(intent);

                            } else {
                                Toast.makeText(Register.this, "Registration failed." + task.getException(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                    break;
                }
        }

    @Override
    public void onConnected(@Nullable Bundle bundle) {

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }
}

1 个答案:

答案 0 :(得分:1)

您没有连接到GoogleApiClient。使用onCreate方法创建GoogleApiClient对象。覆盖另外两种方法onStartonStop。在onStart方法中,通过调用googleapiclient.connect()连接到GoogleApiClient。在onStop方法中,通过调用if(googleapiclient.isConnected()) { googleapiclient.disconnect() }来断开客户端。