作为标题,如何从Firebase获取数据并在android studio中显示? 当前,因为我不知道如何使用微调器,所以我将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);
}
}
答案 0 :(得分:3)
我想在微调器中显示所有eventid(1111,2222,3333 ....)的所有registerEventName(Google)。
要获取event
属性等于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);
答案 1 :(得分:0)
我相信您所需要的只是一种获取所有标题列表的方法,因此您要做的就是获取值并将它们存储在arraylist中。
然后使用适配器将它们放在微调器中。
这是一段代码,可以将它们作为列表从Firebase中获取:
在您的onDataChange()
中实施类似的操作。
//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());
}
}
}