首页 > 解决方案 > 如何从 Firebase 中检索数据并在 CardView 中很好地显示

问题描述

我创建了 CreateEvent.java 模块来将数据上传到 firebase。但是如何检索数据并显示在 Cardlist 中?例如在下面的 xml 文件中显示。而且如果firebase中有超过1个数据,如何显示我在xml文件中创建的多个卡片列表?

创建事件.java

package com.example.edward.eventmanagementsystem.ManageEvent;
import android.Manifest;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.edward.eventmanagementsystem.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import static android.widget.Toast.LENGTH_SHORT;


public class CreateEvent extends Activity {

    private static final String TAG = "activity_create_event";
    private Uri filePath;
    private TextView mDisplayDate;
    private DatePickerDialog.OnDateSetListener mDateSetListener;
    private DatabaseReference mDatabaseReference;
    private Button mRegisterButton;
    EditText mEventNameText, mContactNumText, mEventLocationText;
    TextView mEventDate;
    RadioGroup mEventType;
    FirebaseStorage storage;
    StorageReference storageRef,imageRef;
    ProgressDialog progressDialog;
    UploadTask uploadTask;
    Uri uriImage = Uri.parse("com.example.edward.eventmanagementsystem.ManageEvent/"+ R.drawable.ic_launcher_background);
    public static final int PICK_IMAGE = 1;
    ImageView mimageToUpload;



    @Override
    protected void onCreate(Bundle savedInstanceState) {

        FirebaseDatabase firebaseDatabase;
        mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("ListEventInformation").push();
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_create_event);
        mRegisterButton = (Button)findViewById(R.id.btnRegisterEvent);
        storage = FirebaseStorage.getInstance();
        storageRef = storage.getReference();

        mDisplayDate = (TextView) findViewById(R.id.RegisterEventStartDate);
        mDisplayDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar cal = Calendar.getInstance();
                int year = cal.get(Calendar.YEAR);
                int month = cal.get(Calendar.MONTH);
                int day = cal.get(Calendar.DAY_OF_MONTH);

                DatePickerDialog dialog = new DatePickerDialog(
                        CreateEvent.this,
                        android.R.style.Theme_Holo_Light_Dialog_MinWidth,
                        mDateSetListener,
                        year, month, day);
                dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                dialog.show();
            }
        });

        mDateSetListener = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int day) {
                month = month + 1;
                Log.d(TAG, "onDateSet: date: mm/dd/yyyy: " + month + "/" + day + "/" + year);

                String date = month +  "/"  + day + "/" + year;
                mDisplayDate.setText(date);
            }
        };

        //perform action upload image
        mimageToUpload = (ImageView) findViewById(R.id.imageToUpload);

        //insert data to database
        mEventNameText = (EditText) findViewById(R.id.RegisterEventName);
        mContactNumText = (EditText) findViewById(R.id.RegisterContactNumber);
        mEventDate = (TextView) findViewById(R.id.RegisterEventStartDate);
        mEventType =  (RadioGroup) findViewById(R.id.RegisterEventRadiogroup);
        mEventLocationText = (EditText) findViewById(R.id.RegisterEventLocation);
        mimageToUpload = (ImageView) findViewById(R.id.imageToUpload);
        mRegisterButton = (Button) findViewById(R.id.btnRegisterEvent);

        mimageToUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (ContextCompat.checkSelfPermission(CreateEvent.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
                    selectPdf();
                }
                else {
                    ActivityCompat.requestPermissions(CreateEvent.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},9);
                }
            }
        });

        mRegisterButton.setOnClickListener(new View.OnClickListener() {
        @Override
            public void onClick(View v) {

                int selectedId = mEventType.getCheckedRadioButtonId();
                RadioButton radioButton = (RadioButton)findViewById(selectedId);

                final String name = mEventNameText.getText().toString().trim();
                final String contact = mContactNumText.getText().toString().trim();
                final String date = mEventDate.getText().toString().trim();
                final String type = radioButton.getText().toString().trim();
                final String location = mEventLocationText.getText().toString().trim();

                if (TextUtils.isEmpty(name)) {
                    mEventNameText.setError("Enter First Name!");
                    return;
                }


                if (TextUtils.isEmpty(date)) {
                    mEventDate.setError("Enter Date!");
                    return;
                }


                if (TextUtils.isEmpty(type)) {
                    radioButton.setError("Enter Phone Number!");
                    return;
                }
                if(isValidPhone(contact)){

                    Toast.makeText(getApplicationContext(),"Phone number is valid",Toast.LENGTH_SHORT).show();
                }else {
                    mContactNumText.setError("Phone number is not valid");
                    Toast.makeText(getApplicationContext(),"Phone number is not valid",Toast.LENGTH_SHORT).show();
                    return;
                }


                if (TextUtils.isEmpty(location)) {
                    mEventLocationText.setError("Enter Location!");
                    return;
                }

                Map userInfo = new HashMap();
                userInfo.put("mEventNameText", name);
                userInfo.put("mContactNumText", contact);
                userInfo.put("mEventDate", date);
                userInfo.put("radioButton", type);
                userInfo.put("mEventLocationText", location);

                mDatabaseReference.updateChildren(userInfo);
                final String fileName = System.currentTimeMillis()+"";

                if(uriImage != null) {
                    StorageReference storageReference = storage.getReference();
                    storageReference.child("profileImageUrl").child(fileName).putFile(uriImage)
                            .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                                @Override
                                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                                    String url = taskSnapshot.getMetadata().getReference().getDownloadUrl().toString();
                                    mDatabaseReference.child("profileImageUrl").setValue(url).addOnCompleteListener(new OnCompleteListener<Void>() {
                                        @Override
                                        public void onComplete(@NonNull Task<Void> task) {


                                            if (task.isSuccessful()){ }
                                            else{

                                                Toast.makeText(getApplicationContext(),"File not Successfully Uploaded",LENGTH_SHORT).show(); }
                                        }
                                    });
                                }
                            }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {

                            Toast.makeText(getApplicationContext(),"File not Successfully Uploaded",LENGTH_SHORT).show();

                        }
                    }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {

                        }
                    });
                }else{


                }

            Toast.makeText(getApplicationContext(),"New event created successfully!",LENGTH_SHORT).show();
            Intent ManageEventMenu =  new Intent(CreateEvent.this, com.example.edward.eventmanagementsystem.ManageEvent.ManageEventMenu.class);
            startActivity(ManageEventMenu);


            }
        });
    }

    public boolean isValidPhone(CharSequence phone) {
        boolean check=false;
        if(!Pattern.matches("[a-zA-Z]+", phone))
        {
            if(phone.length() < 10 || phone.length() > 11)
            {
                check = false;
            }
            else
            {
                check = true;
            }
        }
        else
        {
            check=false;
        }
        return check;
    }

    private void selectPdf() {

        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
        startActivityForResult(intent,86);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 86 && resultCode == RESULT_OK && data != null){

            final Uri imageUri = data.getData();
            uriImage = imageUri;
            mimageToUpload.setImageURI(uriImage);
        }
        else {
            Toast.makeText(getApplicationContext(),"Please select file", LENGTH_SHORT).show();
        }
    }
}

