注意: - 由於英語不是我的母語,所以對不起我的英語很糟糕,因爲我已經使用谷歌翻譯器。在Firebase數據庫中讀取和寫入數據
我正在開發一個android地圖應用程序,其中用戶可以找到他們朋友的當前位置並存儲當前位置我正在使用FireBase實時數據庫。因此,當用戶點擊查找按鈕時,他們朋友的當前位置將以其用戶名位於地圖上。
但我無法解決一個問題,當我試圖從Firebase中獲取用戶數據時。它沒有以正確的方式反映出來。數據被反映在2條不同的線在日誌中:
- 第1行: - 緯度&經度爲0.0但電子郵件是顯示並在
- 第2行: - 緯度&經度被正確地反映,但電子郵件是空
我不知道如何在一行中得到兩個。我在谷歌上搜索了很多,但失敗了。請幫助我瞭解如何以正確的方式完成。
下面是我的代碼和android studio屏幕截圖。
MainActivity.java
findfriend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, MapsActivity.class));
}
});
final TextView tname;
tname = (TextView) findViewById(R.id.textview);
ref = FirebaseDatabase.getInstance().getReferenceFromUrl("https://ffinder-b4617.firebaseio.com/Email");
mReferece2 = ref.child("email");
mReferece2 = ref.child("location");
proceed.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren()){
UserInformation details = dataSnapshot1.getValue(UserInformation.class);
String email = details.email;
Double lat = details.latitude;
Double lon = details.longitude;
tname.setText(lat+" "+'\n'+lon+'\n'+email);
System.out.println("-->"+ lat+" " + lon+" "+ email);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
MapsActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
Firebase.setAndroidContext(this);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
//Check if Google Play Services Available or not
if (!CheckGooglePlayServices()) {
Log.d("onCreate", "Finishing test case since Google Play Services are not available");
finish();
} else {
Log.d("onCreate", "Google Play Services available.");
}
auth = FirebaseAuth.getInstance();
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
FirebaseDatabase.getInstance().getReference().child("Location");
}
@Override
public void onLocationChanged(Location location) {
Log.d("onLocationChanged", "entered");
mLastLocation = location;
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = new Date();
mLastUpdateTime = ((dateFormat.format(date).toString()));
saveToFirebase();
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.draggable(true);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
Toast.makeText(MapsActivity.this,"Your Current Location", Toast.LENGTH_LONG).show();
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
Log.d("onLocationChanged", "Removing Location Updates");
}
}
public void saveToFirebase() {
Firebase firebase = new Firebase("https://ffinder-b4617.firebaseio.com").child("Email").child("location");
Map mLoactions = new HashMap();
mLoactions.put("timestamp",mLastUpdateTime);
mLoactions.put("latitude", mLastLocation.getLatitude());
mLoactions.put("longitude", mLastLocation.getLongitude());
firebase.setValue(mLoactions);
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
@Override
public boolean onMarkerClick(Marker marker) {
marker.setDraggable(true);
return false;
}
@Override
public void onMarkerDragStart(Marker marker) {}
@Override
public void onMarkerDrag(Marker marker) {}
@Override
public void onMarkerDragEnd(Marker marker) {
end_latitude = marker.getPosition().latitude;
end_longitude = marker.getPosition().longitude;
Log.d("end_lat",""+end_latitude);
Log.d("end_lng",""+end_longitude);
}
}
Login.class
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Firebase.setAndroidContext(this);
auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null){
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnSignup = (Button) findViewById(R.id.btn_signup);
btnLogin = (Button) findViewById(R.id.btn_login);
btnReset = (Button) findViewById(R.id.btn_reset_password);
auth = FirebaseAuth.getInstance();
btnSignup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, SignupActivity.class));
}
});
btnReset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class));
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
//authenticate user
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
// there was an error
if (password.length() < 6) {
inputPassword.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
});
}
});
}
public void userLoginInfo(){
String email = inputEmail.getText().toString();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Email").push();
String userId = mDatabase.child("email").getKey();
mDatabase.child(userId).setValue(email);
}
}
個UserInformation.class
public class UserInformation {
public String email;
public double latitude;
public double longitude;
public UserInformation() {
}
public UserInformation(String email, double latitude, double longitude) {
this.email = email;
this.latitude = latitude;
this.longitude = longitude;
}
public String getEmail() {
return email;
}
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
}
火力地堡數據庫截圖 Android Studio中的日誌截圖
感謝您的回覆,它幫助我組織單親「電子郵件」下的數據,但現在我沒有在Firebase中獲取用戶的登錄電子郵件。 –
它是未來像這樣如下: - 。 ffinder-b4617 電子郵件 郵件: 「電子郵件」 緯度:31.5037501 經度:74.3502436 –
你可以用'FirebaseAuth.getInstance()getCurrentUser()getEmail( )'以獲得當前用戶的電子郵件地址,因此您可以在'saveToFirebase()'方法中使用它。這會起作用嗎? – Grimthorr