📌  相关文章
📜  如何从Android中的Firebase Firestore读取数据?

📅  最后修改于: 2021-05-09 16:34:39             🧑  作者: Mango

在上一篇文章中,我们了解了如何在Android中向Firebase Firestore添加数据。这是本系列的继续。现在,我们将看到如何在Firebase Firestore中读取此添加的数据。现在,我们将着手在Android Firebase中实现此读取数据的实现。

我们将在本文中构建什么?

我们将在先前的应用程序中创建一个新屏幕,在该屏幕中,我们将显示在RecyclerView中添加到Firebase Firestore中的数据。我们将从应用程序内的Firebase Firestore中读取所有数据。

分步实施

步骤1:使用activity_main.xml文件

转到activity_main.xml文件,再添加一个按钮,以显示所有已添加课程的列表。下面是代码片段,最后添加了代码。

XML


XML


  
    
    
  
    
    
  
    
    
  
    
    


XML


  
    
    
  
    
    
      


XML


  
    
  
        
        
          
        
        
          
        
        
          
    
  


Java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
  
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
  
import java.util.ArrayList;
  
public class CourseRVAdapter extends RecyclerView.Adapter {
    // creating variables for our ArrayList and context
    private ArrayList coursesArrayList;
    private Context context;
  
    // creating constructor for our adapter class
    public CourseRVAdapter(ArrayList coursesArrayList, Context context) {
        this.coursesArrayList = coursesArrayList;
        this.context = context;
    }
  
    @NonNull
    @Override
    public CourseRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // passing our layout file for displaying our card item
        return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.course_item, parent, false));
    }
  
    @Override
    public void onBindViewHolder(@NonNull CourseRVAdapter.ViewHolder holder, int position) {
        // setting data to our text views from our modal class.
        Courses courses = coursesArrayList.get(position);
        holder.courseNameTV.setText(courses.getCourseName());
        holder.courseDurationTV.setText(courses.getCourseDuration());
        holder.courseDescTV.setText(courses.getCourseDescription());
    }
  
    @Override
    public int getItemCount() {
        // returning the size of our array list.
        return coursesArrayList.size();
    }
  
    class ViewHolder extends RecyclerView.ViewHolder {
        // creating variables for our text views.
        private final TextView courseNameTV;
        private final TextView courseDurationTV;
        private final TextView courseDescTV;
  
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing our text views.
            courseNameTV = itemView.findViewById(R.id.idTVCourseName);
            courseDurationTV = itemView.findViewById(R.id.idTVCourseDuration);
            courseDescTV = itemView.findViewById(R.id.idTVCourseDescription);
        }
    }
}


Java
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
  
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
  
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;
  
import java.util.ArrayList;
import java.util.List;
  
public class CourseDetails extends AppCompatActivity {
  
    // creating variables for our recycler view, 
    // array list, adapter, firebase firestore
    // and our progress bar.
    private RecyclerView courseRV;
    private ArrayList coursesArrayList;
    private CourseRVAdapter courseRVAdapter;
    private FirebaseFirestore db;
    ProgressBar loadingPB;
      
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_course_details);
          
        // initializing our variables.
        courseRV = findViewById(R.id.idRVCourses);
        loadingPB = findViewById(R.id.idProgressBar);
          
        // initializing our variable for firebase
        // firestore and getting its instance.
        db = FirebaseFirestore.getInstance();
          
        // creating our new array list
        coursesArrayList = new ArrayList<>();
        courseRV.setHasFixedSize(true);
        courseRV.setLayoutManager(new LinearLayoutManager(this));
          
        // adding our array list to our recycler view adapter class.
        courseRVAdapter = new CourseRVAdapter(coursesArrayList, this);
          
        // setting adapter to our recycler view.
        courseRV.setAdapter(courseRVAdapter);
          
        // below line is use to get the data from Firebase Firestore.
        // previously we were saving data on a reference of Courses
        // now we will be getting the data from the same reference.
        db.collection("Courses").get()
                .addOnSuccessListener(new OnSuccessListener() {
                    @Override
                    public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                        // after getting the data we are calling on success method
                        // and inside this method we are checking if the received 
                        // query snapshot is empty or not.
                        if (!queryDocumentSnapshots.isEmpty()) {
                            // if the snapshot is not empty we are
                            // hiding our progress bar and adding 
                            // our data in a list.
                            loadingPB.setVisibility(View.GONE);
                            List list = queryDocumentSnapshots.getDocuments();
                            for (DocumentSnapshot d : list) {
                                // after getting this list we are passing 
                                // that list to our object class.
                                Courses c = d.toObject(Courses.class);
                                  
                                // and we will pass this object class
                                // inside our arraylist which we have 
                                // created for recycler view.
                                coursesArrayList.add(c);
                            }
                            // after adding the data to recycler view.
                            // we are calling recycler view notifuDataSetChanged
                            // method to notify that data has been changed in recycler view.
                            courseRVAdapter.notifyDataSetChanged();
                        } else {
                            // if the snapshot is empty we are displaying a toast message.
                            Toast.makeText(CourseDetails.this, "No data found in Database", Toast.LENGTH_SHORT).show();
                        }
                    }
                }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                // if we do not get any data or any error we are displaying 
                // a toast message that we do not get any data
                Toast.makeText(CourseDetails.this, "Fail to get the data.", Toast.LENGTH_SHORT).show();
            }
        });
    }
}


