How to get data from firebase and show in android

2020-01-29 19:27发布

As title, how to get data from firebase and show in android studio? Currently because I don't know how to use spinner, so I put the id eventSpinner in xml file as EditText first. Someone know how to get the data from firebase and amend the java file? For example the I want to show all the registerEventName (Google) of all the eventid (1111,2222,3333....) in the spinner. I have add the attachement at below. Thanks for advance who can help me to make it. I search around the stackoverflow but still dont know how to make it.

XML File

<?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 File

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

2条回答
▲ chillily
2楼-- · 2020-01-29 19:47

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

To get all event objects where registerEventName property is equal to Google, please use the following query:

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

Edit:

According to your comment, if you want to display all event names into a spinner, please use the following lines of code:

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);
查看更多
别忘想泡老子
3楼-- · 2020-01-29 19:49

I believe all you are looking for is a way to get a list of all titles So what you do is you get the values and store them in an arraylist.

Then Using an adapter put them in a spinner.

So here is a code which will fetch all of them as a list form firebase:

In your onDataChange() Implement something like this.

//Then pass the list to a method to update the spinner where you use a spinner adapter.

     @Override
            public void onDataChange(DataSnapshot snapshot) {
                if (snapshot != null) {
                    List<String> titles= = new ArrayList<>();
                    for ( DataSnapshot snapshot1:snapshot.getChildren()){
                        MyEvents allocation = snapshot1.getValue(MyEvent.class);
                        // Hope you have a class called Representing the objects I called mine myEvents
                        //Put it in the List
                        titles.add(allocation.getTitle());
                    }

                }
            }
查看更多
登录 后发表回答