java - 如何从 Firebase 实时数据库获取数据并将其显示在微调器中?

标签 java android firebase firebase-realtime-database

如标题,如何从firebase获取数据并在android studio中显示? 目前,因为我不知道如何使用 spinner,所以我首先将 id eventSpinner 放在 XML 文件中作为 EditText。有人知道如何从 firebase 获取数据并修改 java 文件吗?例如,我想在微调器中显示所有eventid(1111,2222,3333....)的所有registerEventName(Google)。我已添加下面的附件。感谢您提前帮助我做到这一点。我在 StackOverflow 上搜索,但仍然不知道如何制作。

XML 文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".StaffAttendanceCheckIn">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/title"
        android:text="Staff Check In"
        android:textSize="24dp"
        android:gravity="center"
        android:layout_marginTop="10dp"
        android:textStyle="bold"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:id="@+id/eventName"
        android:layout_below="@+id/title">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:textStyle="bold"
            android:textSize="18dp"
            android:text="Event Name: "/>

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:id="@+id/eventSpinner"
            android:text="Google Event"
            android:textSize="18dp"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_below="@+id/eventName"
        android:id="@+id/checkInTime">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:textStyle="bold"
            android:textSize="18dp"
            android:text="Check In Time: "/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:textSize="18dp"
            android:id="@+id/txtCurrentTime"
            android:text="Show time here"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_below="@+id/checkInTime"
        android:id="@+id/checkInDate">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:textStyle="bold"
            android:textSize="18dp"
            android:text="Check In Date: "/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:id="@+id/txtCurrentDate"
            android:textSize="18dp"
            android:text="Show date here"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_below="@+id/checkInDate"
        android:id="@+id/checkInLocation">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:textStyle="bold"
            android:textSize="18dp"
            android:text="Current Location: "/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/location"
            android:layout_marginLeft="13dp"
            android:textSize="18dp"
            android:text="Show location here"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_below="@+id/checkInLocation"
        android:id="@+id/account">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:textStyle="bold"
            android:textSize="18dp"
            android:text="Account Check In: "/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/txtDisplayName"
            android:layout_marginLeft="13dp"
            android:textSize="18dp"
            android:text="Show acc name here"/>
    </LinearLayout>


    <com.google.android.gms.maps.MapView
        android:id="@+id/mapview"
        android:background="@color/darkGrey"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:layout_below="@+id/account"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:apiKey="@string/GooglePlaceApi"
        android:enabled="true" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/mapview"
        android:gravity="center"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btnCheckIn"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_margin="10dp"
            android:textColor="@color/white"
            android:layout_marginTop="10dp"
            android:background="@android:color/holo_red_dark"
            android:textSize="18dp"
            android:text="Confirm" />

    </LinearLayout>
</RelativeLayout>

Java 文件

package com.example.edward.neweventmanagementsystem;

import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.edward.neweventmanagementsystem.Model.AttendanceInfo;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.text.SimpleDateFormat;

import java.util.Date;
import java.util.Locale;

import static android.widget.Toast.LENGTH_SHORT;

public class StaffAttendanceCheckIn extends AppCompatActivity  {

    private TextView CheckInTime, CheckInDate, CheckInName;
    private EditText EventName;
    private Button btnCheckIn;

    private static final int REQUEST_LOCATION = 1;
    TextView CurrentLocation;
    LocationManager locationManager;
    String latitude,longitude;
    MapView map1;
    private GoogleMap map;
    private DatabaseReference mDatabaseReference;

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

        EventName = (EditText) findViewById(R.id.eventSpinner);
        CheckInDate = (TextView) findViewById(R.id.txtCurrentDate);
        CheckInTime = (TextView) findViewById(R.id.txtCurrentTime);
        CheckInName = (TextView) findViewById(R.id.txtDisplayName);

        map1 = (MapView) findViewById(R.id.mapview);
        btnCheckIn = (Button) findViewById(R.id.btnCheckIn);

        map1.onCreate(savedInstanceState);

        mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("AttendanceRecord");
        System.out.println("Test mDatabase: "+mDatabaseReference);

        //Display the info in the spinner
        FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference myRef = database.getReference("EventName");

        SimpleDateFormat date = new SimpleDateFormat("EEEE dd MMM yyyy", Locale.ENGLISH);
        String currentDate = date.format(new Date());

        SimpleDateFormat time = new SimpleDateFormat("HH:mm:ss");
        String currentTime = time.format(new Date());

        CheckInDate.setText(currentDate);
        CheckInTime.setText(currentTime);

        FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser() ;
        CheckInName.setText(currentFirebaseUser.getDisplayName());

