Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to Create a Wallpaper App in Android Studio?

  • Last Updated : 15 Nov, 2021

Almost all Android devices are having a wallpaper set on their home screen. For setting this wallpaper to the screen many Android devices provides a Wallpaper Application where we can browse different types of wallpapers based on various categories. In this article we will look at, building a similar application in Android devices in Android Studio. 

What we are going to build in this article? 

We will be building a simple wallpaper application in which we will be adding functionality to filter wallpapers based on various categories. Along with that we will be also adding a search bar to search wallpapers based on the user search query. Below is the video in which we will get to see what we are going to build in this article. Note that we are going to implement this project using the Java language. 

Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!

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: Before going to the coding section first you have to do some pre-task

Go to the app > res > values > colors.xml section and set the colors for your app.

XML




<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="purple_200">#0F9D58</color>
    <color name="purple_500">#0F9D58</color>
    <color name="purple_700">#0F9D58</color>
    <color name="teal_200">#0F9D58</color>
    <color name="teal_700">#FF018786</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>
  
    <color name="blac_shade_1">#292D36</color>
    <color name="black_shade_2">#272B33</color>
    <color name="black_shade_3">#22252D</color>
    <color name="dark_blue_shade">#021853</color>
    <color name="yellow">#ffa500</color>
  
</resources>


Step 3: Adding dependency in build.gradle file

Go to the Gradle Scripts > build.gradle (Module: app) section and import the following dependencies and click the “sync Now” on the above pop-up.

implementation 'com.github.bumptech.glide:glide:4.11.0'
implementation 'com.android.volley:volley:1.1.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
implementation 'com.github.Shashank02051997:FancyToast-Android:0.1.8'

Navigate to the app > Gradle Scripts > build.gradle(Project level) and in this file, we have to go to add mavenCentral in allProjects section. 

allprojects {
    repositories {
        google()
        mavenCentral()
        // add below line 
        maven { url "https://jitpack.io" }
        jcenter() 
    }
}

After adding this dependency we simply have to sync our project to install the packages of all dependencies. 

Step 4: Adding Internet Permissions in the AndroidManifest.xml file



Navigate to the app > AndroidManifest.xml file and add the below line of code in it.  

XML




<uses-permission android:name="android.permission.SET_WALLPAPER" />
<uses-permission android:name="android.permission.INTERNET" />


Step 5: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black_shade_1"
    tools:context=".MainActivity">
  
    <ImageView
        android:id="@+id/idIVIcon"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_centerInParent="true" />
  
    <TextView
        android:id="@+id/idTVHeading"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/idIVIcon"
        android:layout_marginTop="20dp"
        android:fontFamily="@font/adamina"
        android:gravity="center"
        android:text="@string/app_name"
        android:textAlignment="center"
        android:textColor="@color/white"
        android:textSize="20sp" />
  
    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/idTVHeading"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp" />
      
</RelativeLayout>


Step 6: Creating a new Java Modal Class for storing the data of categories

Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as CategoryRVModal add below code to it. Comments are added in the code to get to know in more detail.

Java




public class CategoryRVModal {
    // creating variable font category 
    // and image url on below line.
    private String category;
    private String imgUrl;
  
    public CategoryRVModal(String category, String imgUrl) {
        this.category = category;
        this.imgUrl = imgUrl;
    }
  
    // creating a constructor, getter and setter methods.
    public String getCategory() {
        return category;
    }
  
    public void setCategory(String category) {
        this.category = category;
    }
  
    public String getImgUrl() {
        return imgUrl;
    }
  
    public void setImgUrl(String imgUrl) {
        this.imgUrl = imgUrl;
    }
}


Step 7: Creating drawable files 

We will be creating two drawable files one will be for our button background. For creating this file, navigate to the app > res > drawable > Right-click on it > New and name it as button_back and add the code below. Comments are added in the code to get to know in more detail. 



XML




<?xml version="1.0" encoding="utf-8"?>
    android:shape="rectangle">
    <solid android:color="@color/black_shade_1" />
    <!--stroke for our button-->
    <stroke
        android:width="1dp"
        android:color="@color/white" />
    <corners android:radius="20dp" />
</shape>


After that, we will be creating a drawable file for our search bar background. Similarly, create another drawable file and name it as search_back and add the below code to it. 

XML




<?xml version="1.0" encoding="utf-8"?>
    android:shape="rectangle">
    <corners android:radius="15dp" />
    <solid android:color="@color/white" />
