In this tutorial, we are going to create a sample app for WordPress using the rest API for Android. For successful implementation of the rest API for WordPress we need to it in two parts. In the first part, we will learn some basic configuration on the server side and configure the Android project in android using the Android Studio.
If you are using the WordPress version 4.7 and above you do not require any special configuration for this, you can just test your configuration by sending the sample request to the http://yoursite/wp-json/ . You will get the output into the JSON format.
Now, If you are using the older version of the WordPress then you need to install the WordPress REST API Plugin using the below-mentioned steps.
After installing the WP REST API you can check the REST API working status for your website by sending the sample request to http://yoursite/wp-json/.
If you are looking for Self hosting solution on regainable price, even you can start totally free if you SignUp by clicking on the link from this website on DigitalOcean.
Create the Project by just clicking on File->New->New Project and select the default activity and you are ready to write the code in Android for developing the Android App using the Rest API for WordPress.
First of all, we need to add one recyclerView to our main layout files to list the post.
Now create an ItemView for individual post, we have given it name as postitem.xml
We need to write four class in this segment of the tutorial as given below.
Post.java
First of all, we will create the Post.java class which is the POJO for our post item. To create and modify the Post.java file as given below.
Config.java
We will now create the Config.java class to store the static config value for our project.
MainActivity.java
Now, it is time to create and modify our MainActivity.java file. So now modify the MainActivity.java file as given below.
PostAdapter.java
Finally, we are now at last stage of our tutorial where we will create the PostAdapter.java class. This class we will use to show the post item into the Recyclerview. So now create and modify the PostAdapter.java class as given below and let us know in case of any challenge.
Now, we can run and test our application and it will just show the list recent 10 posts from your blog, as given below. In next part of this tutorial, we will show the individual post on click event on below list of post and some more stuff.
[caption id="attachment_447" align="aligncenter" width="576"]
WP Android App with REST API[/caption]
Read the second part of this tutorial from below link.
WP Android App using REST and volley part2
LiveData and ViewModel for WP Android App using REST and volley part3
Requirement to create the Android App for WordPress
- WordPress API is included in core release of the WordPress version 4.7 and above.
- For older version, you need to install the WordPress plugin API
- Android Studio 2.X.X or 3.X.X
If you are using the WordPress version 4.7 and above you do not require any special configuration for this, you can just test your configuration by sending the sample request to the http://yoursite/wp-json/ . You will get the output into the JSON format.
Now, If you are using the older version of the WordPress then you need to install the WordPress REST API Plugin using the below-mentioned steps.
Installing plugin to create the WP Android App using REST
- Download the WP REST API Plugin from WordPress.
- Install the WordPress Plugin by WordPress plugin management window as a normal plugin or alternatively you search and install online as well from plugin management page from admin portal.
- Activate the plugin from word press plugin management page.
After installing the WP REST API you can check the REST API working status for your website by sending the sample request to http://yoursite/wp-json/.
If you are looking for Self hosting solution on regainable price, even you can start totally free if you SignUp by clicking on the link from this website on DigitalOcean.
Create Project for WP Android App using the REST in Android Studio
Create the Project by just clicking on File->New->New Project and select the default activity and you are ready to write the code in Android for developing the Android App using the Rest API for WordPress.
Permission needs to be added to the AndroidManifest.xml files.
<uses-permission android:name="android.permission.INTERNET" />
Dependency needs to be added in build.gradle file to create the project
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.android.support:design:25.3.1'
compile 'com.google.code.gson:gson:2.7'
compile 'com.android.volley:volley:1.0.0'
compile 'com.android.support:cardview-v7:25.3.1'
compile 'com.android.support:recyclerview-v7:25.3.1'
Let's creating the layout for Item of the post
First of all, we need to add one recyclerView to our main layout files to list the post.
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/recyclerHome">
</android.support.v7.widget.RecyclerView>
Now create an ItemView for individual post, we have given it name as 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">
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
android:textAppearance="@style/TextAppearance.AppCompat.Body1"
android:textIsSelectable="true"
android:textSize="20sp"
android:visibility="visible" />
</android.support.v7.widget.CardView>
Android Code to retrieve the post and show into the RecyclerView
We need to write four class in this segment of the tutorial as given below.
- Posts.java -- Post.java class is a POJO call to define the datatype of the post which is used to define the Item inside our main and adapter class
- Config.java -- Config.java class are used to define some constant value like base URL of your WordPress websites
- MainActivity.java -- It is the main call of our application and most of the activity will be done inside this method, rest other class are just to support this class.
- PostAdapter -- It is the adapter for our RecyclerView to show the post item into the RecylerView
Post.java
First of all, we will create the Post.java class which is the POJO for our post item. To create and modify the Post.java file as given below.
package com.nplix.wpapp;
/**
* Created by PK on 7/22/2017.
*/
import com.google.gson.annotations.SerializedName;
public class Posts {
@SerializedName("id")
long id;
String post;
int status;
String createdAt;
String Title;
String Description;
String postURL;
String postImg;
public String getPostURL() {
return postURL;
}
public void setPostURL(String postURL) {
this.postURL = postURL;
}
public String getPostImg() {
return postImg;
}
public void setPostImg(String postImg) {
this.postImg = postImg;
}
public String getPost() {
return post;
}
public void setPost(String post) {
this.post = post;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
}
Config.java
We will now create the Config.java class to store the static config value for our project.
public class Config {
public static String base_url="https://www.nplix.com/wp-json/";
}
MainActivity.java
Now, it is time to create and modify our MainActivity.java file. So now modify the MainActivity.java file as given below.
package com.nplix.wpapp;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
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.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
public static String TAG="WPAPP";
public List<Posts> mPosts;
public Button btnGetPost;
public RecyclerView recyclerView;
public PostAdapter postAdapter;
public int page=1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
recyclerView= (RecyclerView) findViewById(R.id.recyclerHome);
postAdapter=new PostAdapter(mPosts,this,false,false);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
getPost();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void getPost() {
mPosts = new ArrayList<Posts>();
JsonArrayRequest getRequest = new JsonArrayRequest(Request.Method.GET, Config.base_url+"wp/v2/posts/?page="+page, null,
new Response.Listener<JSONArray>()
{
@Override
public void onResponse(JSONArray response) {
// display response
Log.d(TAG, response.toString() + "Size: "+response.length());
for(int i=0;i<response.length();i++){
Posts post=new Posts();
try {
Log.d(TAG,"Object at " + i+ response.get(i));
JSONObject obj=response.getJSONObject(i);
post.setId(obj.getInt("id"));
post.setCreatedAt(obj.getString("date"));
post.setPostURL(obj.getString("link"));
JSONObject titleObj=obj.getJSONObject("title");
post.setTitle(titleObj.getString("rendered"));
mPosts.add(post);
} catch (JSONException e) {
e.printStackTrace();
}
}
setData(mPosts);
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.toString());
}
}
) ;
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(getRequest);
}
public void setData(List<Posts> posts){
recyclerView.setAdapter(postAdapter);
postAdapter.setData(mPosts);
postAdapter.notifyDataSetChanged();
}
}
PostAdapter.java
Finally, we are now at last stage of our tutorial where we will create the PostAdapter.java class. This class we will use to show the post item into the Recyclerview. So now create and modify the PostAdapter.java class as given below and let us know in case of any challenge.
package com.nplix.wpapp;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.RecyclerView;
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.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;
Context context;
Bundle bundle=new Bundle();
private List<Posts> questionList;
private boolean mWithHeader;
private boolean mWithFooter;
private View.OnClickListener mOnClickListener;
public PostAdapter(List<Posts> 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) {
if(viewType==TYPE_HEADER) {
return new header(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.header, viewGroup, false));
}
else if(viewType==TYPE_FOOTER){
return new footer(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.footer, viewGroup, false));
}
else {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.postitem, viewGroup, false);
RecyclerView.LayoutParams.WRAP_CONTENT));
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){
//((header) holder).vName.setText(album_name);
}
else if(holder instanceof footer){
((footer) holder).context = context;
}
else {
Posts post=getItem(position);
((VideoViewHolder)holder).vTitle.setText(post.getTitle());
((VideoViewHolder) holder).context = context;
}
}
@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;
}
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 Posts 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<Posts> questionList) {
this.questionList=questionList;
}
public class VideoViewHolder extends RecyclerView.ViewHolder {
protected ImageView vImage;
protected TextView vName;
protected TextView vDetails,vTitle;
protected String vFilePath;
protected Context context;
protected Bundle b;
protected int position;
private String album;
public VideoViewHolder(View v) {
super(v);
vTitle = (TextView) v.findViewById(R.id.title);
}
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);
}
}
}
Now, we can run and test our application and it will just show the list recent 10 posts from your blog, as given below. In next part of this tutorial, we will show the individual post on click event on below list of post and some more stuff.
[caption id="attachment_447" align="aligncenter" width="576"]