        /**
        FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference myRef = database.getReference("EventName");

        System.out.println("Test Script: " + myRef); */

        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);

        CurrentLocation = (TextView)findViewById(R.id.location);

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            buildAlertMessageNoGps();

        } else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            getLocation();
        }


        btnCheckIn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                final ProgressDialog mDialog = new ProgressDialog(StaffAttendanceCheckIn.this);

                mDialog.setMessage("Please waiting...");
                mDialog.show();

                mDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();

                        if(dataSnapshot.child(EventName.getText().toString()).child(CheckInDate.getText().toString()).child(currentFirebaseUser.getUid()).exists()){

                            mDialog.dismiss();
                            Toast.makeText(StaffAttendanceCheckIn.this, "The following account already check in on today for this event!", Toast.LENGTH_SHORT).show();
                        }
                        else {
                            AttendanceInfo attendanceInfo = new AttendanceInfo(EventName.getText().toString().trim(),
                                    CheckInTime.getText().toString().trim(),
                                    CheckInDate.getText().toString().trim(),
                                    CurrentLocation.getText().toString().trim(),
                                    CheckInName.getText().toString().trim());

                                    mDatabaseReference.child(EventName.getText().toString()).child(CheckInDate.getText().toString()).child(currentFirebaseUser.getUid()).setValue(attendanceInfo);

                        Toast.makeText(getApplicationContext(),"User "+currentFirebaseUser.getDisplayName()+ " check in successfully on " + CheckInDate.getText().toString(),LENGTH_SHORT).show();
                        Intent intent =  new Intent(StaffAttendanceCheckIn.this, com.example.edward.neweventmanagementsystem.StaffAttendance.class);
                        startActivity(intent);

                        }

                    }

                    @Override

                    public void onCancelled(@NonNull DatabaseError databaseError) {

                    }
                });
            }

        });
    }

//    @Override
//    public void onClick(View view) {
//
//    }

    private void getLocation() {
        if (ActivityCompat.checkSelfPermission(com.example.edward.neweventmanagementsystem.StaffAttendanceCheckIn.this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
                (com.example.edward.neweventmanagementsystem.StaffAttendanceCheckIn.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(com.example.edward.neweventmanagementsystem.StaffAttendanceCheckIn.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);

        } else {
            Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

            Location location1 = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

            Location location2 = locationManager.getLastKnownLocation(LocationManager. PASSIVE_PROVIDER);

            if (location != null) {
                double latti = location.getLatitude();
                double longi = location.getLongitude();

                latitude = String.valueOf(latti);
                longitude = String.valueOf(longi);

                CurrentLocation.setText("Lat = " + latitude + "\n" + "Lon = " + longitude);
//                CurrentLocation.setText("latitude"+latitude);
//                CurrentLocation.setText("longitude"+longitude);

                final float ZOOM_MAP = 17.0f;
                final LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                map1.getMapAsync(new OnMapReadyCallback() {
                    @Override
                    public void onMapReady(GoogleMap googleMap) {

                        CameraUpdate myLocation = CameraUpdateFactory.newLatLngZoom(latLng, ZOOM_MAP);
                        googleMap.animateCamera(myLocation);
                        googleMap.getUiSettings().setAllGesturesEnabled(false
                        );
                    }
                });


//                CameraUpdate myLocation = CameraUpdateFactory.newLatLngZoom(latLng, ZOOM_MAP);
//                map.animateCamera(myLocation);


//                CameraUpdate myLocation = CameraUpdateFactory.newLatLngZoom(latLng, ZOOM_MAP);
//                System.out.println("Test Script" + myLocation);
//                map.animateCamera(myLocation);


            } else  if (location1 != null) {
                double latti = location1.getLatitude();
                double longi = location1.getLongitude();
                latitude = String.valueOf(latti);
                longitude = String.valueOf(longi);
//                LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
//                System.out.println("Test Script: " +latLng);

                CurrentLocation.setText("Lat = " + latitude + "\n" + "Lon = " + longitude);

            } else  if (location2 != null) {
                double latti = location2.getLatitude();
                double longi = location2.getLongitude();
                latitude = String.valueOf(latti);
                longitude = String.valueOf(longi);

                CurrentLocation.setText("Lat = " + latitude + "\n" + "Lon = " + longitude);

            }else{

                Toast.makeText(this,"Unble to Trace your location",Toast.LENGTH_SHORT).show();

            }
        }
    }

    protected void buildAlertMessageNoGps() {

        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Please Turn ON your GPS Connection")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int id) {
                        startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int id) {
                        dialog.cancel();
                    }
                });
        final AlertDialog alert = builder.create();
        alert.show();
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();
        map1.onDestroy();
    }

    @Override
    public void onLowMemory(){
        super.onLowMemory();
        map1.onLowMemory();
    }

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

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        map1.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(this, StaffAttendance.class);
        startActivity(intent);
    }
}

Sample Image

最佳答案

I want to show all the registerEventName (Google) of all the eventid (1111,2222,3333....) in the spinner.

要获取 registerEventName 属性等于 Google 的所有 event 对象,请使用以下查询:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef
    .child("ListOfEvents")
    .child(uid)
    .orderByChild("registerEventName")
    .equalsTo("Google");
query.addListenerForSingleValueEvent(/* ... */);

编辑:

根据您的评论,如果您想在微调器中显示所有事件名称,请使用以下代码行:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("ListOfEvents").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<String> eventList = new ArrayList<String>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String registerEventName = ds.child("registerEventName").getValue(String.class);
            eventList.add(registerEventName);
        }
        Spinner spinner = (Spinner) findViewById(R.id.spinner);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, eventList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
    }
};
uidRef.addListenerForSingleValueEvent(valueEventListener);

关于java - 如何从 Firebase 实时数据库获取数据并将其显示在微调器中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53171376/

相关文章:

java - 从任意 url 动态加载 jar

java - 如何从java中的字符数组中获取替代字符?

java - 卡在数据库插入中

java - 无法在 java 中从 String 转换为 float

android - 如何将 Android 任务转换为 Kotlin Deferred?

rest - Firestore REST API 数据库监听

java - Java中矩阵和表的常用数据类型

java - 在将对象转换为字符串时,如何动态决定 json 项?

android - 为什么 ImageView setImageResource() 将图片大小设置为 match_parent?

python - 使用 Chaquopy 安装 TensorFlow 时出现 "Read timed out"