Retrofit is the library which converts your JSON data into Java object. In this tutorial, we will learn about how to implement the Retrofit to create a WordPress Mobile App. As we all know, WordPress is the one of the biggest CMS (Content Management System) of the world. Wordpress full fill the requirements for all most every type of the website. So, in this tutorial, I am going to learn how to create an Android App using the WordPress REST API and Retrofit.
If you want to know about Retrofit, I would like to give you just a simple one-line explanation of the Retrofit. It is a library which converts your REST HTTP request to Java interface. We will learn how we can do all these stuff using some very simple steps.
Further, you can check the Retrofit Library here.
So, In this tutorial, we will use the Retrofit to retrieve all post and there except ( A short Description of Post) form a WordPress website.
There is some prerequisite for creating the WordPress, which is given below.
Check if your WordPress site has the REST API by putting the below URL into your favorite browser.
http://www.yoursite.com/wp-json/
If REST API is working on your site it displays the all available route on your website for REST API.
Next, we have to add the Retrofit Library to our Project level build.gradle file as given below.
We required two layout files for this sample Demo App to use the WordPress REST API by using the Retrofit library. Below is the layout files for our demo app.
postitem.xml
activity_main.xml
We need to create the POJO for our WordPress Website, but we all know there is the huge number of field and creating the exact POJO for all the field are very difficult. So for creating the POJO, we have a very simple way. You can go to jsonschema2pojo Website, it is a simple tool which will create the POJO from your JSON data.
To get the JSON data of your website you can use the Postman for Chrome and you can get the desktop version from here.
So getting the JSON data of your website you can put the "http://www.pgtfb.com/wp-json/wp/v2/posts"
Copy the extract JSON data and post on the website on JSON input field and then click on Preview button. You can see the output given below.
Even if you want you can download the all generated Java file into the zipped format and extract at your Java source code directory.
Next, We have to create a service to get all posts from WordPress Website. So now create or modify the WordPress Service class as given below.
The above class will fetch the all the post from given website.
In the above example we are using @GET("wp/v2/posts") this is the route after the base URL. This will give as 10 recent posts because WordPress by default gives 10 posts.
If you want to play with the other option of the WordPress REST API you can refer the WordPress official tutorial about RESET API.
This Call<List<Post>> getAllPost(); the method will get automatically mapped with our response from the Retrofit Library and return the List of Post.
A sample Post class will look like as given below. However, exact Post class depends on your website, that you gave as input on the jsonschema2pojo like given below.
This is the simple RecyclerView Adapter which we will use to show the post details on RecyclerView.
PostAdapter.java
First of all, we need to do the initialization of our basic UI component inside the onCreate method of our Main Activity.
Next, We have to create the instance of Retrofit like given below.
Create the service by mapping the request with our WordPress Service Interface.
Call the getAllPost method of WordPress Service to retrieve all post and store the output into call list variable.
Using below method we need to enqueue the request to get the all the post.
That's all we required to create the WordPress Android App using Retrofit. Below is the full source code of the main activity.
Now, we are ready to test our WordPress Android App using the Retrofit Library. If you run you will see the output as given below.
If you want to learn how to create the WordPress app using the Volley. Then check the other article on WordPress Android App as given below.
What is Retrofit?
If you want to know about Retrofit, I would like to give you just a simple one-line explanation of the Retrofit. It is a library which converts your REST HTTP request to Java interface. We will learn how we can do all these stuff using some very simple steps.
Further, you can check the Retrofit Library here.
So, In this tutorial, we will use the Retrofit to retrieve all post and there except ( A short Description of Post) form a WordPress website.
Prerequisite for using the Retrofit for WordPress Android App
There is some prerequisite for creating the WordPress, which is given below.
- There must be REST API is active on your WordPress Website or blog
- Retrofit should be added to your project as dependency
Check if your WordPress site has the REST API by putting the below URL into your favorite browser.
http://www.yoursite.com/wp-json/
If REST API is working on your site it displays the all available route on your website for REST API.
Next, we have to add the Retrofit Library to our Project level build.gradle file as given below.
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
implementation 'com.android.support:cardview-v7:26.1.0'
implementation 'com.android.support:recyclerview-v7:26.1.0'
compile 'com.google.code.gson:gson:2.8.1'
Create Layout file for WordPress Android App
We required two layout files for this sample Demo App to use the WordPress REST API by using the Retrofit library. Below is the layout files for our demo app.
postitem.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:orientation="vertical"
android:layout_marginStart="5dp"
android:layout_marginEnd="5dp">
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="@style/TextAppearance.AppCompat.Caption"
android:textIsSelectable="true"
android:textSize="20sp"
android:textStyle="bold"
android:visibility="visible" />
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/blog_image"
android:fitsSystemWindows="true"/>
<TextView
android:id="@+id/excerpt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="@style/TextAppearance.AppCompat.Display1"
android:textIsSelectable="true"
android:textSize="16sp"
android:visibility="visible" />
</LinearLayout>
</android.support.v7.widget.CardView>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context="com.nplix.retrofitdemo.MainActivity">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/recyclerHome">
</android.support.v7.widget.RecyclerView>
</android.support.constraint.ConstraintLayout>
Create POJO of WordPress Website REST API
We need to create the POJO for our WordPress Website, but we all know there is the huge number of field and creating the exact POJO for all the field are very difficult. So for creating the POJO, we have a very simple way. You can go to jsonschema2pojo Website, it is a simple tool which will create the POJO from your JSON data.
To get the JSON data of your website you can use the Postman for Chrome and you can get the desktop version from here.
So getting the JSON data of your website you can put the "http://www.pgtfb.com/wp-json/wp/v2/posts"
Copy the extract JSON data and post on the website on JSON input field and then click on Preview button. You can see the output given below.
Even if you want you can download the all generated Java file into the zipped format and extract at your Java source code directory.
Create the Service for WordPress Using Retrofit
Next, We have to create a service to get all posts from WordPress Website. So now create or modify the WordPress Service class as given below.
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
/**
* Created by PK on 2/4/2018.
*/
public interface WordPressService {
@GET("wp/v2/posts")
Call<List<Post>> getAllPost();
}
The above class will fetch the all the post from given website.
In the above example we are using @GET("wp/v2/posts") this is the route after the base URL. This will give as 10 recent posts because WordPress by default gives 10 posts.
If you want to play with the other option of the WordPress REST API you can refer the WordPress official tutorial about RESET API.
This Call<List<Post>> getAllPost(); the method will get automatically mapped with our response from the Retrofit Library and return the List of Post.
A sample Post class will look like as given below. However, exact Post class depends on your website, that you gave as input on the jsonschema2pojo like given below.
package com.nplix.retrofitdemo;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Post {
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("title")
@Expose
private Title title;
@SerializedName("content")
@Expose
private Content content;
@SerializedName("excerpt")
@Expose
private Excerpt excerpt;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Title getTitle() {
return title;
}
public void setTitle(Title title) {
this.title = title;
}
public Content getContent() {
return content;
}
public void setContent(Content content) {
this.content = content;
}
public Excerpt getExcerpt() {
return excerpt;
}
public void setExcerpt(Excerpt excerpt) {
this.excerpt = excerpt;
}
}
Create Adapter for WordPress Android App
This is the simple RecyclerView Adapter which we will use to show the post details on RecyclerView.
PostAdapter.java
package com.nplix.retrofitdemo;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
/**
* Created by Pawan on 2/20/2016.
*/
public class PostAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final static int FADE_DURATION = 1000;
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
private static final int TYPE_FOOTER = 2;
private String TAG="LoadImage";
private Context context;
Bundle bundle=new Bundle();
private List<Post> questionList;
private boolean mWithHeader;
private boolean mWithFooter;
private View.OnClickListener mOnClickListener;
public PostAdapter(List<Post> posts, Context context, boolean withHeader, boolean withFooter) {
this.questionList = posts;
this.context=context;
this.mWithHeader=withHeader;
this.mWithFooter=withFooter;
}
@Override
public int getItemViewType(int position) {
if (mWithHeader && isPositionHeader(position))
return TYPE_HEADER;
if (mWithFooter && isPositionFooter(position))
return TYPE_FOOTER;
return TYPE_ITEM;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.postitem, viewGroup, false);
VideoViewHolder holder = new VideoViewHolder(itemView);
itemView.setTag(holder);
itemView.setOnClickListener(mOnClickListener);
return holder;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if(holder instanceof header){
}
else if(holder instanceof footer){
((footer) holder).context = context;
}
else {
Post post=getItem(position);
((VideoViewHolder)holder).vTitle.setText(Html.fromHtml(post.getTitle().getRendered()));
Excerpt excerpt=post.getExcerpt();
if(excerpt!=null){
if(excerpt.getRendered().length()>=254){
((VideoViewHolder)holder).vExcerpt.setText(Html.fromHtml(excerpt.getRendered().substring(0,254)+" .."));
}
else {
((VideoViewHolder)holder).vExcerpt.setText(Html.fromHtml(post.getExcerpt()+" .."));
}
}
((VideoViewHolder) holder).context = context;
((VideoViewHolder) holder).content=post.getContent().getRendered();
}
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
@Override
public int getItemCount() {
int itemCount=0;
if(questionList!=null) {
itemCount = questionList.size();
if (mWithHeader)
itemCount = itemCount + 1;
if (mWithFooter)
itemCount = itemCount + 1;
// return itemCount;
}
return itemCount;
}
private boolean isPositionHeader(int position) {
return position == 0;
}
private boolean isPositionFooter(int position) {
return position == getItemCount() - 1;
}
public void setOnClickListener(View.OnClickListener lis) {
mOnClickListener = lis;
}
protected Post getItem(int position) {
return mWithHeader ? questionList.get(position - 1) : questionList.get(position);
}
private int getItemPosition(int position){
return mWithHeader ? position - 1 : position;
}
public void setData(List<Post> questionList) {
this.questionList=questionList;
}
public class VideoViewHolder extends RecyclerView.ViewHolder {
ImageView vImage;
protected TextView vName;
TextView vDetails,vTitle,vExcerpt;
String content;
Context context;
VideoViewHolder(View v) {
super(v);
vImage = (ImageView) v.findViewById(R.id.blog_image);
vTitle = (TextView) v.findViewById(R.id.title);
vExcerpt=(TextView) v.findViewById(R.id.excerpt);
v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
public void clearAnimation() {
this.clearAnimation();
}
}
public class header extends RecyclerView.ViewHolder {
protected Context context;
protected int position;
public header(View v) {
super(v);
}
}
public class footer extends RecyclerView.ViewHolder {
protected Context context;
protected int position;
public footer(View v) {
super(v);
}
}
}
Create instance of Retrofit Library to get all Post of WordPress
First of all, we need to do the initialization of our basic UI component inside the onCreate method of our Main Activity.
RecyclerView recyclerView=findViewById(R.id.recyclerHome);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
final PostAdapter postAdapter=new PostAdapter(postList,this,false,false);
recyclerView.setAdapter(postAdapter);
Next, We have to create the instance of Retrofit like given below.
Retrofit retrofit=new Retrofit.Builder()
.baseUrl(Config.base_url)
.addConverterFactory(GsonConverterFactory.create())
.build();
Create the service by mapping the request with our WordPress Service Interface.
WordPressService wordPressService=retrofit.create(WordPressService.class);
Call the getAllPost method of WordPress Service to retrieve all post and store the output into call list variable.
Call<List<Post>> call=wordPressService.getAllPost();
Using below method we need to enqueue the request to get the all the post.
call.enqueue(new Callback<List<Post>>() {
@Override
public void onResponse(Call<List<Post>> call, Response<List<Post>> response) {
Log.d("myResponse:", "Total Post:"+response.body().size());
//Set the data into adapter
postAdapter.setData(response.body());
// Update the Layout with latest data
postAdapter.notifyDataSetChanged();
}
@Override
public void onFailure(Call<List<Post>> call, Throwable t) {
Log.d("myResponse:", "MSG"+t.toString());
}
});
That's all we required to create the WordPress Android App using Retrofit. Below is the full source code of the main activity.
package com.nplix.retrofitdemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
List<Post> postList=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView=findViewById(R.id.recyclerHome);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
final PostAdapter postAdapter=new PostAdapter(postList,this,false,false);
recyclerView.setAdapter(postAdapter);
Retrofit retrofit=new Retrofit.Builder()
.baseUrl(Config.base_url)
.addConverterFactory(GsonConverterFactory.create())
.build();
WordPressService wordPressService=retrofit.create(WordPressService.class);
Call<List<Post>> call=wordPressService.getAllPost();
call.enqueue(new Callback<List<Post>>() {
@Override
public void onResponse(Call<List<Post>> call, Response<List<Post>> response) {
Log.d("myResponse:", "Total Post:"+response.body().size());
postAdapter.setData(response.body());
postAdapter.notifyDataSetChanged();
}
@Override
public void onFailure(Call<List<Post>> call, Throwable t) {
Log.d("myResponse:", "MSG"+t.toString());
}
});
}
}
Now, we are ready to test our WordPress Android App using the Retrofit Library. If you run you will see the output as given below.
If you want to learn how to create the WordPress app using the Volley. Then check the other article on WordPress Android App as given below.
Thank you for tutorial! Very helpful
ReplyDeleteYou're Most Welcome!
ReplyDeleteBit of a novice in studio I think I have plugins / kotlin up to date should be I just installed studio on a new machine... Error:Could not find method implementation() for arguments [com.squareup.retrofit2:retrofit:2.3.0] on root project 'WPRetrofit' of type org.gradle.api.Project.
ReplyDeleteIt asked me to restart studio when fetching plugin update that's when I got the new error.
Got it open again, now Gradle sync failed: Declaring custom 'clean' task when using the standard Gradle lifecycle plugins is not allowed. Over my pay grade here.
ReplyDeleteHi,
ReplyDeleteIt looks like you are using the older version of android studio. In older version compile is used instead of implementation. You can modify the build.gradle file from implementation to compile if you want to use the same version.
Example:
In Older version but still supported
compile 'com.google.code.gson:gson:2.8.1'
Android studio 3.0 and higher
implementation 'com.google.code.gson:gson:2.8.1'
Try to update to android studio 3.0 or higher version. If still not work try to clean the project from build menu and then retry.
Thanks,
Pawan Kumar
Fixed: You cannot use "compile" in 3.1 built on March 21 should be "implementation com.google.code.gson:gson:2.8.1". At least I couldn't. Once the maven and repos were identified correctly no errors were thrown.
ReplyDeleteThat's Great.
ReplyDeleteThanks for sharing your experience. Let me try Android Studio 3.1.
Happy Coding!
1 question at a time... so in your great tut I have everything running and gradle build throws no errors but I'm stuck at this point: Create or modify the WordPress Service class as given below.
ReplyDeleteI've looked in documentation but don't understand where this code gets inserted. I thought it was in the manifest from reading other sites but I'm wrong, Can you tell me exactly how to "create" this service class?
Thanks always!
Stu
Hi,
ReplyDeleteThis service needs to create inside java code folder of your project like any other class.
Thanks,
This service needs to create inside java code folder of your project like any other class....
ReplyDeleteI am missing something. I create class "WordPressService" but don't understand how to insert your code... https://imgur.com/a/Wx9bs
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
/**
* Created by PK on 2/4/2018.
*/
public interface WordPressService {
@GET("wp/v2/posts")
Call<List> getAllPost();
}
Hi,
ReplyDeleteJust paste the code into that file and press control insert key wherever you are getting the red line into the code.
The complete code of this interface will look like as given below, including dependency import into that interface.
package com.nplix.retrofitdemo;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
/**
* Created by PK on 2/4/2018.
*/
public interface WordPressService {
@GET("wp/v2/posts")
Call> getAllPost();
}
These are basic I suggest start with some basic app then move to develop the complicated app development.
Please let me know if I can help you into this.
Thanks
hi thanks for the tutorial. but whe i try to open the post nothing happens why is that?
ReplyDeleteHi
ReplyDeleteClick event are only work when you tab on the title.
Thanks
keep getting this when i click on title
ReplyDeleteD/ViewRootImpl@3d823b7[MainActivity]: ViewPostImeInputStage processPointer 0
/ViewRootImpl@3d823b7[MainActivity]: ViewPostImeInputStage processPointer 1
when i click on title i get this on log. am i suppoed to put somthing inside onClick(View v) { }.
ReplyDeleteViewPostImeInputStage processPointer 0
ViewPostImeInputStage processPointer 1
Hi ,
ReplyDeleteYes, You have to put something inside the onclick event and simplest way put a webview inside an activity or fragment and load the full content into the webView on activity/fragment start.
Thanks,
Hi I want to know that in wordpress we create api key. so can i use this api in Android App. if i can use it so that's is the faster then putting damoain name etc ?
ReplyDeleteYes, you can.
ReplyDeleteHow to Fetch wp featured image using retrofit?
ReplyDeleteRefer the below tutorial:-
ReplyDeletehttps://www.nplix.com/wp-android-app-using-rest-volley-livedata-part3/
// getting URL of the Post fetured Image
JSONObject featureImage=obj.getJSONObject("_links");
JSONArray featureImageUrl=featureImage.getJSONArray("wp:featuredmedia");
JSONObject featureImageObj=featureImageUrl.getJSONObject(0);
String fiurl=featureImageObj.getString("href");
There is a website similar to pojo json because my input was larger than 51200 characters
ReplyDeletehy bro can you help me pleaseeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee. i want all post from my wordpress website
ReplyDeletehttps://domainname.com/wp-json/wp/v2/posts
but when i click this link it will display only 10 items... how to get all items... i have 400 post on my website.. help me?
Hi Arslan,
ReplyDeleteYou can use the pagination function of the rest api.
For example: use below syntax to fetch first 50 post and for next 50 change the page=2 and so on.
https://domainnamecom/wp-json/wp/v2/posts/?per_page=50&page=1
You can use the per_page from 1 to 100, So if you have 400 page then you can retrieve it in four iteration by setting the pagesize 100 and change the page 1,2,3 and 4.
Thanks,
Pawan Kumar
I am thankful to you for this article because you are providing such good information as I see, thanks for this. keep sharing this.Home Deep Retrofit Scheme Ireland
ReplyDeleteYou are sharing a piece of nice information here. The information you have provided is genuinely instructive and significant for us. Thanks for sharing an article like this.Mobile Application Development Company in Noida UP
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteSuch quality content! I find this article very informative. I am waiting for your next post. Keep it up.
ReplyDeleteios development company