Skip to main content

WP Android App using REST and volley

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.



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"]WP android app sample 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

Comments

  1. […] 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
  2. Can I have the Source code as android studio project ?

    ReplyDelete
  3. You can get the source code from below link on Github on https://github.com/debugandroid/WPApp .

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

    ReplyDelete
  4. Thank you for the tutorial. Subscribed.

    ReplyDelete
  5. I see that your PostAdapter.java mentions R.layout.header and R.layout.footer. However, there is no such elements in our layout file.

    ReplyDelete
  6. Hi Daniel,

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

    ReplyDelete
  7. Thank you Pawan. But now I have error message here:
    " " + mediaType.getString("file"));

    the IDE said that mediaType is not defined.

    ReplyDelete
  8. Hi Daniel,
    Its 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!

    ReplyDelete
  9. i have 1 doubt i have to show the wordpress "content": {
    "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

    ReplyDelete
  10. Yes, it can be just to some google you will find the solution.

    ReplyDelete

Post a Comment

Popular posts from this blog

Flutter Theme Creation, Programmatic Way

Flutter and Dart is an excellent combination for creating the mobile app with material design with nice GUI. Its lots of widget which help the developer for creating the app UI very fast with respect to the other language. You may face some problem in starting due to comm, curly brace and semicolon but after some time you will find the way how to work with these all stuff and it becomes very easy for you. But in this article, we are not going to discuss all these. In this article, we will handle a very interesting topic on how to create a custom theme or multiple themes and let's user decide which theme to use.



Create a flutter project



So let's create a flutter project by selecting the appropriate option from the File menu in android studio or Visual Code. If you are new to Flutter and Dart you can check out our recent post to get started Creating Cross-platform app using flutter.



Once your project is created you will get the default counter app and you try running the app in the…

Flutter How to Start Android Activity from Flutter View

Flutter and Dart is an excellent combination for creating the UI, but for accessing the platform-specific service we need to open platform-specific activity. So lets in this article we will explore how to start an android activity and access the service from Flutter View.

Create a Project for this Android Activity Flutter View Demo Create a Project From File menu select the New Flutter Project Enter the project name Select the AndroidX support and click on next After the above, we step click on Finish We will have the following project structure created. Create the Second Activity in Android
Just go to the android folder and open it in separate windows. We will have the following project structure.









Create the Activity Just right click on the Kotlin folder and create a blank activity from the menu. If you create the activity then you may be required to upgrade the Gradle and do some import. So Just click on update and wait for the project sync completed.
Update the project build config …

Flutter State Management With Provider and ChangeNotifier

Flutter state management with provider library and why it's so important? There are lots of topics in flutter which are very important but out of those state management of your flutter application is the most important and little bit complicated as well. So in this article, I will try to explain how to use the provider package for managing the state of flutter and dart application and how to access the data down the hierarchy of the widget tree without recreating the whole UI.



Basic knowledge of the state management and data flow in the Flutter



Before starting the coding I would like to explain some basics about the Flutter application so that you can understand, why it's important to manage the state of your application in the correct way.



In Flutter, everything is a widget and whenever the state of your application changes the UI is recreated the UI with the new data. Let's list out the topic or problem that we are going to explore about state management.



Challenge of St…