Welcome folks today in this blog post we will be building an android app
where we will be making a http call
to the jsonplaceholder
api and displaying the data inside the recyclerview
using the volley
and gson
libraries in java. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new android
project inside the android studio and then you will see the below directory
structure as shown below at the end
of the project.
Now we need to edit the AndroidManifest.xml
file you need to include the internet
permission so that we can fetch external
data from the jsonplaceholder api.
AndroidManifest.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:dataExtractionRules="@xml/data_extraction_rules" android:fullBackupContent="@xml/backup_rules" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/Theme.ImageCropper" tools:targetApi="31"> <activity android:name=".MainActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |
Adding External Dependencies
Now guys we need to add the below lines inside the dependencies
block of the build.gradle
file as shown below
1 2 3 |
implementation 'com.android.volley:volley:1.2.1' implementation 'com.google.code.gson:gson:2.8.9' implementation 'androidx.recyclerview:recyclerview:1.2.1' |
Now after adding the above
lines you need to press the sync
button and after that android studio will install these dependencies
automatically in the background.
Now we need to edit the activity_main.xml
layout file where we need to embed the recyclerView
widget inside the constraintLayout
section as shown below.
activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/postRecyclerView" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" tools:listitem="@layout/item_post" /> </androidx.constraintlayout.widget.ConstraintLayout> |
And now we need to edit the MainActivity.java
file and copy paste the following code
MainActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
package com.example.imagecropper; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; 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 { private RecyclerView recyclerView; private PostAdapter adapter; private LinearLayoutManager layoutManager; private ArrayList<Post> postList; private int page = 1; private boolean isLoading = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); postList = new ArrayList<>(); recyclerView = findViewById(R.id.postRecyclerView); adapter = new PostAdapter(postList); layoutManager = new LinearLayoutManager(this); recyclerView.setAdapter(adapter); recyclerView.setLayoutManager(layoutManager); recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); int visibleItemCount = layoutManager.getChildCount(); int totalItemCount = layoutManager.getItemCount(); int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition(); if (!isLoading) { if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount && firstVisibleItemPosition >= 0) { loadPosts(); } } } }); loadPosts(); } private void loadPosts() { isLoading = true; String url = "https://jsonplaceholder.typicode.com/posts?_page=" + page; JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { if (response.length() > 0) { for (int i = 0; i < response.length(); i++) { try { JSONObject jsonObject = response.getJSONObject(i); int id = jsonObject.getInt("id"); String title = jsonObject.getString("title"); String body = jsonObject.getString("body"); Post post = new Post(id, title, body); postList.add(post); } catch (JSONException e) { e.printStackTrace(); } } adapter.notifyDataSetChanged(); page++; } isLoading = false; } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { isLoading = false; error.printStackTrace(); } }); Volley.newRequestQueue(this).add(request); } } |
As you can see in the above java
code we are making the http
call to the jsonplaceholder
api using the volley library and then we are parsing the json
response which is coming using the gson
library and then we are displaying the results inside the recyclerView
widget. As you can see we are importing the Post
class and then PostAdapter
classes required for the application
Now we need to create the Post
java class where we will be declaring the information
that we will be extracting from the jsonplaceholder
api as shown below
Post.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
package com.example.imagecropper; public class Post { private int id; private String title; private String body; public Post(int id, String title, String body) { this.id = id; this.title = title; this.body = body; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } } |
As you can see inside this Post
class where we are declaring the constructor for receiving the id title
and body
of the post. And then we have the getters
and the setters
for this data.
Now we need to create the PostAdapter
java class and paste the below code
PostAdapter.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
package com.example.imagecropper; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder> { private ArrayList<Post> postList; public PostAdapter(ArrayList<Post> postList) { this.postList = postList; } @NonNull @Override public PostViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_post, parent, false); return new PostViewHolder(view); } @Override public void onBindViewHolder(@NonNull PostViewHolder holder, int position) { Post post = postList.get(position); holder.postId.setText(String.valueOf(post.getId())); holder.postTitle.setText(post.getTitle()); holder.postBody.setText(post.getBody()); } @Override public int getItemCount() { return postList.size(); } public class PostViewHolder extends RecyclerView.ViewHolder { TextView postId, postTitle, postBody; public PostViewHolder(@NonNull View itemView) { super(itemView); postId = itemView.findViewById(R.id.postId); postTitle = itemView.findViewById(R.id.postTitle); postBody = itemView.findViewById(R.id.postBody); } } } |
Now we need to create the view
for the different items which will be inflated
inside the recyclerView for that we need to create the xml
layout file called item_post.xml
file as shown below
item_post.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="16dp"> <TextView android:id="@+id/postId" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@android:color/holo_green_dark" android:textSize="18sp" android:textStyle="bold"/> <TextView android:id="@+id/postTitle" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="@android:color/holo_blue_dark" android:textSize="16sp" android:textStyle="bold"/> <TextView android:id="@+id/postBody" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="14sp"/> </LinearLayout> |
As you can see we have three textView
widgets required for holding the id title
and the body
of the post.
And now if you run the android
app you will see the below result as shown below