Java
// adding onclick listener to view data in new activity
viewCoursesBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // opening a new activity on button click
                Intent i = new Intent(MainActivity.this,CourseDetails.class);
                startActivity(i);
            }
   });


Java
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
  
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
  
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
  
public class MainActivity extends AppCompatActivity {
  
    // creating variables for our edit text
    private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt;
  
    // creating variable for button
    private Button submitCourseBtn, viewCoursesBtn;
  
    // creating a strings for storing
    // our values from edittext fields.
    private String courseName, courseDuration, courseDescription;
  
    // creating a variable
    // for firebasefirestore.
    private FirebaseFirestore db;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // getting our instance
        // from Firebase Firestore.
        db = FirebaseFirestore.getInstance();
  
        // initializing our edittext and buttons
        courseNameEdt = findViewById(R.id.idEdtCourseName);
        courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);
        courseDurationEdt = findViewById(R.id.idEdtCourseDuration);
        submitCourseBtn = findViewById(R.id.idBtnSubmitCourse);
        viewCoursesBtn = findViewById(R.id.idBtnViewCourses);
  
        // adding onclick listener to view data in new activity
        viewCoursesBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // opening a new activity on button click
                Intent i = new Intent(MainActivity.this,CourseDetails.class);
                startActivity(i);
            }
        });
  
        // adding on click listener for button
        submitCourseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
  
                // getting data from edittext fields.
                courseName = courseNameEdt.getText().toString();
                courseDescription = courseDescriptionEdt.getText().toString();
                courseDuration = courseDurationEdt.getText().toString();
  
                // validating the text fields if empty or not.
                if (TextUtils.isEmpty(courseName)) {
                    courseNameEdt.setError("Please enter Course Name");
                } else if (TextUtils.isEmpty(courseDescription)) {
                    courseDescriptionEdt.setError("Please enter Course Description");
                } else if (TextUtils.isEmpty(courseDuration)) {
                    courseDurationEdt.setError("Please enter Course Duration");
                } else {
                    // calling method to add data to Firebase Firestore.
                    addDataToFirestore(courseName, courseDescription, courseDuration);
                }
            }
        });
    }
  
    private void addDataToFirestore(String courseName, String courseDescription, String courseDuration) {
  
        // creating a collection reference
        // for our Firebase Firetore database.
        CollectionReference dbCourses = db.collection("Courses");
  
        // adding our data to our courses object class.
        Courses courses = new Courses(courseName, courseDescription, courseDuration);
  
        // below method is use to add data to Firebase Firestore.
        dbCourses.add(courses).addOnSuccessListener(new OnSuccessListener() {
            @Override
            public void onSuccess(DocumentReference documentReference) {
                // after the data addition is successful
                // we are displaying a success toast message.
                Toast.makeText(MainActivity.this, "Your Course has been added to Firebase Firestore", Toast.LENGTH_SHORT).show();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                // this method is called when the data addition process is failed.
                // displaying a toast message when data addition is failed.
                Toast.makeText(MainActivity.this, "Fail to add course \n" + e, Toast.LENGTH_SHORT).show();
            }
        });
    }
}


现在下面是activity_main.xml文件的更新代码 添加以上代码段后。

XML格式



  
    
    
  
    
    
  
    
    
  
    
    

第2步:现在,我们将创建新的Activity,以在RecyclerView中显示Firebase Firestore中的数据

要创建新的活动,我们必须导航至应用程序> Java >您的应用程序的程序包名称>右键单击程序包名称>新建>空活动,并将您的活动命名为CourseDetails并创建新的活动。确保选择空白活动。

步骤3:现在,我们将在“课程详细信息”活动中着手XML实现。

