Xamarin.Android: Building WordPress Blog Reader App

xamarinfinal
Want create site? Find Free WordPress Themes and plugins.

WordPress is powering millions of websites, a powerful and an easy to content management system. To the other side, Xamarin is a powerful cross-platform mobile application development platform. In this blog-post, I will walk you through the process of developing a Xamarin.Android app, which would be consuming WordPress blogs through REST API.

Requirements

For this walkthrough, you need:

  1. Microsoft Visual Studio
  2. Xamarin.Android installed
    1. If you don’t have Xamarin.Android installed, click here to install
  3. A WordPress deployment
  4. Internet connection (which I am sure you have right now 🙂 )

You can also use a local WordPress, on your development machine

Before continuing, install WP-REST API v2 plugin on your WordPress

Step 1: Create the Xamarin.Android Project

  1. Start Microsoft Visual Studio
  2. Click File > New > Project
  3. Choose Android from the Templates pane on the left
  4. Choose Blank App (Android) from the middle pane
  5. Enter a project name
  6. Click OK

xamarin-1

Step 2: Configure the Project

When you have successfully created the project, you should see “Get started with Xamarin” page. Before continuing to code, we have to install and configure the project.

Install WordPressDotNet NuGet Package

For installing the package,

  1. Right click on your current project in Solution Explorer
  2. Click Manage NuGet Packagesxamarin-4
  3. In NuGet Package Manager, click on Browse
  4. Search for wordpressdotnet package
  5. Install its latest version
  6. Click OK on Review Changes Windowxamarin-5

After successful package installation, the package should be marked with a green icon with a white mark.

xamarin-6

Allow Internet Access (Manifest)

For accessing WordPress blog posts with REST API, your application requires internet access permission. To allow internet access, do the following changes.

  1. In Solution Explorer, Double Click on Properties (found inside Project)
  2. In Properties pane, go to Android Manifest
  3. Scroll down for required permissions
  4. Check the INTERNET permissionxamarin-7

 

Now you are done with project configuration, we can continue to code.

Step 3: Create Activity for Listing Blog Posts

Modify MainActivity

With default template, you get an Activity named MainActivity. We will modify the activity layout to show a list of blog posts in a ListView. And we will create another ActivityPostActivity, which will show the post content.

So to do as mentioned above, open Main.axml (layout XML) file. The file is located in Resources\Layout. Put a ListView inside a ScrollView. Your layout XML should be looking like:


Add PostItem Template Layout

Right click on Layout folder inside Resources. Add new Android Layout item. Name it PostItem.axml and put the following code in the layout.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="match_parent"
 android:layout_height="match_parent">
 <TextView
 android:id="@+id/PostsItemTitleTextView"
 android:layout_marginTop="12dp"
 android:text=""  />
 <TextView
 android:id="@+id/PostsItemTitleTextView"
 android:layout_marginTop="8dp"
 android:text=""/>
</LinearLayout>
Creating a Custom Adapter for ListView

Before creating the Adapter, create two folders in your project. Models and Adapters, for keeping your view-model classes and custom adapter implementations, respectively. In models, add a view-model class and name it Post. Structure the class with the following properties.

 public int Id { get; set; }
 public string Title { get; set; }
 public System.DateTime PostDate { get; set; }
 public string Content { get; internal set; }

Now create a new class, inherited from BaseAdapter<Post>. Name it PostsAdapter. The class definition should be like

public class PostsAdapter: BaseAdapter & lt;
Post & gt; {
    Activity context;
    List & lt;
    Post & gt;
    list;

    public PostsAdapter(Activity activity, List & lt; Post & gt; listOfPosts) {
        list = listOfPosts;
        context = activity;
    }
    public override Post this[int position] {
        get {
            return list[position];
        }
    }

    public override int Count {
        get {
            return list.Count;
        }
    }

    public override long GetItemId(int position) {
        return list[position].Id;
    }

    public override View GetView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (view == null)
            view = context.LayoutInflater.Inflate(Resource.Layout.PostItem, parent, false);

        var TitleTextView = view.FindViewById & lt;
        TextView & gt;
        (Resource.Id.PostsItemTitleTextView);
        var DateTextView = view.FindViewById & lt;
        TextView & gt;
        (Resource.Id.PostsItemDateTextView);

        var post = this[position];

        TitleTextView.Text = post.Title;
        DateTextView.Text = post.PostDate.ToLongDateString();

        return view;

    }
}

 

Now open MainActivity.cs file, and mark the OnCreate method async.

