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

📅  最后修改于: 2021-05-10 17:03:07             🧑  作者: Mango

我们已经看到在Android中创建了一个基本的Intro Slider,可用于向我们的用户告知我们应用程序的功能以及更多其他功能。在本文中,我们将借助Firebase在我们的应用程序中查看动态Intro Slider的实现。借助Firebase Firestore,我们可以从Firebase控制台动态更改所有数据。现在,让我们开始实施。

我们将在这个项目中建立什么?

我们将构建一个简单的Intro滑块,在其中我们将从Firebase控制台加载所有数据,并将这些数据显示在我们的滑块中。借助Firebase,我们可以根据需求动态更新数据。下面给出了一个示例GIF,以了解我们将在本文中做些什么。注意,我们将使用Java语言实现该项目。

使用Firebase Firestore示例GIF在Android中创建动态简介滑块

分步实施

步骤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。当我们从URL加载图像时,我们必须使用毕加索。

步骤3:为Internet添加权限

由于我们将从URL加载图像,因此我们必须在您的AndroidManifest.xml文件中添加Internet权限。用于添加权限。导航到应用程序> AndroidManifest.xml文件,然后添加以下权限。

XML



XML


  
    
    
      
    
  
        
  
        
        
  
        
        


XML


  
    
    
  
    
    
      
    
    
      


Java
public class SliderModal {
  
    // string variable for storing title,
    // image url and description.
    private String title;
    private String heading;
    private String imgUrl;
  
    public SliderModal() {
        // empty constructor is required
        // when using firebase
    }
  
    // creating getter methods.
    public String getTitle() {
        return title;
    }
  
    public void setTitle(String title) {
        this.title = title;
    }
  
    public String getHeading() {
        return heading;
    }
  
    // creating setter methods
    public void setHeading(String heading) {
        this.heading = heading;
    }
  
    public String getImgUrl() {
        return imgUrl;
    }
  
    public void setImgUrl(String imgUrl) {
        this.imgUrl = imgUrl;
    }
      
    // constructor for our modal class
    public SliderModal(String title, String heading, String imgUrl) {
        this.title = title;
        this.heading = heading;
        this.imgUrl = imgUrl;
    }
}


Java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
  
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
  
import com.squareup.picasso.Picasso;
  
import java.util.ArrayList;
  
public class SliderAdapter extends PagerAdapter {
  
    // creating variables for layout inflater,
    // context and array list.
    LayoutInflater layoutInflater;
    Context context;
    ArrayList sliderModalArrayList;
  
    // creating constructor.
    public SliderAdapter(Context context, ArrayList sliderModalArrayList) {
        this.context = context;
        this.sliderModalArrayList = sliderModalArrayList;
    }
  
    @Override
    public int getCount() {
        // inside get count method returning 
        // the size of our array list.
        return sliderModalArrayList.size();
    }
      
    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        // inside isViewFrombject method we are 
        // returning our Relative layout object.
        return view == (RelativeLayout) object;
    }
  
    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        // in this method we will initialize all our layout items
        // and inflate our layout file as well.
        layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
          
        // below line is use to inflate the layout file which we created.
        View view = layoutInflater.inflate(R.layout.slider_layout, container, false);
          
        // initializing our views.
        ImageView imageView = view.findViewById(R.id.idIV);
        TextView titleTV = view.findViewById(R.id.idTVtitle);
        TextView headingTV = view.findViewById(R.id.idTVheading);
  
        // setting data to our views.
        SliderModal modal = sliderModalArrayList.get(position);
        titleTV.setText(modal.getTitle());
        headingTV.setText(modal.getHeading());
        Picasso.get().load(modal.getImgUrl()).into(imageView);
  
        // after setting the data to our views we 
        // are adding the view to our container.
        container.addView(view);
          
        // at last we are returning the view.
        return view;
    }
  
    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        // this is a destroy view method which
        // is use to remove a view.
        container.removeView((RelativeLayout) object);
    }
}