导航至应用程序> res>布局> activity_course_details.xml,然后将以下代码添加到其中。

XML格式



  
    
    
  
    
    
      

步骤4:现在,我们将为RecyclerView项目创建一个卡片布局

要为RecyclerView创建新项目,请导航至应用程序> res>布局>右键单击layout>新建>布局资源文件,并将其命名为course_item.xml,然后在其中添加以下代码。

XML格式



  
    
  
        
        
          
        
        
          
        
        
          
    
  

步骤5:现在我们将创建Adapter类,该类将处理RecyclerView项的数据

要为我们的Recycler View创建Adapter类,请导航至应用程序> Java >您的应用程序包名称>右键单击它,然后单击>新建> Java类,并将您的类命名为CourseRVAdapter 。创建此类后,将以下代码添加到其中。在代码中添加了注释,以更详细地了解。

Java

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
  
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
  
import java.util.ArrayList;
  
public class CourseRVAdapter extends RecyclerView.Adapter {
    // creating variables for our ArrayList and context
    private ArrayList coursesArrayList;
    private Context context;
  
    // creating constructor for our adapter class
    public CourseRVAdapter(ArrayList coursesArrayList, Context context) {
        this.coursesArrayList = coursesArrayList;
        this.context = context;
    }
  
    @NonNull
    @Override
    public CourseRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // passing our layout file for displaying our card item
        return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.course_item, parent, false));
    }
  
    @Override
    public void onBindViewHolder(@NonNull CourseRVAdapter.ViewHolder holder, int position) {
        // setting data to our text views from our modal class.
        Courses courses = coursesArrayList.get(position);
        holder.courseNameTV.setText(courses.getCourseName());
        holder.courseDurationTV.setText(courses.getCourseDuration());
        holder.courseDescTV.setText(courses.getCourseDescription());
    }
  
    @Override
    public int getItemCount() {
        // returning the size of our array list.
        return coursesArrayList.size();
    }
  
    class ViewHolder extends RecyclerView.ViewHolder {
        // creating variables for our text views.
        private final TextView courseNameTV;
        private final TextView courseDurationTV;
        private final TextView courseDescTV;
  
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing our text views.
            courseNameTV = itemView.findViewById(R.id.idTVCourseName);
            courseDurationTV = itemView.findViewById(R.id.idTVCourseDuration);
            courseDescTV = itemView.findViewById(R.id.idTVCourseDescription);
        }
    }
}

步骤6:使用CourseDetails。 Java文件

在为我们的RecyclerView创建新的Adapter类之后,我们必须转向CourseDetails。 Java文件,并向其中添加以下代码。

Java

import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
  
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
  
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;
  
import java.util.ArrayList;
import java.util.List;
  
public class CourseDetails extends AppCompatActivity {
  
    // creating variables for our recycler view, 
    // array list, adapter, firebase firestore
    // and our progress bar.
    private RecyclerView courseRV;
    private ArrayList coursesArrayList;
    private CourseRVAdapter courseRVAdapter;
    private FirebaseFirestore db;
    ProgressBar loadingPB;
      
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_course_details);
          
        // initializing our variables.
        courseRV = findViewById(R.id.idRVCourses);
        loadingPB = findViewById(R.id.idProgressBar);
          
        // initializing our variable for firebase
        // firestore and getting its instance.
        db = FirebaseFirestore.getInstance();
          
        // creating our new array list
        coursesArrayList = new ArrayList<>();
        courseRV.setHasFixedSize(true);
        courseRV.setLayoutManager(new LinearLayoutManager(this));
          
        // adding our array list to our recycler view adapter class.
        courseRVAdapter = new CourseRVAdapter(coursesArrayList, this);
          
        // setting adapter to our recycler view.
        courseRV.setAdapter(courseRVAdapter);
          
        // below line is use to get the data from Firebase Firestore.
        // previously we were saving data on a reference of Courses
        // now we will be getting the data from the same reference.
        db.collection("Courses").get()
                .addOnSuccessListener(new OnSuccessListener() {
                    @Override
                    public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                        // after getting the data we are calling on success method
                        // and inside this method we are checking if the received 
                        // query snapshot is empty or not.
                        if (!queryDocumentSnapshots.isEmpty()) {
                            // if the snapshot is not empty we are
                            // hiding our progress bar and adding 
                            // our data in a list.
                            loadingPB.setVisibility(View.GONE);
                            List list = queryDocumentSnapshots.getDocuments();
                            for (DocumentSnapshot d : list) {
                                // after getting this list we are passing 
                                // that list to our object class.
                                Courses c = d.toObject(Courses.class);
                                  
                                // and we will pass this object class
                                // inside our arraylist which we have 
                                // created for recycler view.
                                coursesArrayList.add(c);
                            }
                            // after adding the data to recycler view.
                            // we are calling recycler view notifuDataSetChanged
                            // method to notify that data has been changed in recycler view.
                            courseRVAdapter.notifyDataSetChanged();
                        } else {
                            // if the snapshot is empty we are displaying a toast message.
                            Toast.makeText(CourseDetails.this, "No data found in Database", Toast.LENGTH_SHORT).show();
                        }
                    }
                }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                // if we do not get any data or any error we are displaying 
                // a toast message that we do not get any data
                Toast.makeText(CourseDetails.this, "Fail to get the data.", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

步骤7:使用MainActivity。 Java文件

MainActivity中。 Java文件中,我们必须向Incourse.Details.class文件中添加一个Intent。下面是执行此操作的代码段。

Java

// adding onclick listener to view data in new activity
viewCoursesBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // opening a new activity on button click
                Intent i = new Intent(MainActivity.this,CourseDetails.class);
                startActivity(i);
            }
   });

