Saturday, December 28, 2024
Google search engine
HomeLanguagesJavaHow to Read Data from Google Spreadsheet in Android?

How to Read Data from Google Spreadsheet in Android?

Many apps have to display statistical data inside their applications and they stores all their data in the excel file or a spreadsheet. But it is not every time possible to add the whole data in the database to use inside our app. In this article, we will take a look at reading this data from our Excel sheet in Android App in Android Studio. 

What we are going to build in this article? 

We will be building a simple application in which we will be displaying data from our excel sheet which we have already created and we will read the entries from that excel sheet and display that list of data in our recycler view. A sample video 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: Add the below dependency in your build.gradle file

Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section.   

implementation ‘com.android.volley:volley:1.1.1’

// below line is use for image loading library

implementation ‘com.squareup.picasso:picasso:2.71828’

After adding this dependency sync your project and now move towards the AndroidManifest.xml part.  

Step 3: Adding internet permissions to the AndroidManifest.xml file

Navigate to the app > AndroidManifest.xml and add the below code to it. 

XML




<!--permissions for INTERNET-->
<uses-permission android:name="android.permission.INTERNET"/>


 
 

Step 4: Creating a URL for fetching our data from Google Spreadsheet

 

Create a simple Google Spreadsheet which is shown below. Make sure to use the same headers as shown in the below file. 

 

 

After you have created our excel file. Now we have to publish this excel file to use it inside our app. For publishing it.  

 

 

Now we will create a URL in which we will be getting the data in the JSON format. Go to your excel sheet and copy the id of your sheet which is shown in the below screenshot. 

 

https://spreadsheets.google.com/feeds/list/“Enter your ID here”/od6/public/values?alt=json

 

After copying this id paste the id in the below URL and run the URL in your browser. You will get to see all the excel data in JSON format. Now we will use this data in JSON format inside our app. Make sure that you have published your Excel sheet. Otherwise, this method will not work. Now we will use this URL in our app to get the data in JSON format. 

 

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"?>
<!--in this we are displaying a nested scroll view-->
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/idNestedSV"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
   
    <!--recycler view for displaying our list of data
        and we are making nested scroll for our
        recycler view as false-->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/idRVUsers"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:listitem="@layout/user_rv_item" />
   
    <!--we are adding progress bar for thepurpose of loading-->
    <ProgressBar
        android:id="@+id/idPBLoading"
        android:layout_width="wrap_content"
        android:layout_centerInParent="true"
        android:layout_height="wrap_content" />
   
</RelativeLayout>


 
 

 Step 6: Creating a Modal class for storing our data  

 

For storing our data we have to create a new java class. For creating a new java class, Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as UserModal and add the below code to it. 

 

Java




public class UserModal {
   
    // variables for our first name,
    // last name, email and avatar
    private String first_name;
    private String last_name;
    private String email;
    private String avatar;
 
    public String getFirst_name() {
        return first_name;
    }
 
    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }
 
    public String getLast_name() {
        return last_name;
    }
 
    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }
 
    public String getEmail() {
        return email;
    }
 
    public void setEmail(String email) {
        this.email = email;
    }
 
    public String getAvatar() {
        return avatar;
    }
 
    public void setAvatar(String avatar) {
        this.avatar = avatar;
    }
 
    public UserModal(String first_name, String last_name, String email, String avatar) {
        this.first_name = first_name;
        this.last_name = last_name;
        this.email = email;
        this.avatar = avatar;
    }
}


 
 

Step 7: Creating a layout file for each item of our RecyclerView  

 

Navigate to the app > res > layout > Right-click on it > New > layout resource file and give the file name as user_rv_item and add below code to it. 

 

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:elevation="8dp"
    app:cardCornerRadius="8dp">
 
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="2dp">
 
        <!--image view for displaying user image-->
        <ImageView
            android:id="@+id/idIVUser"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_margin="10dp" />
 
        <!--text view for displaying first name-->
        <TextView
            android:id="@+id/idTVFirstName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:layout_toEndOf="@id/idIVUser"
            android:layout_toRightOf="@id/idIVUser"
            android:text="First Name"
            android:textColor="@color/black"
            android:textSize="15sp" />
 
        <!--text view for displaying last name-->
        <TextView
            android:id="@+id/idTVLastName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/idTVFirstName"
            android:layout_marginTop="10dp"
            android:layout_toEndOf="@id/idIVUser"
            android:layout_toRightOf="@id/idIVUser"
            android:text="Last Name"
            android:textColor="@color/black"
            android:textSize="15sp" />
 
        <!--text view for displaying user email-->
        <TextView
            android:id="@+id/idTVEmail"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/idTVLastName"
            android:layout_marginTop="10dp"
            android:layout_toEndOf="@id/idIVUser"
            android:layout_toRightOf="@id/idIVUser"
            android:text="Email"
            android:textColor="@color/black"
            android:textSize="15sp" />
 
    </RelativeLayout>
   
