How to Create Dynamic Auto Image Slider in Android with Firebase?
We have seen many apps that display images in the slider format as that of banners which slide automatically. This type of feature of the auto image slider is seen in many E-commerce sites. This feature is seen in many apps which are having images in them. In this article, we will take a look at How to Create a dynamic Auto Image Slider in Android. So we will be using Firebase to load the images inside our slider with Firebase. With the help of Firebase, these images can be updated in real-time without updating the app. For the implementation of SliderView, we will be using the SliderView library.
What we are going to build in this article?
We will be creating a simple application in which we will be creating a slider view and we will be displaying images from Firebase inside our SliderView. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step by Step Implementation
Step 1: Create a new Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Connect your app to Firebase
After creating a new project, navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot.
Inside that column Navigate to Firebase Cloud Firestore. Click on that option and you will get to see two options on Connect app to Firebase and Add Cloud Firestore to your app. Click on Connect now option and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. After connecting your app to Firebase you will get to see the below screen.
After that verify that dependency for Firebase Firestore database has been added to our Gradle file. Navigate to the app > Gradle Scripts inside that file to check whether the below dependency is added or not. If the below dependency is not present in your build.gradle file. Add the below dependency in the dependencies section.
implementation ‘com.google.firebase:firebase-firestore:22.0.1’
After adding this dependency we will add the dependency for our SliderView and Picasso which will be used to load images from their image URL.
implementation ‘com.github.smarteist:autoimageslider:1.3.9’
implementation ‘com.squareup.picasso:picasso:2.71828’
After adding these dependencies sync your project. Now we will move towards the AndroidManifest.xml part of the app.
Step 3: Working with AndroidManifest.xml file
For adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml and Inside that file add the below permissions to it.
<!--Permissions for internet-->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Step 4: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.
<?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"
tools:context=".MainActivity">
<!--Slider view for displaying our sliding images-->
<com.smarteist.autoimageslider.SliderView
android:id="@+id/slider"
android:layout_width="match_parent"
android:layout_height="150dp"
app:sliderAnimationDuration="600"
app:sliderAutoCycleDirection="back_and_forth"
app:sliderIndicatorAnimationDuration="600"
app:sliderIndicatorEnabled="false"
app:sliderIndicatorGravity="center_horizontal|bottom"
app:sliderIndicatorMargin="15dp"
app:sliderIndicatorOrientation="horizontal"
app:sliderIndicatorPadding="3dp"
app:sliderIndicatorRadius="2dp"
app:sliderIndicatorSelectedColor="#5A5A5A"
app:sliderIndicatorUnselectedColor="#FFF"
app:sliderScrollTimeInSec="1" />
</LinearLayout>
Step 5: Creating a Modal Class for storing the URL of our images in Slider
Now we will create a modal class for storing our URLs for our images. For creating a new java class. Navigate to the app > java > your app’s package name and Right-click on it and click on New > Java Class. Give a name to your java class and add the below code to it. Here we have given the name as SliderData. Below is the code for the SliderData.java file.
public class SliderData {
// string for our image url.
private String imgUrl;
// empty constructor which is
// required when using Firebase.
public SliderData() {
}
// Constructor
public SliderData(String imgUrl) {
this.imgUrl = imgUrl;
}
// Getter method.
public String getImgUrl() {
return imgUrl;
}
// Setter method.
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
}
Step 6: Create a layout file for our items inside our SliderView
For creating a new layout file for displaying inside our SliderView, navigate to the app > res > layout > Right-click on it and click on New > Layout Resource file and give a name to your file. Here we have given the file name as image_slider_item and add the below code to it.
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="8dp">
<!--Image to be displayed in our ImageView-->
<ImageView
android:id="@+id/idIVimage"
android:layout_width="match_parent"
android:layout_height="200dp"
android:contentDescription="@string/app_name" />
</androidx.cardview.widget.CardView>
Step 7: Creating an Adapter class for setting data inside our Slider items
For creating an Adapter class, navigate to the app > java > your app’s package name > Right-click on it > New > java class and name your class as SliderAdapter and add below code to it.
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.smarteist.autoimageslider.SliderViewAdapter;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class SliderAdapter extends SliderViewAdapter<SliderAdapter.SliderAdapterVH> {
// creating a variable for
// context and array list.
private Context context;
private List<SliderData> mSliderItems = new ArrayList<>();
// constructor for our adapter class.
public SliderAdapter(Context context, List<SliderData> mSliderItems) {
this.context = context;
this.mSliderItems = mSliderItems;
}
@Override
public SliderAdapterVH onCreateViewHolder(ViewGroup parent) {
// inside the on Create view holder method we are
// inflating our layout file which we have created.
View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.image_slider_item, null);
return new SliderAdapterVH(inflate);
}
@Override
public void onBindViewHolder(SliderAdapterVH viewHolder, int position) {
// inside on bind view holder method we are
// getting url of image from our modal class
// and setting that url for image inside our
// image view using Picasso.
final SliderData sliderItem = mSliderItems.get(position);
Picasso.get().load(sliderItem.getImgUrl()).into(viewHolder.imageView);
}
@Override
public int getCount() {
// returning the size of our array list.
return mSliderItems.size();
}
// view holder class for initializing our view holder.
class SliderAdapterVH extends SliderViewAdapter.ViewHolder {
// variables for our view and image view.
View itemView;
ImageView imageView;
public SliderAdapterVH(View itemView) {
super(itemView);
// initializing our views.
imageView = itemView.findViewById(R.id.idIVimage);
this.itemView = itemView;
}
}
}
Step 8: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
import android.os.Bundle;
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.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.smarteist.autoimageslider.SliderAnimations;
import com.smarteist.autoimageslider.SliderView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
// creating variables for our adapter, array list,
// firebase firestore and our sliderview.
private SliderAdapter adapter;
private ArrayList<SliderData> sliderDataArrayList;
FirebaseFirestore db;
private SliderView sliderView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// creating a new array list for our array list.
sliderDataArrayList = new ArrayList<>();
// initializing our slider view and
// firebase firestore instance.
sliderView = findViewById(R.id.slider);
db = FirebaseFirestore.getInstance();
// calling our method to load images.
loadImages();
}
private void loadImages() {
// getting data from our collection and after
// that calling a method for on success listener.
db.collection("Slider").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
// inside the on success method we are running a for loop
// and we are getting the data from Firebase Firestore
for (QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) {
// after we get the data we are passing inside our object class.
SliderData sliderData = documentSnapshot.toObject(SliderData.class);
SliderData model = new SliderData();
// below line is use for setting our
// image url for our modal class.
model.setImgUrl(sliderData.getImgUrl());
// after that we are adding that
// data inside our array list.
sliderDataArrayList.add(model);
// after adding data to our array list we are passing
// that array list inside our adapter class.
adapter = new SliderAdapter(MainActivity.this, sliderDataArrayList);
// below line is for setting adapter
// to our slider view
sliderView.setSliderAdapter(adapter);
// below line is for setting animation to our slider.
sliderView.setSliderTransformAnimation(SliderAnimations.SIMPLETRANSFORMATION);
// below line is for setting auto cycle duration.
sliderView.setAutoCycleDirection(SliderView.AUTO_CYCLE_DIRECTION_BACK_AND_FORTH);
// below line is for setting
// scroll time animation
sliderView.setScrollTimeInSec(3);
// below line is for setting auto
// cycle animation to our slider
sliderView.setAutoCycle(true);
// below line is use to start
// the animation of our slider view.
sliderView.startAutoCycle();
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// if we get any error from Firebase we are
// displaying a toast message for failure
Toast.makeText(MainActivity.this, "Fail to load slider data..", Toast.LENGTH_SHORT).show();
}
});
}
}
Step 9: Adding the data to our Firebase Firestore Console
Go to Firebase and click on Go to Console option on the top right corner.
After clicking on this screen you will get to see the below screen with your all project inside that select your project.
Inside that screen click n Firebase Firestore Database in the left window.
After clicking on the Create Database option you will get to see the below screen.
Inside this screen, we have to select the Start in test mode option. We are using test mode because we are not setting authentication inside our app. So we are selecting Start in test mode. After selecting test mode click on the Next option and you will get to see the below screen.
Inside this screen, we just have to click on the Enable button to enable our Firebase Firestore database. After completing this process we just have to add data inside our Firebase Firestore console for adding images to our slider. For adding data click on the Start collection option and you will get to see the below screen.
After adding this data click on the Next option and you will get to see the below screen.
Add the data inside our Firebase Firestore console and click on save. Your first image to the slider has been added. Similarly, add more images by clicking on the “Add document” button.
After adding these images run your app and you will get to see the output on the below screen.
Contact Us