以下是MainActivity的更新代码。 Java文件。

Java

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
  
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
  
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
  
public class MainActivity extends AppCompatActivity {
  
    // creating variables for our edit text
    private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt;
  
    // creating variable for button
    private Button submitCourseBtn, viewCoursesBtn;
  
    // creating a strings for storing
    // our values from edittext fields.
    private String courseName, courseDuration, courseDescription;
  
    // creating a variable
    // for firebasefirestore.
    private FirebaseFirestore db;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // getting our instance
        // from Firebase Firestore.
        db = FirebaseFirestore.getInstance();
  
        // initializing our edittext and buttons
        courseNameEdt = findViewById(R.id.idEdtCourseName);
        courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);
        courseDurationEdt = findViewById(R.id.idEdtCourseDuration);
        submitCourseBtn = findViewById(R.id.idBtnSubmitCourse);
        viewCoursesBtn = findViewById(R.id.idBtnViewCourses);
  
        // adding onclick listener to view data in new activity
        viewCoursesBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // opening a new activity on button click
                Intent i = new Intent(MainActivity.this,CourseDetails.class);
                startActivity(i);
            }
        });
  
        // adding on click listener for button
        submitCourseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
  
                // getting data from edittext fields.
                courseName = courseNameEdt.getText().toString();
                courseDescription = courseDescriptionEdt.getText().toString();
                courseDuration = courseDurationEdt.getText().toString();
  
                // validating the text fields if empty or not.
                if (TextUtils.isEmpty(courseName)) {
                    courseNameEdt.setError("Please enter Course Name");
                } else if (TextUtils.isEmpty(courseDescription)) {
                    courseDescriptionEdt.setError("Please enter Course Description");
                } else if (TextUtils.isEmpty(courseDuration)) {
                    courseDurationEdt.setError("Please enter Course Duration");
                } else {
                    // calling method to add data to Firebase Firestore.
                    addDataToFirestore(courseName, courseDescription, courseDuration);
                }
            }
        });
    }
  
    private void addDataToFirestore(String courseName, String courseDescription, String courseDuration) {
  
        // creating a collection reference
        // for our Firebase Firetore database.
        CollectionReference dbCourses = db.collection("Courses");
  
        // adding our data to our courses object class.
        Courses courses = new Courses(courseName, courseDescription, courseDuration);
  
        // below method is use to add data to Firebase Firestore.
        dbCourses.add(courses).addOnSuccessListener(new OnSuccessListener() {
            @Override
            public void onSuccess(DocumentReference documentReference) {
                // after the data addition is successful
                // we are displaying a success toast message.
                Toast.makeText(MainActivity.this, "Your Course has been added to Firebase Firestore", Toast.LENGTH_SHORT).show();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                // this method is called when the data addition process is failed.
                // displaying a toast message when data addition is failed.
                Toast.makeText(MainActivity.this, "Fail to add course \n" + e, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

完成此过程后,我们必须在Firebase控制台中从应用程序中添加数据,然后单击“查看已添加的课程”按钮,您将看到我们已在Firebase控制台中添加的课程列表。下图显示了仅一个回收站项目的Firebase Firestore数据库的外观。

完成此操作后,运行您的应用程序,然后查看代码输出。

输出:

想要一个节奏更快,更具竞争性的环境来学习Android的基础知识吗?
单击此处,前往由我们的专家精心策划的指南,以使您立即做好行业准备!