Java
import android.os.Bundle;
import android.text.Html;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
  
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
  
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 variables for view pager, 
    // lineralyout, adapter and our array list.
    private ViewPager viewPager;
    private LinearLayout dotsLL;
    SliderAdapter adapter;
    private ArrayList sliderModalArrayList;
    private TextView[] dots;
    int size;
    FirebaseFirestore db;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        db = FirebaseFirestore.getInstance();
          
        // initializing all our views.
        viewPager = findViewById(R.id.idViewPager);
        dotsLL = findViewById(R.id.idLLDots);
          
        // in below line we are creating a new array list.
        sliderModalArrayList = new ArrayList<>();
        loadDataFromFirebase();
  
        // calling method to add dots indicator
        addDots(size, 0);
          
        // below line is use to call on page 
        // change listener method.
        viewPager.addOnPageChangeListener(viewListner);
    }
  
    private void loadDataFromFirebase() {
  
        // below line is use to get data from Firebase
        // firestore using collection in android.
        db.collection("SliderData").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.
                                SliderModal sliderModal = d.toObject(SliderModal.class);
                                  
                                // after getting data from Firebase we are
                                // storing that data in our array list
                                sliderModalArrayList.add(sliderModal);
                            }
                            // below line is use to add our array list to adapter class.
                            adapter = new SliderAdapter(MainActivity.this, sliderModalArrayList);
                              
                            // below line is use to set our
                            // adapter to our viw pager.
                            viewPager.setAdapter(adapter);
                              
                            // we are storing the size of our 
                            // array list in a variable.
                            size = sliderModalArrayList.size();
                        } 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();
            }
        });
    }
      
    private void addDots(int size, int pos) {
        // inside this method we are
        // creating a new text view.
        dots = new TextView[size];
          
        // below line is use to remove all 
        // the views from the linear layout.
        dotsLL.removeAllViews();
          
        // running a for loop to add number
        // of dots to our slider.
        for (int i = 0; i < size; i++) {
            // below line is use to add the dots 
            // and modify its color.
            dots[i] = new TextView(this);
            dots[i].setText(Html.fromHtml("•"));
            dots[i].setTextSize(35);
              
            // below line is called when the
            // dots are not selected.
            dots[i].setTextColor(getResources().getColor(R.color.white));
            dotsLL.addView(dots[i]);
        }
        if (dots.length > 0) {
            // this line is called when the dots 
            // inside linear layout are selected
            dots[pos].setTextColor(getResources().getColor(R.color.purple_200));
        }
    }
  
    // creating a method for view pager for on page change listener.
    ViewPager.OnPageChangeListener viewListner = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
  
        }
  
        @Override
        public void onPageSelected(int position) {
            // we are calling our dots method to 
            // change the position of selected dots.
            addDots(size, position);
        }
  
        @Override
        public void onPageScrollStateChanged(int state) {
  
        }
    };
}


步骤4:使用activity_main.xml文件

导航到应用程序> res>布局> activity_main.xml,然后将以下代码添加到该文件中。以下是activity_main.xml文件的代码。

XML格式



  
    
    
      
    
  
        
  
        
        
  
        
        

步骤5:为我们的滑块项目创建布局文件

现在,我们将创建一个要显示在滑块中的项目。因此,要创建新的布局,请导航至应用程序> res>布局>右键单击它>单击New>布局资源文件,并将其命名为slider_layout ,并向其添加以下代码。

XML格式



  
    
    
  
    
    
      
    
    
      

步骤6:创建一个Modal类来存储Slider项的所有数据

要创建新的Modal类,请导航至应用程序> Java >应用程序的包名称>右键单击它,然后单击New> Java class并将其命名为SliderModal 。创建此类后,将以下代码添加到其中。

Java

public class SliderModal {
  
    // string variable for storing title,
    // image url and description.
    private String title;
    private String heading;
    private String imgUrl;
  
    public SliderModal() {
        // empty constructor is required
        // when using firebase
    }
  
    // creating getter methods.
    public String getTitle() {
        return title;
    }
  
    public void setTitle(String title) {
        this.title = title;
    }
  
    public String getHeading() {
        return heading;
    }
  
    // creating setter methods
    public void setHeading(String heading) {
        this.heading = heading;
    }
  
    public String getImgUrl() {
        return imgUrl;
    }
  
    public void setImgUrl(String imgUrl) {
        this.imgUrl = imgUrl;
    }
      
    // constructor for our modal class
    public SliderModal(String title, String heading, String imgUrl) {
        this.title = title;
        this.heading = heading;
        this.imgUrl = imgUrl;
    }
}

步骤7:创建一个Adapter类,用于将数据设置到每个视图

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

Java

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
  
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
  
import com.squareup.picasso.Picasso;
  
import java.util.ArrayList;
  
public class SliderAdapter extends PagerAdapter {
  
    // creating variables for layout inflater,
    // context and array list.
    LayoutInflater layoutInflater;
    Context context;
    ArrayList sliderModalArrayList;
  
    // creating constructor.
    public SliderAdapter(Context context, ArrayList sliderModalArrayList) {
        this.context = context;
        this.sliderModalArrayList = sliderModalArrayList;
    }
  