</shape>


Step 8: Creating a layout file for category_rv_item

Navigate to the app > res > layout > category_rv_item and add the below code to it. Comments are added in the code to get to know in more detail. 

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 
    android:layout_width="130dp"
    android:layout_height="70dp"
    android:layout_gravity="center"
    android:layout_margin="5dp"
    app:cardCornerRadius="8dp">
  
    <!--creating a relative layout on below line-->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
  
        <!--creating an image view on below line-->
        <ImageView
            android:id="@+id/idIVCategory"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"
            android:src="@color/purple_200" />
  
        <!--creating a text view on below line-->
        <TextView
            android:id="@+id/idTVCategory"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:gravity="center_horizontal"
            android:text="Category"
            android:textAlignment="center"
            android:textColor="@color/white"
            android:textStyle="bold" />
  
    </RelativeLayout>
      
</androidx.cardview.widget.CardView>


Step 9: Creating a layout file for the item in Wallpaper RecyclerView

Navigate to the app > res > layout > Right-click on it > New > Layout Resource file and name it as wallpaper_rv_item and add below code to it. Comments are added in the code to get to know in more detail. 

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 
    android:id="@+id/idCVWallpaper"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:layout_margin="6dp"
    app:cardCornerRadius="8dp">
  
    <!--creating an image view for displaying wallpaper-->
    <ImageView
        android:id="@+id/idIVWallpaper"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"
        android:src="@mipmap/ic_launcher" />
      
</androidx.cardview.widget.CardView>


Step 10: Creating an Adapter class for setting data to items of RecyclerView



Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as WallpaperRVAdapter and add the below code to it. Comments are added in the code to get to know in more detail. 

Java




import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
  
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
  
import com.bumptech.glide.Glide;
  
import java.util.ArrayList;
  
public class WallpaperRVAdapter extends RecyclerView.Adapter<WallpaperRVAdapter.ViewHolder> {
    // creating variables for array list and context.
    private ArrayList<String> wallPaperList;
    private Context context;
  
    // creating a constructor.
    public WallpaperRVAdapter(ArrayList<String> wallPaperList, Context context) {
        this.wallPaperList = wallPaperList;
        this.context = context;
    }
  
    @NonNull
    @Override
    public WallpaperRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // inflating our layout file on below line.
        View view = LayoutInflater.from(context).inflate(R.layout.wallpaper_rv_item, parent, false);
        return new ViewHolder(view);
    }
  
    @Override
    public void onBindViewHolder(@NonNull WallpaperRVAdapter.ViewHolder holder, int position) {
        // setting data to all our views.
        Glide.with(context).load(wallPaperList.get(position)).into(holder.wallpaperIV);
        // adding on click listener to item view.
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // passing data through intent on below line.
                Intent i = new Intent(context, WallpaperActivity.class);
                i.putExtra("imgUrl", wallPaperList.get(position));
                context.startActivity(i);
            }
        });
    }
  
    @Override
    public int getItemCount() {
        return wallPaperList.size();
    }
  
    public class ViewHolder extends RecyclerView.ViewHolder {
          
        // creating variables for our views
        // which are created in layout file.
        private CardView imageCV;
        private ImageView wallpaperIV;
  
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing all the variables.
            wallpaperIV = itemView.findViewById(R.id.idIVWallpaper);
            imageCV = itemView.findViewById(R.id.idCVWallpaper);
        }
    }
}


Step 11: Creating an Adapter class for our Category RecyclerView

Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as CategoryRVAdapter and add the below code to it. Comments are added in the code to get to know in more detail.

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 androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
  
import com.bumptech.glide.Glide;
  
import java.util.ArrayList;
  
public class CategoryRVAdapter extends RecyclerView.Adapter<CategoryRVAdapter.ViewHolder> {
      
    // creating variables for 
    // array list and context and interface.
    private ArrayList<CategoryRVModal> categoryRVModals;
    private Context context;
    private CategoryClickInterface categoryClickInterface;
  
    // creating a constructor.
    public CategoryRVAdapter(ArrayList<CategoryRVModal> categoryRVModals, Context context, CategoryClickInterface categoryClickInterface) {
        this.categoryRVModals = categoryRVModals;
        this.context = context;
        this.categoryClickInterface = categoryClickInterface;
    }
  