Add the following code to the OnCreate method.

  • Give the activity a good looking title
    • Title = "WordPress in Xamarin!";
  • Make a global instance of List<Post> in MainActivity
    • private List<Post> listOfPosts;
  • For setting layout for the activity
    • SetContentView(Resource.Layout.Main);
  • Get access to controls, i.e. the main ListView and a ProgressBar
    • var postsListView = FindViewById<ListView>(Resource.Id.PostsListView);
      var progressBar = FindViewById<ProgressBar>(Resource.Id.ProgressBar);
  • Set the progressBar visible and download posts from WordPress site
    • progressBar.Visibility = Android.Views.ViewStates.Visible;
      var downloadedPosts = await new WordPressDotNet.WordPressConnector("http://zianasir.com/").Posts.GetPostsAsync();
  • We made a view-model, Post. Make a List<Post>, and put all returned downloadedPosts the new List<Post>
    • listOfPosts = new List<Post>();
      foreach (var post in downloadedPosts)
      {
      listOfPosts.Add(new Post() {
      Id = post.id,
      Title = post.title.rendered,
      Content = post.content.rendered,
      PostDate = System.Convert.ToDateTime(post.date)
      });
      }
  • Make the progressBar invisible, attach new Adapter to thepostsListView and attach ItemClick event listener
    • progressBar.Visibility = Android.Views.ViewStates.Gone;
      postsListView.Adapter = new PostsAdapter(this, listOfPosts);
      postsListView.ItemClick += PostsListView_ItemClick;
  • Definition for PostsListView_ItemClick method
    • private void PostsListView_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
      {
      var htmlContent = listOfPosts[e.Position].Content;
      var title = listOfPosts[e.Position].Title;var intent = new Intent(this, typeof(PostActivity));
      intent.PutExtra("HTMLContent", htmlContent);
      intent.PutExtra("Title", title);StartActivity(intent);
      }

So far, we have implemented the MainActivity, but we have to create one last Activity. That is the PostActivity. In the PostsListView_ItemClick method, PostActivity is referenced. So if you compile the app, it should build with errors.

Step 4: Create Activity for Viewing Blog Post Content

Now create a new Activity and name it PostActivity. To do so, right click on your project. Click Add > New Item. Choose Activity from the list.

It should create a Class for you, PostActivity, but the layout is not created automatically. Now add a new layout. To do so, expand Resources folder, and right click on layouts folder. Click Add > New Item. Choose Android Layout as template, and name it Post.axml. Open Post.axml and put the following layout code in it

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent" >
 <android.webkit.WebView
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:id="@+id/contentWebView" />
</RelativeLayout>

We have added a layout with a WebView. WebView helps you show HTML content and websites inside your application. What we want to do with WebView is to show the blog post content in the WebView by using its LoadData() method. To do so, follow the following steps.

  • Open PostActivity class. In OnCreate method, add the following line
    • SetContentView(Resource.Layout.Post);
  • Get data from the Intent.
    • var htmlContent = Intent.GetStringExtra("HTMLContent");
      var title = Intent.GetStringExtra("Title");
  • Set the Title of the Activity to the blog post title
    • Title = title;
  • Find the WebView
    • var contentWebView = FindViewById<WebView>(Resource.Id.contentWebView);
  • Load the HTML into the contentWebView
    • contentWebView.LoadData(htmlContent, "text/HTML", null);

 

Now you are done with coding the basic application. Run the application. You should have one thing, not looking to be working good. The ListView in the MainActivity does not size itself with the number of items in it. For solving the size issue, I am giving you a solution. Do the following changes in your MainActivity.

Add this method to the MainActivity

 public static bool SetListViewHeightBasedOnItems(ListView listView)
 {

 var listAdapter = listView.Adapter;
 if (listAdapter != null)
 {

 int numberOfItems = listAdapter.Count;

 int totalItemsHeight = 0;
 for (int itemPos = 0; itemPos < numberOfItems; itemPos++)
 {
 View item = listAdapter.GetView(itemPos, null, listView);
 item.Measure(0, 0);
 totalItemsHeight += item.MeasuredHeight;
 }


 int totalDividersHeight = listView.DividerHeight *
 (numberOfItems - 1);


 var param = listView.LayoutParameters;
 param.Height = totalItemsHeight + totalDividersHeight;
 listView.LayoutParameters = (param);
 listView.RequestLayout();

 return true;

 }
 else
 {
 return false;
 }

 }

Add this line in the end of OnCreate method
SetListViewHeightBasedOnItems(postsListView);

Conclusion

In this blog post, we created an Android application with Xamarin, to get the WordPress blog content. And view the blog posts in the application. We covered aspects of creating a basic application, and connecting it to the WordPress with WordPressDotNet library, which handles all the HTTP requests for us. We did not have to write extra HTTP request code. I know the application is basic, and worse looking. In next blog post, I will write about customizing the application and putting Lazy Loading in the application, as this application is only designed for loading the first 10 posts from the WordPress deployment.

Did you find apk for android? You can find new Free Android Games and apps.
Malak Zia Nasir

Author Malak Zia Nasir

Software Engineer, a Microsoft guy. Working on multiple platforms. A lover, a miskeen :P

More posts by Malak Zia Nasir

Leave a Reply