Search code examples
javaandroidandroid-layoutwordpress-rest-api

How to get and display Wordpress featured media and author image?


I am creating an android app that displays WordPress posts. At the moment, the app is displaying the title and subtitle (3 lines of text) but, it doesn't show the featured image. I also would love to get the author image, too (if possible) but I am more worry about the featured image. I tried to google it but I might be asking the wrong question. I also tried to get the image path but it didn't work at all. According to JSON the featured image contains an id, and this id can be used to get the path. But, no luck.

RecycleViewAdapter.java

package com.myfitbytes;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;



 public class RecyclerViewAdapter extends RecyclerView.Adapter {

private ArrayList<Model> dataset;
private Context mContext;

public RecyclerViewAdapter(ArrayList<Model> mlist, Context context) {
    this.dataset = mlist;
    this.mContext = context;
}

public static class ImageTypeViewHolder extends RecyclerView.ViewHolder{


    TextView title, subtitle;
    ImageView imageView;

    public ImageTypeViewHolder(View itemView) {
        super(itemView);

        this.title = (TextView)  itemView.findViewById(R.id.title);
        this.subtitle = (TextView) itemView.findViewById(R.id.subtitle);
        //at the moment, it is displaying an icon for all posts
        this.imageView = (ImageView) itemView.findViewById(R.id.Icon);
    }
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from( parent.getContext()).inflate(R.layout.postdetails, parent, false);
    return new ImageTypeViewHolder(view) ;
}

@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
    final Model object = dataset.get(position);

    ( (ImageTypeViewHolder) holder).title.setText( object.title );
    ( (ImageTypeViewHolder) holder).subtitle.setText( object.subtitle );

    ( (ImageTypeViewHolder) holder).title.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(mContext, WPPostDetails.class);
            intent.putExtra("itemPosition", position);
            mContext.startActivity(intent);
        }
    });
    ( (ImageTypeViewHolder) holder).subtitle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(mContext, WPPostDetails.class);
            intent.putExtra("itemPosition", position);
            mContext.startActivity(intent);
        }
    });
    ( (ImageTypeViewHolder) holder).imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(mContext, WPPostDetails.class);
            intent.putExtra("itemPosition", position);
            mContext.startActivity(intent);
        }
    });

    /// dataset.get(position)
}

  @Override
  public int getItemCount() {
    return dataset.size() ;
   }
}

postdetail.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
app:cardElevation="5dp">




    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:gravity="center_vertical"
        android:paddingTop="5dp"

        android:layout_weight="4">

        <ImageView
            android:id="@+id/Icon"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_margin="5dp"
            android:layout_weight="9"
            android:src="@mipmap/ic_launcher" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textStyle="bold"
            android:gravity="left"
            android:id="@+id/title"
            android:textColor="@color/colorBlack"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginBottom="5dp"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="left"
            android:id="@+id/subtitle"
            android:padding="5dp"
            android:layout_marginBottom="5dp"
            android:maxLines="3"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:lineSpacingExtra="2dp"/>



</LinearLayout>

And this is the fragment that displays the posts: Blog.java

    package com.myfitbytes;

   import android.os.Bundle;
   import android.support.annotation.Nullable;
   import android.support.v4.app.Fragment;
   import android.support.v7.widget.LinearLayoutManager;
   import android.support.v7.widget.RecyclerView;
   import android.util.Log;
   import android.view.LayoutInflater;
   import android.view.View;
   import android.view.ViewGroup;
   import android.widget.ProgressBar;

   import java.util.ArrayList;
   import java.util.List;

   import retrofit2.Call;
   import retrofit2.Callback;
   import retrofit2.Response;
   import retrofit2.Retrofit;
   import retrofit2.converter.gson.GsonConverterFactory;

   public class Blog extends Fragment {



private RecyclerView recyclerView;
private ProgressBar progressBar;
private LinearLayoutManager mLayoutManager;
private ArrayList<Model> list;
private RecyclerViewAdapter adapter;

private String baseURL = "https://www.myfitbytes.com/";

public static List<WPPost> mListPost;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup 
container, @Nullable Bundle savedInstanceState) {
    //
    LayoutInflater lf = getActivity().getLayoutInflater();
    View view = lf.inflate(R.layout.fragment_blog, container, false);


    //wordpress blog posts

    recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
    progressBar = (ProgressBar) view.findViewById(R.id.progressBarPosts);

    mLayoutManager = new LinearLayoutManager(getActivity(), 
    LinearLayoutManager.VERTICAL, false);
    recyclerView.setLayoutManager(mLayoutManager);

    list = new ArrayList<Model>();
    /// call retrofill
    getRetrofit();

    adapter = new RecyclerViewAdapter( list, getActivity());

    recyclerView.setAdapter(adapter);



    return view;



}