    @NonNull
    @Override
    public CategoryRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // inflating our layout file on below line.
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.category_rv_item, parent, false);
        return new CategoryRVAdapter.ViewHolder(view);
    }
  
    @Override
    public void onBindViewHolder(@NonNull CategoryRVAdapter.ViewHolder holder, int position) {
        // setting data to all our views.
        CategoryRVModal modal = categoryRVModals.get(position);
        holder.categoryTV.setText(modal.getCategory());
        if (!modal.getImgUrl().isEmpty()) {
            Glide.with(context).load(modal.getImgUrl()).into(holder.categoryIV);
  
        } else {
            holder.categoryIV.setImageResource(R.drawable.ic_launcher_background);
        }
        // adding on click listener to item view on below line.
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // passing position with interface.
                categoryClickInterface.onCategoryClick(position);
            }
        });
    }
  
    @Override
    public int getItemCount() {
        return categoryRVModals.size();
    }
  
    // creating an interface on below line.
    public interface CategoryClickInterface {
        void onCategoryClick(int position);
    }
  
    public class ViewHolder extends RecyclerView.ViewHolder {
        // creating variables on below line.
        private TextView categoryTV;
        private ImageView categoryIV;
  
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing all variables on below line.
            categoryIV = itemView.findViewById(R.id.idIVCategory);
            categoryTV = itemView.findViewById(R.id.idTVCategory);
        }
    }
}


Step 12: Creating a new Activity for displaying a single Wallpaper

Navigate to the app > java > your app’s package name > Right-click on it > New > Activity > Select Empty Activity and name it as WallpaperActivity and now we will move towards working of activity_wallpaper.xml

Step 13: Working with activity_wallpaper.xml file

Navigate to the app > res > layout > activity_wallpaper.xml and add the below code to it. Comments are added in the code to get to know in more detail. 

XML






<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".WallpaperActivity">
  
    <!--creating an image view for displaying image-->
    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop" />
  
    <!--creating a button to set the wallpaper-->
    <Button
        android:id="@+id/idBtnSetWallpaper"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="20dp"
        android:layout_marginEnd="20dp"
        android:layout_marginBottom="10dp"
        android:background="@drawable/button_back"
        android:text="Set Wallpaper"
        android:textAllCaps="false"
        android:textColor="@color/white"
        android:textSize="15sp"
        app:backgroundTint="#A6000000" />
  
    <!--creating a progress bar for loading indicator-->
    <ProgressBar
        android:id="@+id/idPBLoading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />
  
</RelativeLayout>


Step 14: Working with the WallpaperActivity.java file

Navigate to the app > java > your app’s package name > WallpaperActivity.java file and add the below code to it. Comments are added in the code to get to know in more detail. 

Java




import android.app.WallpaperManager;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
  
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
  
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.shashank.sony.fancytoastlib.FancyToast;
  
import java.io.IOException;
  
public class WallpaperActivity extends AppCompatActivity {
  
    // on below line we are creating variables 
    // for imageview and wallpaper manager
    WallpaperManager wallpaperManager;
    ImageView image;
    String url;
    private ProgressBar loadingPB;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wallpaper);
          
        // initializing all variables on below line.
        url = getIntent().getStringExtra("imgUrl");
        image = findViewById(R.id.image);
        loadingPB = findViewById(R.id.idPBLoading);
          
        // calling glide to load image from url on below line.
        Glide.with(this).load(url).listener(new RequestListener<Drawable>() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                // making progress bar visibility 
                // to gone on below line.
                loadingPB.setVisibility(View.GONE);
                return false;
            }
  
            @Override
            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                // making progress bar visibility to gone
                // on below line when image is ready.
                loadingPB.setVisibility(View.GONE);
                return false;
            }
        }).into(image);
  
        wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
        Button setWallpaper = findViewById(R.id.idBtnSetWallpaper);
  
        // on below line we are adding on click 
        // listener to our set wallpaper button.
        setWallpaper.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Glide.with(WallpaperActivity.this)
                        .asBitmap().load(url)
                        .listener(new RequestListener<Bitmap>() {
                                      @Override
                                      public boolean onLoadFailed(@Nullable GlideException e, Object o, Target<Bitmap> target, boolean b) {
                                          Toast.makeText(WallpaperActivity.this, "Fail to load image..", Toast.LENGTH_SHORT).show();
                                          return false;
                                      }
  
                                      @Override
                                      public boolean onResourceReady(Bitmap bitmap, Object o, Target<Bitmap> target, DataSource dataSource, boolean b) {
                                          // on below line we are setting wallpaper using 
                                          // wallpaper manager on below line.
                                          try {
                                              wallpaperManager.setBitmap(bitmap);
                                              Toast.makeText(WallpaperActivity.this, "Wallpaper Set to Home screen.", Toast.LENGTH_SHORT).show();
                                          } catch (IOException e) {
                                              // on below line we are handling exception.
                                              Toast.makeText(WallpaperActivity.this, "Fail to set wallpaper", Toast.LENGTH_SHORT).show();
                                              e.printStackTrace();
                                          }
                                          return false;
                                      }
                                  }
                        ).submit();
                // displaying custom toast on below line.
                FancyToast.makeText(WallpaperActivity.this, "Wallpaper Set to Home Screen", FancyToast.LENGTH_LONG, FancyToast.SUCCESS, false).show();
            }
        });
    }
}


