每次将位置更新存储在Firebase中时,为什么我的位置数据会创建唯一的ID字段

时间:2017-06-12 19:15:32

标签: android firebase firebase-realtime-database firebase-authentication

我已经通过FusedLocation创建了一个位置监听器。每次我记录的auth用户开始跟踪他们的位置时,该位置都是在currentuser user-id下写入的,但它会为在数据库中写入的每个位置添加不同的唯一ID。我需要那个地点'使用我当前的登录用户说明('名称''类型')在同一树中,每当我的当前用户有位置更改数据时,它将覆盖&中的数据#39;纬度'和经度'。我如何重建我的代码?

这是我的数据库截图 my firebase database

这是我的location.class

import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;


/**
 * Created by AKMAL NIZAR ROSLE on 12/6/2017.
 */

public class DriverActivity extends AppCompatActivity implements
    LocationListener,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener {

private static final String TAG = "DriverActivity";
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;

private FirebaseAuth auth;
private DatabaseReference databaseReference;


Button btnFusedLocation;
TextView tvLocation, textViewUser;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
String mLastUpdateTime;

protected void createLocationRequest() {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(INTERVAL);
    mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    auth = FirebaseAuth.getInstance();

    //get current user
    if (auth.getCurrentUser() == null) {
        startActivity(new Intent(DriverActivity.this, LoginActivity.class));
        finish();
    }

    databaseReference = FirebaseDatabase.getInstance().getReference();

    Log.d(TAG, "onCreate ...............................");
    //show error dialog if GoolglePlayServices not available
    if (!isGooglePlayServicesAvailable()) {
        finish();
    }
    createLocationRequest();
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

    setContentView(R.layout.activity_driver);

    FirebaseUser user = auth.getCurrentUser();

    textViewUser = (TextView) findViewById(R.id.textViewUser);

    textViewUser.setText("Welcome"+" "+user.getEmail());

    tvLocation = (TextView) findViewById(R.id.tvLocation);

    btnFusedLocation = (Button) findViewById(R.id.btnShowLocation);
    btnFusedLocation.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            updateUI();
        }
    });

}

@Override
public void onStart() {
    super.onStart();
    Log.d(TAG, "onStart fired ..............");
    mGoogleApiClient.connect();
}

@Override
public void onStop() {
    super.onStop();
    Log.d(TAG, "onStop fired ..............");
    mGoogleApiClient.disconnect();
    Log.d(TAG, "isConnected ...............: " + mGoogleApiClient.isConnected());
}

private boolean isGooglePlayServicesAvailable() {
    final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
    int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
    if (resultCode != ConnectionResult.SUCCESS) {
        if (apiAvailability.isUserResolvableError(resultCode)) {
            apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
                    .show();
        } else {
            Log.d(TAG, "This device is not supported.");
        }
        return false;
    }
    return true;
}

@Override
public void onConnected(Bundle bundle) {
    Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
    startLocationUpdates();
}

protected void startLocationUpdates() {
    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;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(
            mGoogleApiClient, mLocationRequest, this);
    Log.d(TAG, "Location update started ..............: ");
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Log.d(TAG, "Connection failed: " + connectionResult.toString());
}

@Override
public void onLocationChanged(Location location) {
    Log.d(TAG, "Firing onLocationChanged..............................................");
    mCurrentLocation = location;
    mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
    saveToFirebase();
    updateUI();
}


private void saveToFirebase() {
    FirebaseUser user = auth.getCurrentUser();

    Map mLocations = new HashMap();
    Map  mCoordinate = new HashMap();
    mCoordinate.put("latitude", mCurrentLocation.getLatitude());
    mCoordinate.put("longitude", mCurrentLocation.getLongitude());
    mLocations.put("location", mCoordinate);
    databaseReference.child(user.getUid()).push().setValue(mLocations);
}


private void updateUI() {
    Log.d(TAG, "UI update initiated .............");
    if (null != mCurrentLocation) {
        String lat = String.valueOf(mCurrentLocation.getLatitude());
        String lng = String.valueOf(mCurrentLocation.getLongitude());
        tvLocation.setText("At Time: " + mLastUpdateTime + "\n" +
                "Latitude: " + lat + "\n" +
                "Longitude: " + lng + "\n" +
                "Accuracy: " + mCurrentLocation.getAccuracy() + "\n" +
                "Provider: " + mCurrentLocation.getProvider());
    } else {
        Log.d(TAG, "location is null ...............");
    }
}

@Override
protected void onPause() {
    super.onPause();
    stopLocationUpdates();
}

protected void stopLocationUpdates() {
    LocationServices.FusedLocationApi.removeLocationUpdates(
            mGoogleApiClient, this);
    Log.d(TAG, "Location update stopped .......................");
}

@Override
public void onResume() {
    super.onResume();
    if (mGoogleApiClient.isConnected()) {
        startLocationUpdates();
        Log.d(TAG, "Location update resumed .....................");
    }
}

}

1 个答案:

答案 0 :(得分:0)

private void saveToFirebase() {
    FirebaseUser user = auth.getCurrentUser();

    Map mLocations = new HashMap();
    Map  mCoordinate = new HashMap();
    mCoordinate.put("latitude", mCurrentLocation.getLatitude());
    mCoordinate.put("longitude", mCurrentLocation.getLongitude());
    mLocations.put("location", mCoordinate);
    databaseReference.child(user.getUid()).push().setValue(mLocations);
}

只需删除setValue数据库操作中的 push()方法:

private void saveToFirebase() {
    FirebaseUser user = auth.getCurrentUser();
    Map  mCoordinate = new HashMap();
    mCoordinate.put("latitude", mCurrentLocation.getLatitude());
    mCoordinate.put("longitude", mCurrentLocation.getLongitude());
    databaseReference.child(user.getUid() + "/location").setValue(mCoordinate);
}

push()方法生成一个新节点,其中包含数据库引用的唯一键。