Skip to main content

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.

Comments

Popular posts from this blog

web2apk

http://web2apk.com/create.aspx Create App   Intro   About   Changes   MalWare ?   Contact   Privacy Useful Links Bluetooth Mini Keyboards Android Mini PC Reset Android URL App Title Icon or

how to retrieve image from sqlite database in android and display in listview

 Android platform provides several ways to store data in our application. 1. SQLite database 2. SharedPreferences etc For our post, we will only work with SQLite database. First and foremost, we need to understand what an SQLite database is? SQLite database  is an open source SQL database that stores data to a text file on a device. It executes SQL Commands to perform a set of functions, that is, create, read, update and delete operations. On my previous post, I showed how to  store data in SQLite database from edit text, retrieve and populate it in a listview . For this post, I will show the SQLite CRUD operations with images from gallery and text from EditText. We need to understand this; images are stored in SQLite database as BLOB data type. A BLOB is a large binary object that can hold a variable amount of data.  Note, we can only store images in the database as BLOB data type. We need to convert our image path to a bitmap then to bytes. Also

Android Bar Chart Using MpAndroidChart Library Tutorial

https://www.numetriclabz.com/android-bar-chart-using-mpandroidchart-library-tutorial/ Android Bar Chart Using MpAndroidChart Library Tutorial Objective In this tutorial we learn how to implement Bar Chart using MpAndroidChart Library in your Android App. Download Source Code       Step 1 Contents ·        1  Introduction ·        2  Creating Bar chart o    2.1  Create a new Project o    2.2  Adding library in Project o    2.3  Create Layout o    2.4  To Plot Bar Chart §   2.4.1  Initialize the graph id §   2.4.2  Creating a Dataset §   2.4.3  Defining X-axis labels §   2.4.4  Set the data §   2.4.5  Add the description to the chart §   2.4.6  Run your App §   2.4.7  Set the color §   2.4.8  Adding Animations o    2.5  To plot grouped bar chart §   2.5.1  Creating Dataset o    2.6  Get the best of Android plus exclusive deals and freebies in your inbox!