    @Override
    public int getCount() {
        // inside get count method returning 
        // the size of our array list.
        return sliderModalArrayList.size();
    }
      
    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        // inside isViewFrombject method we are 
        // returning our Relative layout object.
        return view == (RelativeLayout) object;
    }
  
    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        // in this method we will initialize all our layout items
        // and inflate our layout file as well.
        layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
          
        // below line is use to inflate the layout file which we created.
        View view = layoutInflater.inflate(R.layout.slider_layout, container, false);
          
        // initializing our views.
        ImageView imageView = view.findViewById(R.id.idIV);
        TextView titleTV = view.findViewById(R.id.idTVtitle);
        TextView headingTV = view.findViewById(R.id.idTVheading);
  
        // setting data to our views.
        SliderModal modal = sliderModalArrayList.get(position);
        titleTV.setText(modal.getTitle());
        headingTV.setText(modal.getHeading());
        Picasso.get().load(modal.getImgUrl()).into(imageView);
  
        // after setting the data to our views we 
        // are adding the view to our container.
        container.addView(view);
          
        // at last we are returning the view.
        return view;
    }
  
    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        // this is a destroy view method which
        // is use to remove a view.
        container.removeView((RelativeLayout) object);
    }
}

步骤8:使用MainActivity。 Java文件

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

Java

import android.os.Bundle;
import android.text.Html;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
  
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
  
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 variables for view pager, 
    // lineralyout, adapter and our array list.
    private ViewPager viewPager;
    private LinearLayout dotsLL;
    SliderAdapter adapter;
    private ArrayList sliderModalArrayList;
    private TextView[] dots;
    int size;
    FirebaseFirestore db;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        db = FirebaseFirestore.getInstance();
          
        // initializing all our views.
        viewPager = findViewById(R.id.idViewPager);
        dotsLL = findViewById(R.id.idLLDots);
          
        // in below line we are creating a new array list.
        sliderModalArrayList = new ArrayList<>();
        loadDataFromFirebase();
  
        // calling method to add dots indicator
        addDots(size, 0);
          
        // below line is use to call on page 
        // change listener method.
        viewPager.addOnPageChangeListener(viewListner);
    }
  
    private void loadDataFromFirebase() {
  
        // below line is use to get data from Firebase
        // firestore using collection in android.
        db.collection("SliderData").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.
                                SliderModal sliderModal = d.toObject(SliderModal.class);
                                  
                                // after getting data from Firebase we are
                                // storing that data in our array list
                                sliderModalArrayList.add(sliderModal);
                            }
                            // below line is use to add our array list to adapter class.
                            adapter = new SliderAdapter(MainActivity.this, sliderModalArrayList);
                              
                            // below line is use to set our
                            // adapter to our viw pager.
                            viewPager.setAdapter(adapter);
                              
                            // we are storing the size of our 
                            // array list in a variable.
                            size = sliderModalArrayList.size();
                        } 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();
            }
        });
    }
      
    private void addDots(int size, int pos) {
        // inside this method we are
        // creating a new text view.
        dots = new TextView[size];
          
        // below line is use to remove all 
        // the views from the linear layout.
        dotsLL.removeAllViews();
          
        // running a for loop to add number
        // of dots to our slider.
        for (int i = 0; i < size; i++) {
            // below line is use to add the dots 
            // and modify its color.
            dots[i] = new TextView(this);
            dots[i].setText(Html.fromHtml("•"));
            dots[i].setTextSize(35);
              
            // below line is called when the
            // dots are not selected.
            dots[i].setTextColor(getResources().getColor(R.color.white));
            dotsLL.addView(dots[i]);
        }
        if (dots.length > 0) {
            // this line is called when the dots 
            // inside linear layout are selected
            dots[pos].setTextColor(getResources().getColor(R.color.purple_200));
        }
    }
  
    // creating a method for view pager for on page change listener.
    ViewPager.OnPageChangeListener viewListner = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
  
        }
  
        @Override
        public void onPageSelected(int position) {
            // we are calling our dots method to 
            // change the position of selected dots.
            addDots(size, position);
        }
  
        @Override
        public void onPageScrollStateChanged(int state) {
  
        }
    };
}

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

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

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

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

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

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

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

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

您必须单击“开始收集选项”,并将收集名称指定为SliderData 。创建集合后,您必须单击“自动识别”选项以创建第一个文档。在其中创建三个字段,分别是titleheadingimgUrl,并在该字段中添加值。在Firebase控制台内以类似的方式添加多个文档。之后,运行您的应用程序,并查看该应用程序的输出。

将这些数据添加到Firebase后,运行您的应用程序并查看该应用程序的输出。

输出:

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