You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中Firebase指定ID数据获取:如何获取ABC的Lat并Toast展示

How to Fetch ABC's Lat Value from Firebase and Show It in a Toast on Button Click

Hey there! Based on your data structure, I’ll assume you’re using Firebase Realtime Database (the most common setup for this kind of key-value storage). Here’s a straightforward, step-by-step implementation for Android (since Toast is an Android component):


1. First, Confirm Firebase Setup

Make sure you’ve added Firebase to your Android project and included the Realtime Database dependency in your module-level build.gradle (use the latest version available):

implementation 'com.google.firebase:firebase-database:20.3.0'

2. Verify Your Firebase Data Structure

Your database should be structured like this (adjust the root node name if yours is different):

"locations": {
  "ABC": {
    "Lat": 12345,
    "Lng": 23124
  },
  "DEF": {
    "Lat": 23324,
    "Lng": 43553
  },
  "GHI": {
    "Lat": 23424,
    "Lng": 12343
  }
}

3. Implement the Button Click & Data Fetch

Here’s the code for your Activity/Fragment, with both Kotlin and Java examples:

Kotlin Example

import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.database.FirebaseDatabase

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Get reference to your Firebase database node
        val dbRef = FirebaseDatabase.getInstance().getReference("locations")

        // Link to your button (replace with your button's ID)
        val showLatBtn: Button = findViewById(R.id.btn_show_abc_lat)

        // Set click listener
        showLatBtn.setOnClickListener {
            // Fetch data for ID "ABC"
            dbRef.child("ABC").get().addOnSuccessListener { snapshot ->
                if (snapshot.exists()) {
                    // Extract the Lat value
                    val abcLat = snapshot.child("Lat").value.toString()
                    // Show the Toast
                    Toast.makeText(this, "ABC's Lat: $abcLat", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(this, "ABC data not found", Toast.LENGTH_SHORT).show()
                }
            }.addOnFailureListener { error ->
                Toast.makeText(this, "Oops, failed to load data: ${error.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

Java Example

import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.ValueEventListener;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initialize Firebase reference
        DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference("locations");

        // Get your button (replace with your button's ID)
        Button showLatBtn = findViewById(R.id.btn_show_abc_lat);

        // Set click handler
        showLatBtn.setOnClickListener(v -> {
            // Fetch ABC's data once
            dbRef.child("ABC").addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot snapshot) {
                    if (snapshot.exists()) {
                        String abcLat = snapshot.child("Lat").getValue().toString();
                        Toast.makeText(MainActivity.this, "ABC's Lat: " + abcLat, Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "ABC data not found", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onCancelled(DatabaseError error) {
                    Toast.makeText(MainActivity.this, "Failed to load data: " + error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        });
    }
}

Key Tips

  • Adjust the Reference Path: If your data is nested under a different root node (like users instead of locations), update the getReference() parameter to match.
  • Permissions: For testing, you can temporarily set Firebase Database rules to allow read access, but make sure to secure them for production.
  • Error Handling: The success/failure listeners ensure you handle cases where the network is down or the ABC node doesn’t exist.

内容的提问来源于stack exchange,提问作者husen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:40:53