Step 15: Generating the API key for Pixels API

For generating an API for using Pexels API we simply have to go to the Pexels site here. After going to this site we simply have to signup on this website and create an account. After creating a new account you have to simply login to your account. After logging in to your account. You will get to see the below screen. 

In this screen, we simply have to click on the account option arrow then simply select the Image and Video API option to get to see our API key. After clicking on that option a new screen will open in which we simply have to click on the Your API key option to get our API key. Then you will get to see your API which is shown below. 

Now we will be using this API key in our application. 

Step 16: 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.

Java




import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
  
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
  
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
  
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
  
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
  
public class MainActivity extends AppCompatActivity implements CategoryRVAdapter.CategoryClickInterface {
  
    // creating variables for recyclerview,
    // progress bar, adapter and array list,
    // edittext and others.
    private RecyclerView categoryRV, wallpaperRV;
    private ProgressBar loadingPB;
    private ArrayList<CategoryRVModal> categoryRVModals;
    private ArrayList<String> wallpaperArrayList;
    private CategoryRVAdapter categoryRVAdapter;
    private WallpaperRVAdapter wallpaperRVAdapter;
    private EditText searchEdt;
    private ImageView searchIV;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_screen);
  
        // initializing all variables on below line.
        categoryRV = findViewById(R.id.idRVCategories);
        wallpaperRV = findViewById(R.id.idRVWallpapers);
        searchEdt = findViewById(R.id.idEdtSearch);
        searchIV = findViewById(R.id.idIVSearch);
        loadingPB = findViewById(R.id.idPBLoading);
        wallpaperArrayList = new ArrayList<>();
        categoryRVModals = new ArrayList<>();
  
        // creating a layout manager for
        // recycler view which is our category.
        LinearLayoutManager manager1 = new LinearLayoutManager(MainActivity.this, RecyclerView.HORIZONTAL, false);
  
        // initializing our adapter class on below line.
        wallpaperRVAdapter = new WallpaperRVAdapter(wallpaperArrayList, this);
        categoryRVAdapter = new CategoryRVAdapter(categoryRVModals, this, this);
  
        // setting layout manager to our
        // category recycler view as horizontal.
        categoryRV.setLayoutManager(manager1);
        categoryRV.setAdapter(categoryRVAdapter);
  
        // creating a grid layout manager
        // for our wallpaper recycler view.
        GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
  
        // setting layout manager and
        // adapter to our recycler view.
        wallpaperRV.setLayoutManager(layoutManager);
        wallpaperRV.setAdapter(wallpaperRVAdapter);
  
        // on below line we are calling method to
        // get categories to add data in array list.
        getCategories();
  
        // on below line we are calling get wallpaper
        // method to get data in wallpaper array list.
        getWallpapers();
  
        // on below line we are adding on click listener
        // for search image view on below line.
        searchIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // inside on click method we are getting data from
                // our search edittext and validating if the input field is empty or not.
                String searchStr = searchEdt.getText().toString();
                if (searchStr.isEmpty()) {
                    Toast.makeText(MainActivity.this, "Please enter something to search", Toast.LENGTH_SHORT).show();
                } else {
                    // on below line we are calling a get wallpaper
                    // method to get wallpapers by category.
                    getWallpapersByCategory(searchStr);
                }
            }
        });
    }
  
    // on below line we are creating a method
    // to get the wallpaper by category.
    private void getWallpapersByCategory(String category) {
        // on below line we are
        // clearing our array list.
        wallpaperArrayList.clear();
        // on below line we are making visibility
        // of our progress bar as gone.
        loadingPB.setVisibility(View.VISIBLE);
        // on below line we are creating a string
        // variable for our url and adding url to it.
        String url = "https://api.pexels.com/v1/search?query=" + category + "&per_page=30&page=1";
        // on below line we are creating a
        // new variable for our request queue.
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
        // on below line we are making a json object
        // request to get the data from url .
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                // on below line we are extracting the data from our
                // response and passing it to our array list.
                try {
                    loadingPB.setVisibility(View.GONE);
                    // on below line we are extracting json data.
                    JSONArray photos = response.getJSONArray("photos");
                    for (int i = 0; i < photos.length(); i++) {
                        JSONObject photoObj = photos.getJSONObject(i);
                        String imgUrl = photoObj.getJSONObject("src").getString("portrait");
                        // on below line we are passing
                        // data to our array list
                        wallpaperArrayList.add(imgUrl);
                    }
                    // here we are notifying adapter
                    // that data has changed in our list.
                    wallpaperRVAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    // handling json exception
                    // on below line.
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // displaying a simple toast message on error response.
                Toast.makeText(MainActivity.this, "Fail to get data..", Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            public Map<String, String> getHeaders() {
                // in this method passing headers as
                // key along with value as API keys.
                HashMap<String, String> headers = new HashMap<>();
                headers.put("Authorization", "Enter your key");
                // at last returning headers.
                return headers;
            }
        };
        queue.add(jsonObjectRequest);
    }
  
    private void getWallpapers() {
        // on below line we are
        // clearing our array list.
        wallpaperArrayList.clear();
        // changing visibility of our
        // progress bar to gone.
        loadingPB.setVisibility(View.VISIBLE);
        // creating a variable for our url.
        // on below line we are creating a
        // new variable for our request queue.
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
        // on below line we are making a json
        // object request to get the data from url .
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                // on below line we are extracting the data from
                // our response and passing it to our array list.
                loadingPB.setVisibility(View.GONE);
                try {
                    // on below line we are extracting json data.
                    JSONArray photos = response.getJSONArray("photos");
                    for (int i = 0; i < photos.length(); i++) {
                        JSONObject photoObj = photos.getJSONObject(i);
                        String imgUrl = photoObj.getJSONObject("src").getString("portrait");
                        // on below line we are passing
                        // data to our array list
                        wallpaperArrayList.add(imgUrl);
                    }
                    wallpaperRVAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    // handling json exception
                    // on below line.
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // displaying a toast message on error response.
                Toast.makeText(MainActivity.this, "Fail to get data..", Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            public Map<String, String> getHeaders() {
                // in this method passing headers as
                // key along with value as API keys.
                HashMap<String, String> headers = new HashMap<>();
                headers.put("Authorization", "Enter your key");
                // at last returning headers.
                return headers;
            }
        };
        queue.add(jsonObjectRequest);
    }
  
    private void getCategories() {
        // on below lines we are adding data to our category array list.
        categoryRVModals.add(new CategoryRVModal("Nature", "https://images.pexels.com/photos/2387873/pexels-photo-2387873.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"));
        categoryRVModals.add(new CategoryRVModal("Travel", "https://images.pexels.com/photos/672358/pexels-photo-672358.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"));
        categoryRVModals.add(new CategoryRVModal("Architecture", "https://images.pexels.com/photos/256150/pexels-photo-256150.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"));
        categoryRVModals.add(new CategoryRVModal("Arts", "https://images.pexels.com/photos/1194420/pexels-photo-1194420.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"));
        categoryRVModals.add(new CategoryRVModal("Music", "https://images.pexels.com/photos/4348093/pexels-photo-4348093.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"));
        categoryRVModals.add(new CategoryRVModal("Abstract", "https://images.pexels.com/photos/2110951/pexels-photo-2110951.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"));
        categoryRVModals.add(new CategoryRVModal("Cars", "https://images.pexels.com/photos/3802510/pexels-photo-3802510.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"));
        categoryRVModals.add(new CategoryRVModal("Flowers", "https://images.pexels.com/photos/1086178/pexels-photo-1086178.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"));
    }
  
    @Override
    public void onCategoryClick(int position) {
        // on below line we are getting category from our
        // array list and calling a method
        // to get wallpapers by category.
        String category = categoryRVModals.get(position).getCategory();
        getWallpapersByCategory(category);
    }
}


Now run your application and see the output of the application. 

Note: All drawable files used in the app are present in the drawable folder. Check out the project on below GitHub link. 

GitHub Link: https://github.com/ChaitanyaMunje/Wallpaper-App

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!