📌  相关文章
📜  如何使用Firebase Firestore在Android中创建动态卧式RecyclerView?

📅  最后修改于: 2021-05-09 17:01:51             🧑  作者: Mango

在许多应用程序中都可以看到HorizontalRecyclerView。通常用于显示大多数应用程序和网站中的类别。在许多电子商务应用程序中都可以看到这种类型的RecyclerView,以指示应用程序中的类别。而且该RecyclerView也是动态的,因此管理员可以随时从该RecyclerView中添加或删除任何项目。因此,在本文中,我们将介绍使用Firebase在Android中创建动态的Horizontal Recycler View。我们将使用Firebase Firestore显示RecyclerView的项目。

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

我们将构建一个简单的应用程序,其中将显示水平RecyclerView,其中将显示计算机科学中使用的不同技术。因此,我们将在Horizontal RecyclerView中展示这一惊人的计算机技术。下面给出了一个示例GIF,以了解我们将在本文中做些什么。注意,我们将使用Java语言实现该项目。

使用Firebase示例GIF在Android中创建动态卧式RecyclerView

分步实施

步骤1:创建一个新项目

要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。

第2步:将您的应用连接到Firebase

创建新项目后,导航至顶部栏上的“工具”选项。在里面单击Firebase。单击Firebase后,您可以在屏幕快照中看到下面提到的右列。

在该列内,导航到Firebase Cloud Firestore。单击该选项,您将在“将应用程序连接到Firebase”和“将Cloud Firestore添加到您的应用程序”中看到两个选项。单击立即连接选项,您的应用程序将连接到Firebase。之后,单击第二个选项,现在您的应用已连接到Firebase。将您的应用程序连接到Firebase后,您将看到以下屏幕。

之后,确认已将Firebase Firestore数据库的依赖项添加到我们的Gradle文件中。导航到该文件中的app> Gradle脚本,以检查是否添加了以下依赖项。如果您的build.gradle文件中不存在以下依赖项。在“依赖项”部分中添加以下依赖项。

添加此依赖项后,同步您的项目,现在我们可以创建我们的应用程序了。如果您想了解有关将您的应用程序连接到Firebase的更多信息。请参阅本文以详细了解如何将Firebase添加到Android App。

步骤3:使用AndroidManifest.xml文件

要将数据添加到Firebase,我们必须授予访问Internet的权限。要添加这些权限,请导航至应用程序> AndroidManifest.xml,然后在该文件内向其添加以下权限。

XML



XML


  
    
  
    
      


Java
public class DataModal {
  
    // variables for storing our image and name.
    private String name;
    private String imgUrl;
  
    public DataModal() {
        // empty constructor required for firebase.
    }
  
    // constructor for our object class.
    public DataModal(String name, String imgUrl) {
        this.name = name;
        this.imgUrl = imgUrl;
    }
  
    // getter and setter methods
    public String getName() {
        return name;
    }
  
    public void setName(String name) {
        this.name = name;
    }
  
    public String getImgUrl() {
        return imgUrl;
    }
  
    public void setImgUrl(String imgUrl) {
        this.imgUrl = imgUrl;
    }
}


XML


  
    
    
  
    
    
  


Java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
  
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
  
import com.squareup.picasso.Picasso;
  
import java.util.ArrayList;
  
public class DataRVAdapter extends RecyclerView.Adapter {
    private ArrayList dataModalArrayList;
    private Context context;
  
    // constructor class for our Adapter
    public DataRVAdapter(ArrayList dataModalArrayList, Context context) {
        this.dataModalArrayList = dataModalArrayList;
        this.context = context;
    }
  
    @NonNull
    @Override
    public DataRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // passing our layout file for displaying our card item
        return new DataRVAdapter.ViewHolder(LayoutInflater.from(context).inflate(R.layout.image_rv_item, parent, false));
    }
  
    @Override
    public void onBindViewHolder(@NonNull DataRVAdapter.ViewHolder holder, int position) {
        // setting data to our views in Recycler view items.
        DataModal modal = dataModalArrayList.get(position);
        holder.courseNameTV.setText(modal.getName());
          
        // we are using Picasso to load images
        // from URL inside our image view.
        Picasso.get().load(modal.getImgUrl()).into(holder.courseIV);
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // setting on click listener
                // for our items of recycler items.
                Toast.makeText(context, "Clicked item is " + modal.getName(), Toast.LENGTH_SHORT).show();
            }
        });
    }
  
    @Override
    public int getItemCount() {
        // returning the size of array list.
        return dataModalArrayList.size();
    }
  
    public class ViewHolder extends RecyclerView.ViewHolder {
        // creating variables for our 
        // views of recycler items.
        private TextView courseNameTV;
        private ImageView courseIV;
  
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing the views of recycler views.
            courseNameTV = itemView.findViewById(R.id.idTVtext);
            courseIV = itemView.findViewById(R.id.idIVimage);
        }
    }
}