我想以这种方式显示数据。我想在从 CreateEvent.java 上传时显示从 Firebase 创建的数据的 xml 文件示例

activity_list_of_event.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    android:background="@drawable/gradientwallpaper">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Events"
        android:layout_marginLeft="10dp"
        android:textStyle="bold"
        android:layout_marginTop="20dp"
        android:textSize="24dp"
        android:textColor="@color/white"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Total Created Event"
        android:layout_marginLeft="10dp"
        android:textSize="16dp"
        android:textColor="@color/white"
        android:layout_marginTop="10dp"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="5dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Upcoming"
            android:layout_marginLeft="10dp"
            android:textSize="16dp"
            android:textColor="@color/white"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Pass"
            android:gravity="right"
            android:layout_marginRight="10dp"
            android:textSize="16dp"
            android:textColor="@color/white"/>

    </LinearLayout>

    <android.support.v7.widget.CardView 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="wrap_content"
        android:layout_margin="10dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/white"
            android:padding="10dp"
            android:weightSum="10">

            <LinearLayout
                android:layout_width="100dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_weight="4"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/item_month"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"

                    android:text="Month" />/                    android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"

                <TextView
                    android:id="@+id/item_date"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"

                    android:text="Date" />/                    android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"

            </LinearLayout>


            <LinearLayout
                android:layout_width="200dp"
                android:layout_height="wrap_content"
                android:layout_weight="4"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/item_eventName"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Event Name"
                    android:textStyle="bold" />/android:textScaleX="18sp"

                <TextView
                    android:id="@+id/item_contactNumber"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Contact Number"

                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/item_type"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Type of event"

                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/itemLocation"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Location"

                    android:textStyle="bold" />


            </LinearLayout>

            <ImageView
                android:id="@+id/item_image"
                android:layout_width="75dp"
                android:layout_height="75dp"
                android:background="@color/white"
                android:scaleType="centerCrop"
                android:src="@drawable/pic1" />


        </LinearLayout>
    </android.support.v7.widget.CardView>

</LinearLayout>

标签: androidfirebasefirebase-realtime-database

解决方案


推荐阅读