public void getRetrofit(){

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseURL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    RetrofitArrayApi service = retrofit.create(RetrofitArrayApi.class);
    Call<List<WPPost>>  call = service.getPostInfo();

    // to make call to dynamic URL

    // String yourURL = yourURL.replace(BaseURL,"");
    // Call<List<WPPost>>  call = service.getPostInfo( yourURL);

    /// to get only 6 post from your blog
    // http://your-blog-url/wp-json/wp/v2/posts?per_page=2

    // to get any specific blog post, use id of post
    //  http://www.blueappsoftware.in/wp-json/wp/v2/posts/1179

    // to get only title and id of specific
    // http://www.blueappsoftware.in/android/wp-json/wp/v2/posts/1179? 
     fields=id,title



    call.enqueue(new Callback<List<WPPost>>() {
        @Override
        public void onResponse(Call<List<WPPost>> call, Response<List<WPPost>> 
        response) {
            Log.e("blog", " response "+ response.body());
            mListPost = response.body();
            progressBar.setVisibility(View.GONE);
            for (int i=0; i<response.body().size();i++){
                Log.e("main ", " title "+ 
            response.body().get(i).getTitle().getRendered() + " "+
                        response.body().get(i).getId());

                String tempdetails =  
                response.body().get(i).getExcerpt().getRendered().toString();
                tempdetails = tempdetails.replace("<p>","");
                tempdetails = tempdetails.replace("</p>","");
                tempdetails = tempdetails.replace("[&hellip;]","");

                list.add( new Model( Model.IMAGE_TYPE,  
    response.body().get(i).getTitle().getRendered(),
                        tempdetails,

   response.body().get(i).getLinks().getWpFeaturedmedia().get(0).getHref())  );

            }
            adapter.notifyDataSetChanged();

        }

        @Override
        public void onFailure(Call<List<WPPost>> call, Throwable t) {

        }
    });

   }

   public static List<WPPost> getList(){
       return  mListPost;
   }


}

EDIT: I tried to add this code inside the RecycleViewAdapter.class but still no luck

Glide.with(mContext).load(response.body().getMediaDetails().getSizes().getThumbnail().getSourceUrl())
                    .into(imageView);

Edit - So, someone sent me a few details. But I still don't get it. The last time that I tried to create an android app was in 2014-2015. Here are the details:

Yes, you can fetch everything from your WordPress website. WordPress store blog post image on another table. so follow this step

1) get blog post using REST APi..it will be a JSON array.

2) check each json object, each have this JSON object- Links --> WpFeaturedmedia--->object(0)-->Href

3) this Href is index of image for the blog post.

4) pass this href to adapter..

5) inside adapter class again use another retrofit call for this href url

6) the response of this retrofit will have all images(multiple sizes) of blog post. response.body().getMediaDetails().getSizes().getThumbnail().getSourceUrl()

7) pass it to glide method (inside adpater class only) Glide.with(mContext) .load( response.body().getMediaDetails().getSizes().getThumbnail().getSourceUrl()) .into(imageView);

Finally, response POJO in adapter is not the response POJO that you use on activity. Create another POJO for image url.


Solution

  • Ok so after doing some research, i have found that you just have to concate _embed at the end of your url and you will be able to get featured image as well as author bio with image.

    Here is the demo url

    https://www.myfitbytes.com/wp-json/wp/v2/posts?_embed 
    

    And from there you can get author data inside _embed object

    enter image description here

    And for featured image it will look like

    enter image description here

    enter image description here