Java
import android.os.Bundle;
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 MainActivity extends AppCompatActivity {
  
    private RecyclerView courseRV;
    private ArrayList dataModalArrayList;
    private DataRVAdapter dataRVAdapter;
    private FirebaseFirestore db;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // initializing our variables.
        courseRV = findViewById(R.id.idRVItems);
          
        // initializing our variable for firebase 
        // firestore and getting its instance.
        db = FirebaseFirestore.getInstance();
          
        // creating our new array list
        dataModalArrayList = new ArrayList<>();
        courseRV.setHasFixedSize(true);
          
        // adding horizontal layout manager for our recycler view.
        courseRV.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
          
        // adding our array list to our recycler view adapter class.
        dataRVAdapter = new DataRVAdapter(dataModalArrayList, this);
          
        // setting adapter to our recycler view.
        courseRV.setAdapter(dataRVAdapter);
  
        loadrecyclerViewData();
    }
  
    private void loadrecyclerViewData() {
  
        db.collection("Data").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.
                            List list = queryDocumentSnapshots.getDocuments();
                            for (DocumentSnapshot d : list) {
                                // after getting this list we are passing that 
                                // list to our object class.
                                DataModal dataModal = d.toObject(DataModal.class);
                                  
                                // and we will pass this object class
                                // inside our arraylist which we have
                                // created for recycler view.
                                dataModalArrayList.add(dataModal);
                            }
                            // after adding the data to recycler view.
                            // we are calling recycler view notifyDataSetChanged
                            // method to notify that data has been changed in recycler view.
                            dataRVAdapter.notifyDataSetChanged();
                        } else {
                            // if the snapshot is empty we are 
                            // displaying a toast message.
                            Toast.makeText(MainActivity.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(MainActivity.this, "Fail to get the data.", Toast.LENGTH_SHORT).show();
            }
        });
    }
}


步骤4:使用activity_main.xml文件

转到activity_main.xml文件,并参考以下代码。以下是activity_main.xml文件的代码。

XML格式



  
    
  
    
      

步骤5:现在,我们将创建一个新的Java类来存储我们的数据

为了从Firebase Firestore数据库读取数据,我们必须创建一个Object类,并且将在该类内部读取数据。要创建对象类,请导航至应用程序> Java >应用程序的包名称>右键单击它,然后单击新建> Java类>给您的类命名。在这里,我们将名称命名为DataModal ,并将以下代码添加到其中。

Java

public class DataModal {
  
    // variables for storing our image and name.
    private String name;
    private String imgUrl;
  
    public DataModal() {
        // empty constructor required for firebase.
    }
  
    // constructor for our object class.
    public DataModal(String name, String imgUrl) {
        this.name = name;
        this.imgUrl = imgUrl;
    }
  
    // getter and setter methods
    public String getName() {
        return name;
    }
  
    public void setName(String name) {
        this.name = name;
    }
  
    public String getImgUrl() {
        return imgUrl;
    }
  
    public void setImgUrl(String imgUrl) {
        this.imgUrl = imgUrl;
    }
}

步骤6:现在,我们将为RecyclerView项目创建一个布局文件。

导航到应用程序> res>布局>右键单击它,然后单击New> Layout Resource File并为该文件命名。创建该文件后,将以下代码添加到其中。在这里,我们将名称命名为image_rv_item ,并将以下代码添加到其中。

XML格式



  
    
    
  
    
    
  

步骤7:现在,我们将朝着创建Adapter类的方向发展

要创建新的Adapter类,请导航至应用程序> Java >应用程序的包名称>右键单击它,然后单击New> Java类,并将您的Java类命名为DataRVAdapter并向其添加以下代码。在代码内部添加了注释,以更详细地了解代码。

Java

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
  
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
  
import com.squareup.picasso.Picasso;
  
import java.util.ArrayList;
  
public class DataRVAdapter extends RecyclerView.Adapter {
    private ArrayList dataModalArrayList;
    private Context context;
  
    // constructor class for our Adapter
    public DataRVAdapter(ArrayList dataModalArrayList, Context context) {
        this.dataModalArrayList = dataModalArrayList;
        this.context = context;
    }
  