Read the second part of this tutorial from below link.
WP Android App using REST and volley part2
LiveData and ViewModel for WP Android App using REST and volley part3
[…] last part of WP Android App using REST and volley tutorial we have learned to set up the basic UI for our WP app. In this part we will learn the […]
ReplyDelete[…] Create wordpress app using Json part1 […]
ReplyDelete[…] WP Android App using REST and volley […]
ReplyDelete[…] WP Android App using REST and Vollery Part1 […]
ReplyDeleteCan I have the Source code as android studio project ?
ReplyDeleteYou can get the source code from below link on Github on https://github.com/debugandroid/WPApp .
ReplyDeleteBut you have to go through the second and third part of the tutorial as it is based on that.
WordPress Tutorial part 2 https://www.nplix.com/wp-android-app-using-rest2/
WordPress Tutorial part 3 https://www.nplix.com/wp-android-app-using-rest-volley-livedata-part3/
Thank You.
Thank you for the tutorial. Subscribed.
ReplyDeleteYou are most Welcome!
ReplyDeleteI see that your PostAdapter.java mentions R.layout.header and R.layout.footer. However, there is no such elements in our layout file.
ReplyDeleteHi Daniel,
ReplyDeleteBoth layout file is sample model to put the header and footer in the RecyclerView. You can create the both layout file as per your requirement of the project inside the layout directory.
You can get the sample layout files here in the below link of the source code from GitHub.
https://github.com/debugandroid/WPApp/tree/master/app/src/main/res/layout
Thanks,
Thank you Pawan. But now I have error message here:
ReplyDelete" " + mediaType.getString("file"));
the IDE said that mediaType is not defined.
Hi Daniel,
ReplyDeleteIts looks like it is an typo error and this line is extra.
Just remove this line of code " ” ” + mediaType.getString(“file”));" updated this article as well.
Thank you!
i have 1 doubt i have to show the wordpress "content": {
ReplyDelete"rendered": values show in dynamic because inside that rendered value put so many weblink ,pictures it is possible show in dynamic when click that weblink to passing data in webview
Yes, it can be just to some google you will find the solution.
ReplyDeleteThis comment has been removed by the author.
ReplyDelete