How to retrieve Pins from Pinterest in Android Tutorial

Udemy Generic 728x90

Objective

In this tutorial, we will learn how to get Pins from Pinterest to Android application through a simple example.

 



 

Pinterest is a platform where we can share photos of favorite event, hobbies and interest. Pinterest is a social bookmarking tool for saving and discovering creative ideas. User can save, sort and manage images known as Pin and a collection of media (videos, images) known as Pinboard.

We already explained Pinterest Integration and Login process in Android Pinterest Integration and Login Tutorial.  Now, we are going to explain how to retrieve Pin from Pinterest to Android application.

 

Step 2

Create a MyPinsActivity Activity

Create a new Activity called MyPinsActivity. In this Activity, we will retrieve a list of pins from Pinterest to Android application.

 

Step 3

Create a MyPinsActivity Layout

We will display a list of Pins as a grid. So, we need to use GridView to display Pins as a grid.


 <GridView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/grid_view"
        android:numColumns="2"
        android:horizontalSpacing="10dip"
        android:verticalSpacing="10dip"
        android:padding="10dip"
        android:cacheColorHint="@android:color/transparent"
        android:layout_below="@id/create_pin" />

 

Step 4

Creating Layout to display list of items

We will display Image and Note of Pin. So, we need to create a layout named as list_item_pin and use ImageView and TextView in this layout. We will use this layout to inflate in GridView Adapter class.

<?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">

    <ImageView
        android:layout_width="200dip"
        android:layout_height="200dip"
        android:scaleType="centerCrop"
        android:id="@+id/image_view" />

    <TextView
        android:layout_width="200dip"
        android:layout_height="60dip"
        android:maxLines="2"
        android:id="@+id/title_view"
        android:layout_below="@+id/image_view" />

</RelativeLayout>

 

Step 5

Initialize GridView

To use GridView feature, we need to initialize GridView in onCreate() method.

GridView gridView = (GridView) findViewById(R.id.grid_view);
Step 6

Create GridView Adapter

To display a list of Pin, we need to create PinsAdapter class that extends BaseAdapter. To implement BaseAdapter class, it requires some methods:

  • getCount(): Returns the size of array list.
  • getItem(int): Returns the actual object at the specified position in the adapter.
  • getItemId(int): Returns the row id of the item.
  • getView(): This method creates new view for each pin added to PinsAdapter.
/**
 * GridView Adapter class
 */
private class PinsAdapter extends BaseAdapter {

    private List<PDKPin> _pinList;
    private Context _context;

    public PinsAdapter(Context context) {
            _context = context;
    }

    /**
     *  Add list of item to List<PDKPin> array
     * @param list
     */
    public void setPinList(List<PDKPin> list) {

        if (_pinList == null)
              _pinList = new ArrayList<PDKPin>();

        if (list == null)
             _pinList.clear();

        else
           _pinList.addAll(list);

        notifyDataSetChanged();
    }

    /**
     * @return array list
     */
    public List<PDKPin> getPinList() {
            return _pinList;
    }

    /**
     * @return size of array
     */
    @Override
    public int getCount() {
        return _pinList == null ? 0 : _pinList.size();
    }

    /**
     * Get the data item associated with the specified position in the data set.
     * @param position
     * @return position of item
     */
     @Override
     public Object getItem(int position) {
         return position;
     }

     /**
      * Get the row id associated with the specified position in the list.
      * @param position
      * @return
      */
      @Override
      public long getItemId(int position) {
          return position;
      }

      /**
       * Get a View that displays the data at the specified position in the data set.
       * @param position
       * @param convertView
       * @param parent
       * @return
       */
      @Override
      public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolderItem viewHolder;

            //load more pins if about to reach end of list
            if (_pinList.size() - position < 5) {
                loadNext();
            }

            if (convertView == null) {

                LayoutInflater inflater = ((Activity) _context).getLayoutInflater();

                // inflate list_item_pin xml file
                convertView = inflater.inflate(R.layout.list_item_pin, parent, false);

                viewHolder = new ViewHolderItem();
                viewHolder.textViewItem = (TextView) convertView.findViewById(R.id.title_view);
                viewHolder.imageView = (ImageView) convertView.findViewById(R.id.image_view);

                convertView.setTag(viewHolder);

            } else {

                viewHolder = (ViewHolderItem) convertView.getTag();
            }

            PDKPin pinItem = _pinList.get(position);

            if (pinItem != null) {

                // set note of pin to textview
                viewHolder.textViewItem.setText(pinItem.getNote());

                // load pin image
                Picasso.with(_context.getApplicationContext())
                       .load(pinItem.getImageUrl())
                       .into(viewHolder.imageView);
            }

            return convertView;
        }

        private class ViewHolderItem {

            TextView textViewItem;
            ImageView imageView;
        }
   }

 

Step 7

Initialize PinsAdapter class

We will set list of data to Adapter class. So, we need to initialize PinsAdapter in onCreate() method.

pinAdapter = new PinsAdapter(this);

 

Step 8

Add PDKCallback object

We will use PDKCallback object to get a response, when we send request to get Pins. For that, we will create PDKCallback object and add onSuccess and onFailure method within this object. The onSuccess method is used to get user pin. We will retrieve user pin list by calling getPinList() method. The onFailure method is to get failure response.

/**
 * Created PDKCallback method and get user pin list by calling getPinList() method.
 * Set the pin list to Adapter by calling  setPinList() method of PinAdapter class.
 */
public void getResponse(){

   myPinsCallback = new PDKCallback() {
        @Override
        public void onSuccess(PDKResponse response) {
            loading = false;
            myPinsResponse = response;
            pinAdapter.setPinList(response.getPinList());
        }

        @Override
        public void onFailure(PDKException exception) {
            loading = false;
            Log.e(getClass().getName(), exception.getDetailMessage());
        }
    };
}

 

Step 9

Get User Pins

We need to define Pin field. Pin Field is details about user Pin. Now, we need to make requests to get pin by calling getMyPins() method of PDKClient class. Pass the pin field and PDKCallback object in getMyPins() method.

private static final String PIN_FIELDS = "id,link,creator,image,counts,note,created_at,board,metadata";

/**
 * Make a request to get Pins by calling getMyPins() method and
 * pass the pin field and PDKCallback object
 */
    private void fetchPins() {

        pinAdapter.setPinList(null);
        PDKClient.getInstance().getMyPins(PIN_FIELDS, myPinsCallback);
    }

 

myPins

Step 10

Final code of MyPinsActivity class

Here is the final code of MyPinsActivity class:

public class MyPinsActivity extends AppCompatActivity {

    private PDKCallback myPinsCallback;
    private PDKResponse myPinsResponse;
    private GridView gridView;
    private PinsAdapter pinAdapter;
    private boolean loading = false;
    private static final String PIN_FIELDS = "id,link,creator,image,counts,note,created_at,board,metadata";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_pins);
        setTitle("My Pins");

        // Initialize PinAdapter class
        pinAdapter = new PinsAdapter(this);

        // Calling init() method
        init();

        // Calling getResponse() method
        getResponse();

        // Set Adapter class
        gridView.setAdapter(pinAdapter);

        loading = true;

        // Calling fetchPins() method
        fetchPins();
    }

    public void init(){

        gridView = (GridView) findViewById(R.id.grid_view);

    }

    /**
     * Created PDKCallback method and get user pin list by calling getPinList() method.
     * Set the pin list to Adapter by calling  setPinList() method of PinAdapter class.
     */
    public void getResponse(){

        myPinsCallback = new PDKCallback() {
            @Override
            public void onSuccess(PDKResponse response) {
                loading = false;
                myPinsResponse = response;
                pinAdapter.setPinList(response.getPinList());
            }

            @Override
            public void onFailure(PDKException exception) {
                loading = false;
                Log.e(getClass().getName(), exception.getDetailMessage());
            }
        };
    }

    /**
     * Make a request to get Pins by calling getMyPins() method and pass the pin field and PDKCallback object
     */
    private void fetchPins() {

        pinAdapter.setPinList(null);
        PDKClient.getInstance().getMyPins(PIN_FIELDS, myPinsCallback);
    }

    /**
     * Load pins
     */
    private void loadNext() {

        if (!loading && myPinsResponse.hasNext()) {

            loading = true;
            myPinsResponse.loadNext(myPinsCallback);
        }
    }

    /**
     * GridView Adapter class
     */
    private class PinsAdapter extends BaseAdapter {

        private List<PDKPin> _pinList;
        private Context _context;
        public PinsAdapter(Context context) {
            _context = context;
        }

        /**
         *  Add list of item to List<PDKPin> array
         * @param list
         */
        public void setPinList(List<PDKPin> list) {

            if (_pinList == null)
                _pinList = new ArrayList<PDKPin>();

            if (list == null)
                _pinList.clear();

            else
                _pinList.addAll(list);

            notifyDataSetChanged();
        }

        /**
         * @return array list
         */
        public List<PDKPin> getPinList() {
            return _pinList;
        }

        /**
         * @return size of array
         */
        @Override
        public int getCount() {
            return _pinList == null ? 0 : _pinList.size();
        }

        /**
         * Get the data item associated with the specified position in the data set.
         * @param position
         * @return position of item
         */
        @Override
        public Object getItem(int position) {
            return position;
        }

        /**
         * Get the row id associated with the specified position in the list.
         * @param position
         * @return
         */
        @Override
        public long getItemId(int position) {
            return position;
        }

        /**
         * Get a View that displays the data at the specified position in the data set.
         * @param position
         * @param convertView
         * @param parent
         * @return
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolderItem viewHolder;

            //load more pins if about to reach end of list
            if (_pinList.size() - position < 5) {
                loadNext();
            }

            if (convertView == null) {

                LayoutInflater inflater = ((Activity) _context).getLayoutInflater();

                // inflate list_item_pin xml file
                convertView = inflater.inflate(R.layout.list_item_pin, parent, false);

                viewHolder = new ViewHolderItem();
                viewHolder.textViewItem = (TextView) convertView.findViewById(R.id.title_view);
                viewHolder.imageView = (ImageView) convertView.findViewById(R.id.image_view);

                convertView.setTag(viewHolder);

            } else {

                viewHolder = (ViewHolderItem) convertView.getTag();
            }

            PDKPin pinItem = _pinList.get(position);

            if (pinItem != null) {

                // set note of pin to textview
                viewHolder.textViewItem.setText(pinItem.getNote());

                // load pin image
                Picasso.with(_context.getApplicationContext())
                       .load(pinItem.getImageUrl())
                       .into(viewHolder.imageView);
            }

            return convertView;
        }

        private class ViewHolderItem {

            TextView textViewItem;
            ImageView imageView;
        }
    }
}




 

Udemy Generic 728x90

Spread the word. Share this post!