    @NonNull
    @Override
    public DataRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // passing our layout file for displaying our card item
        return new DataRVAdapter.ViewHolder(LayoutInflater.from(context).inflate(R.layout.image_rv_item, parent, false));
    }
  
    @Override
    public void onBindViewHolder(@NonNull DataRVAdapter.ViewHolder holder, int position) {
        // setting data to our views in Recycler view items.
        DataModal modal = dataModalArrayList.get(position);
        holder.courseNameTV.setText(modal.getName());
          
        // we are using Picasso to load images
        // from URL inside our image view.
        Picasso.get().load(modal.getImgUrl()).into(holder.courseIV);
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // setting on click listener
                // for our items of recycler items.
                Toast.makeText(context, "Clicked item is " + modal.getName(), Toast.LENGTH_SHORT).show();
            }
        });
    }
  
    @Override
    public int getItemCount() {
        // returning the size of array list.
        return dataModalArrayList.size();
    }
  
    public class ViewHolder extends RecyclerView.ViewHolder {
        // creating variables for our 
        // views of recycler items.
        private TextView courseNameTV;
        private ImageView courseIV;
  
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing the views of recycler views.
            courseNameTV = itemView.findViewById(R.id.idTVtext);
            courseIV = itemView.findViewById(R.id.idIVimage);
        }
    }
}

步骤8:使用MainActivity。 Java文件

转到MainActivity。 Java文件并参考以下代码。下面是MainActivity的代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。

Java

import android.os.Bundle;
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 MainActivity extends AppCompatActivity {
  
    private RecyclerView courseRV;
    private ArrayList dataModalArrayList;
    private DataRVAdapter dataRVAdapter;
    private FirebaseFirestore db;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // initializing our variables.
        courseRV = findViewById(R.id.idRVItems);
          
        // initializing our variable for firebase 
        // firestore and getting its instance.
        db = FirebaseFirestore.getInstance();
          
        // creating our new array list
        dataModalArrayList = new ArrayList<>();
        courseRV.setHasFixedSize(true);
          
        // adding horizontal layout manager for our recycler view.
        courseRV.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
          
        // adding our array list to our recycler view adapter class.
        dataRVAdapter = new DataRVAdapter(dataModalArrayList, this);
          
        // setting adapter to our recycler view.
        courseRV.setAdapter(dataRVAdapter);
  
        loadrecyclerViewData();
    }
  
    private void loadrecyclerViewData() {
  
        db.collection("Data").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.
                            List list = queryDocumentSnapshots.getDocuments();
                            for (DocumentSnapshot d : list) {
                                // after getting this list we are passing that 
                                // list to our object class.
                                DataModal dataModal = d.toObject(DataModal.class);
                                  
                                // and we will pass this object class
                                // inside our arraylist which we have
                                // created for recycler view.
                                dataModalArrayList.add(dataModal);
                            }
                            // after adding the data to recycler view.
                            // we are calling recycler view notifyDataSetChanged
                            // method to notify that data has been changed in recycler view.
                            dataRVAdapter.notifyDataSetChanged();
                        } else {
                            // if the snapshot is empty we are 
                            // displaying a toast message.
                            Toast.makeText(MainActivity.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(MainActivity.this, "Fail to get the data.", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

步骤9:现在将数据添加到Firebase控制台

在浏览器中搜索Firebase并转到该网站,您将看到以下屏幕。

单击“转到控制台”选项后。单击您的项目,如下所示。

单击您的项目后,您将看到以下屏幕。单击该项目后,您将看到以下屏幕。

单击创建数据库选项后,您将看到以下屏幕。

在此屏幕内,我们必须选择“以测试模式启动”选项。我们正在使用测试模式,因为我们未在应用内设置身份验证。因此,我们选择在测试模式下启动。选择测试模式后,单击下一步选项,您将看到以下屏幕。

在此屏幕内,我们只需单击“启用”按钮即可启用我们的Firebase Firestore数据库。完成此过程后,我们必须在Firebase控制台中添加数据。用于将数据添加到我们的Firebase控制台。

您必须单击“开始收集选项”,并将收集名称指定为“数据” 。创建集合后,您必须单击“自动识别”选项以创建第一个文档。然后创建两个字段,一个字段用于“ name ”,一个字段用于“ imgUrl ”,并为它们输入相应的值。请注意,在imgUrl字段的值中指定图像URL链接。然后单击“保存”按钮。您的第一张图片已添加到数据中。

同样,通过单击“添加文档”按钮添加更多图像。

添加这些图像后,运行您的应用程序,您将在以下屏幕上看到输出。

输出:

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