WordPress Android App with REST API And Retrofit

WordPress Android App with REST API And Retrofit

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.

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”

Retrofit Example

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.

JSON to Java Object Generator

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;
    }
}

JSON to Java Object convtor

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.

WordPress Android App and Retrofit

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.

Get Email Updates!

Signup now receive an email once I publish new content. I will never give away, trade or sell your email address. You can unsubscribe at any time.

Join 911 other subscribers

This Post Has 20 Comments

  1. when i click on title i get this on log. am i suppoed to put somthing inside onClick(View v) { }.

    ViewPostImeInputStage processPointer 0
    ViewPostImeInputStage processPointer 1

    1. Hi ,

      Yes, 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,

  2. keep getting this when i click on title

    D/ViewRootImpl@3d823b7[MainActivity]: ViewPostImeInputStage processPointer 0
    /ViewRootImpl@3d823b7[MainActivity]: ViewPostImeInputStage processPointer 1

  3. Bit 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.

    It asked me to restart studio when fetching plugin update that’s when I got the new error.

    1. 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.

      1. 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.

        1. That’s Great.
          Thanks for sharing your experience. Let me try Android Studio 3.1.

          Happy Coding!

          1. 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.

            I’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

          2. Hi,

            This service needs to create inside java code folder of your project like any other class.

            Thanks,

    2. Hi,

      It 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

      1. This service needs to create inside java code folder of your project like any other class….

        I 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();
        }

        1. Hi,

          Just 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

  4. Thank you for tutorial! Very helpful

    1. You’re Most Welcome!

      1. hi thanks for the tutorial. but whe i try to open the post nothing happens why is that?

        1. Hi

          Click event are only work when you tab on the title.
          Thanks

Leave a Reply

Close Menu
%d bloggers like this: