如何从firebase获取数据并在android studio中显示?

如何从firebase获取数据并在android studio中显示?,第1张

概述作为标题,如何从firebase获取数据并在androidstudio中显示?目前因为我不知道如何使用微调器,所以我首先将id的eventSpinner作为EditText放在xml文件中.有人知道如何从firebase获取数据并修改java文件吗?例如,我想在旋转器中显示所有eventid(1111,2222,3333….)的所有registerEvent

作为标题,如何从firebase获取数据并在android studio中显示?
目前因为我不知道如何使用微调器,所以我首先将ID的eventSpinner作为EditText放在xml文件中.有人知道如何从firebase获取数据并修改java文件吗?例如,我想在旋转器中显示所有eventID(1111,2222,3333 ….)的所有registerEventname(Google).我在下面添加了附件.感谢能够帮助我成功的进步.我搜索堆栈溢出但仍然不知道如何制作它.

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的所有事件对象,请使用以下查询:

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);

总结

以上是内存溢出为你收集整理的如何从firebase获取数据并在android studio中显示?全部内容,希望文章能够帮你解决如何从firebase获取数据并在android studio中显示?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1102355.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-28
下一篇 2022-05-28

发表评论

登录后才能评论

评论列表(0条)

保存