Android中实现实时经纬度存储至Firebase并支持后续检索
Hey there! Let's get your latitude and longitude saved to Firebase Realtime Database and set up a way to retrieve that data later. I'll walk you through modifying your existing code step by step.
Step 1: Firebase Setup (Prerequisite)
First, make sure you've got Firebase configured in your project:
- Add Firebase Realtime Database dependencies to your app-level
build.gradlefile (use the latest available versions):implementation 'com.google.firebase:firebase-database:20.3.0' implementation 'com.google.firebase:firebase-core:21.1.1' - Connect your app to Firebase via the Firebase Console, and adjust your Realtime Database rules (for testing, you can use temporary public rules, but lock them down for production).
Step 2: Modified MapsActivity Code
Here's the updated code that handles saving location to Firebase and includes a method to retrieve stored data later:
import android.Manifest; import android.content.pm.PackageManager; import android.location.Location; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationServices; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; public class MapsActivity extends AppCompatActivity { private FusedLocationProviderClient client; private DatabaseReference mDatabase; // Firebase Database reference private EditText locationNameEt; // Renamed for better readability @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Initialize Firebase Database reference (points to a "user_locations" node) mDatabase = FirebaseDatabase.getInstance().getReference("user_locations"); requestPermission(); client = LocationServices.getFusedLocationProviderClient(this); Button saveLocBtn = findViewById(R.id.button); locationNameEt = findViewById(R.id.ed); // Save current location to Firebase when button is clicked saveLocBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { requestPermission(); return; } client.getLastLocation().addOnSuccessListener(MapsActivity.this, new OnSuccessListener<Location>() { @Override public void onSuccess(Location location) { if(location!=null) { double latitude = location.getLatitude(); double longitude = location.getLongitude(); String locationName = locationNameEt.getText().toString().trim(); // Create a structured object to store in Firebase LocationData locationData = new LocationData(locationName, latitude, longitude); // Generate a unique key for this location entry (prevents overwrites) String entryKey = mDatabase.push().getKey(); if (entryKey != null) { mDatabase.child(entryKey).setValue(locationData) .addOnSuccessListener(aVoid -> { Toast.makeText(MapsActivity.this, "Location saved successfully!", Toast.LENGTH_SHORT).show(); locationNameEt.setText(""); }) .addOnFailureListener(e -> { Toast.makeText(MapsActivity.this, "Save failed: " + e.getMessage(), Toast.LENGTH_SHORT).show(); }); } } else { Toast.makeText(MapsActivity.this, "Couldn't retrieve location. Try again.", Toast.LENGTH_SHORT).show(); } } }); } }); // Optional: Uncomment this and add a "retrieve" button to your layout to fetch saved locations /*Button retrieveBtn = findViewById(R.id.retrieve_btn); retrieveBtn.setOnClickListener(v -> fetchSavedLocations());*/ } // Model class to define the structure of location data for Firebase public static class LocationData { public String locationName; public double latitude; public double longitude; // Empty constructor required for Firebase deserialization public LocationData() {} public LocationData(String locationName, double latitude, double longitude) { this.locationName = locationName; this.latitude = latitude; this.longitude = longitude; } } // Method to retrieve all saved locations from Firebase private void fetchSavedLocations() { mDatabase.addValueEventListener(new com.google.firebase.database.ValueEventListener() { @Override public void onDataChange(@NonNull com.google.firebase.database.DataSnapshot snapshot) { StringBuilder locationList = new StringBuilder(); for (com.google.firebase.database.DataSnapshot entrySnapshot : snapshot.getChildren()) { LocationData locData = entrySnapshot.getValue(LocationData.class); if (locData != null) { locationList.append("Name: ").append(locData.locationName) .append("\nLat: ").append(locData.latitude) .append(" | Lng: ").append(locData.longitude) .append("\n\n"); } } // Display retrieved data (you can replace this with a TextView/RecyclerView for better UI) Toast.makeText(MapsActivity.this, locationList.toString(), Toast.LENGTH_LONG).show(); } @Override public void onCancelled(@NonNull com.google.firebase.database.DatabaseError error) { Toast.makeText(MapsActivity.this, "Retrieval failed: " + error.getMessage(), Toast.LENGTH_SHORT).show(); } }); } public void requestPermission() { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1); } // Handle permission request results properly @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == 1) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "Location permission granted!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "Permission denied. Cannot access location.", Toast.LENGTH_SHORT).show(); } } } }
Key Details to Note:
- Firebase Node Structure: We use a
user_locationsnode to store all location entries. Thepush()method generates a unique key for each entry, so you won't overwrite existing data. - LocationData Class: This acts as a blueprint for the data saved to Firebase, making it easy to serialize/deserialize data.
- Retrieval Logic: The
fetchSavedLocations()method listens for changes in the Firebase node and collects all stored locations. You can adapt this to display data in a RecyclerView or TextView for a better user experience. - Permission Handling: Added
onRequestPermissionsResultto properly respond when the user grants or denies location access.
内容的提问来源于stack exchange,提问作者M Hero
相关产品推荐
相关产品推荐