</androidx.cardview.widget.CardView>


 
 

Step 8: Creating an Adapter class for setting data to our RecyclerView item  

 

For creating a new Adapter class. Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as UserRVAdapter and add the below code to it. 

 

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.squareup.picasso.Picasso;
 
import java.util.ArrayList;
 
public class UserRVAdapter extends RecyclerView.Adapter<UserRVAdapter.ViewHolder> {
   
    // variable for our array list and context.
    private ArrayList<UserModal> userModalArrayList;
    private Context context;
 
    // creating a constructor.
    public UserRVAdapter(ArrayList<UserModal> userModalArrayList, Context context) {
        this.userModalArrayList = userModalArrayList;
        this.context = context;
    }
 
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // inflating our layout file on below line.
        View view = LayoutInflater.from(context).inflate(R.layout.user_rv_item, parent, false);
        return new ViewHolder(view);
    }
 
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
       
        // getting data from our array list in our modal class.
        UserModal userModal = userModalArrayList.get(position);
         
          // on the below line we are setting data to our text view.
        holder.firstNameTV.setText(userModal.getFirst_name());
        holder.lastNameTV.setText(userModal.getLast_name());
        holder.emailTV.setText(userModal.getEmail());
       
        // on below line we are loading our image from the URL
        // in our image view using Picasso.
        Picasso.get().load(userModal.getAvatar()).into(holder.userIV);
    }
 
    @Override
    public int getItemCount() {
        // returning the size of array list.
        return userModalArrayList.size();
    }
 
    public class ViewHolder extends RecyclerView.ViewHolder {
       
        // creating a variable for our text view and image view.
        private TextView firstNameTV, lastNameTV, emailTV;
        private ImageView userIV;
 
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
           
            // initializing our variables.
            firstNameTV = itemView.findViewById(R.id.idTVFirstName);
            lastNameTV = itemView.findViewById(R.id.idTVLastName);
            emailTV = itemView.findViewById(R.id.idTVEmail);
            userIV = itemView.findViewById(R.id.idIVUser);
        }
    }
}


 
 

Step 9: 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.ProgressBar;
import android.widget.Toast;
 
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.NestedScrollView;
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;
 
public class MainActivity extends AppCompatActivity {
 
    // creating a variable for our array list, adapter class,
    // recycler view, progressbar, nested scroll view
    private ArrayList<UserModal> userModalArrayList;
    private UserRVAdapter userRVAdapter;
    private RecyclerView userRV;
    private ProgressBar loadingPB;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        // creating a new array list.
        userModalArrayList = new ArrayList<>();
       
        // initializing our views.
        userRV = findViewById(R.id.idRVUsers);
        loadingPB = findViewById(R.id.idPBLoading);
       
        // calling a method to load our API.
        getDataFromAPI();
    }
 
    private void getDataFromAPI() {
       
        // creating a string variable for URL.
       
          // creating a new variable for our request queue
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
       
        // creating a variable for our JSON object request and passing our URL to it.
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                loadingPB.setVisibility(View.GONE);
                try {
                    JSONObject feedObj = response.getJSONObject("feed");
                    JSONArray entryArray = feedObj.getJSONArray("entry");
                    for(int i=0; i<entryArray.length(); i++){
                        JSONObject entryObj = entryArray.getJSONObject(i);
                        String firstName = entryObj.getJSONObject("gsx$firstname").getString("$t");
                        String lastName = entryObj.getJSONObject("gsx$lastname").getString("$t");
                        String email = entryObj.getJSONObject("gsx$email").getString("$t");
                        String avatar = entryObj.getJSONObject("gsx$avatar").getString("$t");
                        userModalArrayList.add(new UserModal(firstName, lastName, email, avatar));
                         
                        // passing array list to our adapter class.
                        userRVAdapter = new UserRVAdapter(userModalArrayList, MainActivity.this);
                         
                        // setting layout manager to our recycler view.
                        userRV.setLayoutManager(new LinearLayoutManager(MainActivity.this));
                       
                        // setting adapter to our recycler view.
                        userRV.setAdapter(userRVAdapter);
                    }
 
                } catch (JSONException e) {
                    e.printStackTrace();
                }
 
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // handling on error listener method.
                Toast.makeText(MainActivity.this, "Fail to get data..", Toast.LENGTH_SHORT).show();
            }
        });
        // calling a request queue method
        // and passing our json object
        queue.add(jsonObjectRequest);
    }
}


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

Output:

 

 

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments