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

📅  最后修改于: 2021-05-13 17:39:55             🧑  作者: Mango

GridView也是最常用的UI组件之一,用于在我们的应用程序内以Grid格式显示项目。通过使用这种类型的视图,我们可以以网格格式显示项目。我们已经在大多数应用程序中看到了这种GridView类型。我们还在应用程序中看到了GridView的实现。在本文中,我们将介绍在Android中使用Firebase FirestoreGridView的实现

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

我们将构建一个简单的应用程序,在该应用程序中,我们将以网格格式显示数据,并将这些数据从GridView中的Firebase Firestore加载。下面给出了一个示例GIF,以使我们对本文中要做的事情有一个了解。注意,我们将使用Java语言实现该项目。

使用Firebase Firestore示例GIF在Android中创建动态GridView

分步实施

步骤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.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
  
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
  
import com.squareup.picasso.Picasso;
  
import java.util.ArrayList;
  
public class CoursesGVAdapter extends ArrayAdapter {
  
    // constructor for our list view adapter.
    public CoursesGVAdapter(@NonNull Context context, ArrayList dataModalArrayList) {
        super(context, 0, dataModalArrayList);
    }
  
    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
  
        // below line is use to inflate the 
        // layout for our item of list view.
        View listitemView = convertView;
        if (listitemView == null) {
            listitemView = LayoutInflater.from(getContext()).inflate(R.layout.image_gv_item, parent, false);
        }
          
        // after inflating an item of listview item
        // we are getting data from array list inside 
        // our modal class.
        DataModal dataModal = getItem(position);
          
        // initializing our UI components of list view item.
        TextView nameTV = listitemView.findViewById(R.id.idTVtext);
        ImageView courseIV = listitemView.findViewById(R.id.idIVimage);
          
        // after initializing our items we are
        // setting data to our view.
        // below line is use to set data to our text view.
        nameTV.setText(dataModal.getName());
          
        // in below line we are using Picasso to load image
        // from URL in our Image VIew.
        Picasso.get().load(dataModal.getImgUrl()).into(courseIV);
  
        // below line is use to add item 
        // click listener for our item of list view.
        listitemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // on the item click on our list view.
                // we are displaying a toast message.
                Toast.makeText(getContext(), "Item clicked is : " + dataModal.getName(), Toast.LENGTH_SHORT).show();
            }
        });
        return listitemView;
    }
}


Java
import android.os.Bundle;
import android.widget.GridView;
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.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 {
  
    // creating a variable for our 
    // grid view, arraylist and 
    // firebase Firestore.
    GridView coursesGV;
    ArrayList dataModalArrayList;
    FirebaseFirestore db;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // below line is use to initialize our variables.
        coursesGV = findViewById(R.id.idGVCourses);
        dataModalArrayList = new ArrayList<>();
  
        // initializing our variable for firebase
        // firestore and getting its instance.
        db = FirebaseFirestore.getInstance();
         
        // here we are calling a method 
        // to load data in our list view.
        loadDatainGridView();
    }
  
    private void loadDatainGridView() {
        // below line is use to get data from Firebase
        // firestore using collection in android.
        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);
                                  
                                // after getting data from Firebase 
                                // we are storing that data in our array list
                                dataModalArrayList.add(dataModal);
                            }
                            // after that we are passing our array list to our adapter class.
                            CoursesGVAdapter adapter = new CoursesGVAdapter(MainActivity.this, dataModalArrayList);
                             
                            // after passing this array list 
                            // to our adapter class we are setting 
                            // our adapter to our list view.
                            coursesGV.setAdapter(adapter);
                        } 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) {
                // we are displaying a toast message 
                // when we get any error from Firebase.
                Toast.makeText(MainActivity.this, "Fail to load 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:为我们的GridView项目创建一个布局文件

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

XML格式



  
    
    
  
    
    
  

步骤7:现在为我们的GridView创建一个Adapter类

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

Java

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
  
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
  
import com.squareup.picasso.Picasso;
  
import java.util.ArrayList;
  
public class CoursesGVAdapter extends ArrayAdapter {
  
    // constructor for our list view adapter.
    public CoursesGVAdapter(@NonNull Context context, ArrayList dataModalArrayList) {
        super(context, 0, dataModalArrayList);
    }
  
    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
  
        // below line is use to inflate the 
        // layout for our item of list view.
        View listitemView = convertView;
        if (listitemView == null) {
            listitemView = LayoutInflater.from(getContext()).inflate(R.layout.image_gv_item, parent, false);
        }
          
        // after inflating an item of listview item
        // we are getting data from array list inside 
        // our modal class.
        DataModal dataModal = getItem(position);
          
        // initializing our UI components of list view item.
        TextView nameTV = listitemView.findViewById(R.id.idTVtext);
        ImageView courseIV = listitemView.findViewById(R.id.idIVimage);
          
        // after initializing our items we are
        // setting data to our view.
        // below line is use to set data to our text view.
        nameTV.setText(dataModal.getName());
          
        // in below line we are using Picasso to load image
        // from URL in our Image VIew.
        Picasso.get().load(dataModal.getImgUrl()).into(courseIV);
  
        // below line is use to add item 
        // click listener for our item of list view.
        listitemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // on the item click on our list view.
                // we are displaying a toast message.
                Toast.makeText(getContext(), "Item clicked is : " + dataModal.getName(), Toast.LENGTH_SHORT).show();
            }
        });
        return listitemView;
    }
}

步骤8:使用MainActivity。 Java文件

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

Java

import android.os.Bundle;
import android.widget.GridView;
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.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 {
  
    // creating a variable for our 
    // grid view, arraylist and 
    // firebase Firestore.
    GridView coursesGV;
    ArrayList dataModalArrayList;
    FirebaseFirestore db;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // below line is use to initialize our variables.
        coursesGV = findViewById(R.id.idGVCourses);
        dataModalArrayList = new ArrayList<>();
  
        // initializing our variable for firebase
        // firestore and getting its instance.
        db = FirebaseFirestore.getInstance();
         
        // here we are calling a method 
        // to load data in our list view.
        loadDatainGridView();
    }
  
    private void loadDatainGridView() {
        // below line is use to get data from Firebase
        // firestore using collection in android.
        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);
                                  
                                // after getting data from Firebase 
                                // we are storing that data in our array list
                                dataModalArrayList.add(dataModal);
                            }
                            // after that we are passing our array list to our adapter class.
                            CoursesGVAdapter adapter = new CoursesGVAdapter(MainActivity.this, dataModalArrayList);
                             
                            // after passing this array list 
                            // to our adapter class we are setting 
                            // our adapter to our list view.
                            coursesGV.setAdapter(adapter);
                        } 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) {
                // we are displaying a toast message 
                // when we get any error from Firebase.
                Toast.makeText(MainActivity.this, "Fail to load data..", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

添加上述代码后,将数据添加到Android中的Firebase Firestore。

第9步:将数据添加到Android中的Firebase Firestore

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

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

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

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

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

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

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

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

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

输出:

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