Android Pinterest Integration and Login Tutorial

Udemy Generic 728x90

Udemy Generic 728x90

Objective

In this tutorial, we will learn how to integrate Pinterest with 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.

This tutorial explains, how to integrate Pinterest with an Android Application using Pinterest SDK and also explains how to create and get pin of authenticated user. To integrate Pinterest, we need to create an account on Pinterest. We will display user name and image and also display saved pin.

 

Step 2

Create a New Project

Create a new Project in Android Studio, goto File ⇒ New ⇒ New Projects.

 

Step 3

Download Pinterest SDK

We will integrate Android application with Pinterest using Pinterest SDK. Hence, we need to download Pinterest SDK.

 

Step 4

Include Pinterest SDK

Unzip downloaded file into the project directory. We need to include Pinterest SDK in project. So, open setting.gradle file and include Pinterest SDK directory name. Pinterest SDK directory name is pdk. Use the following code:

include ':app',':pdk'

 

Step 5

Add Pinterest SDK As Dependency

To compile Pinterest SDK, we need to add Pinterest SDK as dependency and also need to add picasso library. Picasso library will use to display images in the project. So, open your build.gradle file and add SDK and Picasso library as dependencies.

compile project(':pdk')
compile 'com.squareup.picasso:picasso:2.5.2'

 

Step 6

Create App to Pinterest

To integrate Pinterest, we need to create an App on Pinterest to get App Id. We will use this App Id to integrate Pinterest with Android App. Follow these steps to create an App:

  • Login to Pinterest.
  • Go to Pinterest Developer
  • Select checkbox of Pinterest Developer Terms and API policy and click on the Create app button.
    create app
  • We have to fill App name and description about our App in the form. Click on the Create button. It creates a new App.
    form
  • We will be add App Id in the MainActivity.java file to configure this app with Android App. So, copy App Id.
    pinterest app

 

Step 7

Add Internet Permission

To authenticate Android application with Pinterest account, So, we need to request Internet Permission. Hence, we will add Internet permission in Android Application.

<uses-permission android:name="android.permission.INTERNET" />

 

Step 8

Add Intent Filter

We will add intent filter inside our login activity in AndroidMenifest.xml file. In this example, MainActivity.java file is login activity. So, we are going to add intent filter inside <application> tag of MainActivity class. Replace {app-id} with your App id.

&lt;intent-filter&gt;
   &lt;action android:name=&quot;android.intent.action.VIEW&quot; /&gt;
   &lt;category android:name=&quot;android.intent.category.DEFAULT&quot; /&gt;
   &lt;category android:name=&quot;android.intent.category.BROWSABLE&quot; /&gt;

   &lt;data android:scheme=&quot;pdk{app-id}&quot; /&gt;
&lt;/intent-filter&gt;

 

Step 9

Create Layout

We will implement authentication process on click button. So, we need to add Button widget in activity_main.xml file.

&lt;Button
    android:id=&quot;@+id/login&quot;
    android:layout_width=&quot;wrap_content&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:text=&quot;Login With Pinterest&quot;
    android:onClick=&quot;onLogin&quot;/&gt;

login button

Step 10

Configure PDK Client

Now, we need to create link between App Id to Pinterest SDK client in App. To configure Pinterest SDK client, we need to call configureInstance(), onConnect(), setDebugMode() method. Pass the context and App id in the configureInstance() method. The onConnect() method makes the connection between App Id to SDK client. Use the following code in MainActivity.java file.

public class MainActivity extends AppCompatActivity {

    private PDKClient pdkClient;

    // Replace App-id with your App id
    private static final String appID = &quot;App-id&quot;;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Call configureInstance() method with context and App Id
        pdkClient = PDKClient.configureInstance(this, appID);

        // Call onConnect() method to make link between App id and Pinterest SDK
        pdkClient.onConnect(this);
        pdkClient.setDebugMode(true);
    }
}

 

Step 11

Authentication

We need to start authentication requests to authenticate user. For that, create an array list in which we add Pinterest SDK permission that will be used by the user. Call login() method of PDKClient class. Pass the context, list of scopes and PDKCallback object.

/**
 * Create an array list and add PDKClient permission that will be used by user.
 * Called login method and pass context, array list and PDKCallback object.
 * It will make authentication request to authenticate user.
 * @param view
 */
 public void onLogin(View view) {

    List scopes = new ArrayList&lt;String&gt;();
    scopes.add(PDKClient.PDKCLIENT_PERMISSION_READ_PUBLIC);
    scopes.add(PDKClient.PDKCLIENT_PERMISSION_WRITE_PUBLIC);
    scopes.add(PDKClient.PDKCLIENT_PERMISSION_READ_RELATIONSHIPS);
    scopes.add(PDKClient.PDKCLIENT_PERMISSION_WRITE_RELATIONSHIPS);
    copes.add(PDKClient.PDKCLIENT_PERMISSION_READ_PRIVATE);
    scopes.add(PDKClient.PDKCLIENT_PERMISSION_WRITE_PRIVATE);

    pdkClient.login(this, scopes, new PDKCallback() {

            /**
             * It called, when Authentication success
             * @param response
             */
            @Override
            public void onSuccess(PDKResponse response) {

                Log.e(getClass().getName(), response.getData().toString());

            }

            /**
             * It called, when Authentication failed
             * @param exception
             */
            @Override
            public void onFailure(PDKException exception) {
                Log.e(getClass().getName(), exception.getDetailMessage());
            }
        });
}

authenticate user

Step 12

Result Handler

We need to add onActivityResult() method to handle switch back to own app, when authentication process complete.

/**
 * It handle reuslt and switch back to own app when authentication process complete
 * @param requestCode
 * @param resultCode
 * @param data
 */
 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     super.onActivityResult(requestCode, resultCode, data);
     pdkClient.onOauthResponse(requestCode, resultCode,
                data);
     // call onLoginSuccess() method
     onLoginSuccess();
 }

 

Step 13

Call Home Activity

After successfully login, we will call HomeActivity in onLoginSuccess method.

/**
 * Start HomeActivity class
 */
 private void onLoginSuccess() {
    Intent i = new Intent(this, HomeActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(i);
    finish();
 }

 

Step 14

Final code of MainAcitivity class

Here is the final code of MainActivity class

public class MainActivity extends AppCompatActivity {

    private PDKClient pdkClient;

    // Replace App-id with your App id
    private static final String appID = &quot;48237318644705xxxxxxx&quot;;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Call configureInstance() method with context and App Id
        pdkClient = PDKClient.configureInstance(this, appID);

        // Call onConnect() method to make link between App id and Pinterest SDK
        pdkClient.onConnect(this);
        pdkClient.setDebugMode(true);
    }

    /**
     * It handle reuslt and switch back to own app when authentication process complete
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        pdkClient.onOauthResponse(requestCode, resultCode,
                data);

        onLoginSuccess();
    }

    /**
     * Create an array list and add PDKClient permission that will be used by user.
     * Called login method and pass context, array list and PDKCallback object.
     * It will make authentication request to authenticate user.
     * @param view
     */
    public void onLogin(View view) {
        List scopes = new ArrayList&lt;String&gt;();
        scopes.add(PDKClient.PDKCLIENT_PERMISSION_READ_PUBLIC);
        scopes.add(PDKClient.PDKCLIENT_PERMISSION_WRITE_PUBLIC);
        scopes.add(PDKClient.PDKCLIENT_PERMISSION_READ_RELATIONSHIPS);
        scopes.add(PDKClient.PDKCLIENT_PERMISSION_WRITE_RELATIONSHIPS);
        scopes.add(PDKClient.PDKCLIENT_PERMISSION_READ_PRIVATE);
        scopes.add(PDKClient.PDKCLIENT_PERMISSION_WRITE_PRIVATE);

        pdkClient.login(this, scopes, new PDKCallback() {

            /**
             * It called, when Authentication success
             * @param response
             */
            @Override
            public void onSuccess(PDKResponse response) {

                Log.e(getClass().getName(), response.getData().toString());

            }

            /**
             * It called, when Authentication failed
             * @param exception
             */
            @Override
            public void onFailure(PDKException exception) {
                Log.e(getClass().getName(), exception.getDetailMessage());
            }
        });
    }

    /**
     * Start HomeActivity class
     */
    private void onLoginSuccess() {
        Intent i = new Intent(this, HomeActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(i);
        finish();
    }
}

 

Step 15

Create a HomeActivity class

We need to create new activity class called HomeActivity. In this class, we will display user name and user picture and also will get Pins from user account and implement logout process.

 

Step 16

Create HomeActivity Layout

In the HomeActivity class, we will display user name and image. So, we need to use TextView and ImageView in activity_home.xml file. We also call another activity and implement a logout process on click button. So we need to add Button widget in activity_home.xml file.

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    android:paddingBottom=&quot;@dimen/activity_vertical_margin&quot;
    android:paddingLeft=&quot;@dimen/activity_horizontal_margin&quot;
    android:paddingRight=&quot;@dimen/activity_horizontal_margin&quot;
    android:paddingTop=&quot;@dimen/activity_vertical_margin&quot;
    tools:context=&quot;app.pinterest.HomeActivity&quot;&gt;

    &lt;ImageView
        android:layout_width=&quot;50dip&quot;
        android:layout_height=&quot;50dip&quot;
        android:paddingTop=&quot;20dip&quot;
        android:layout_centerHorizontal=&quot;true&quot;
        android:id=&quot;@+id/profile_imageview&quot;
        /&gt;

    &lt;TextView
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:id=&quot;@+id/name_textview&quot;
        android:layout_centerHorizontal=&quot;true&quot;
        android:gravity=&quot;center&quot;
        android:layout_below=&quot;@+id/profile_imageview&quot;
        /&gt;

    &lt;Button
        android:layout_width=&quot;200dip&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:text=&quot;My Pins&quot;
        android:id=&quot;@+id/pins_button&quot;
        android:layout_centerHorizontal=&quot;true&quot;
        android:layout_below=&quot;@+id/name_textview&quot;
        android:background=&quot;@null&quot;
        android:onClick=&quot;myPins&quot;/&gt;

    &lt;Button
        android:layout_width=&quot;200dip&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:id=&quot;@+id/logout_button&quot;
        android:text=&quot;Logout&quot;
        android:layout_below=&quot;@+id/pins_button&quot;
        android:layout_centerHorizontal=&quot;true&quot;
        android:background=&quot;@null&quot;
        android:onClick=&quot;logout&quot;
        /&gt;

&lt;/RelativeLayout&gt;

home layout
 

Step 17

Initialize TextView and ImageView

To use TextView and ImageView Properties, we need to initialize TextView and ImageView in onCreate() method.

public class HomeActivity extends AppCompatActivity {

    private TextView name;
    private ImageView profile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        // Initialize TextView and ImageView.
        name = (TextView) findViewById(R.id.name_textview);
        profile = (ImageView) findViewById(R.id.profile_imageview);
    }
}

 

Step 18

Get User Details

Now, we will get user details from Pinterest. First, we need to define user fields then Call getMe() method. Pass the user field and PDKCallback object in getMe() method. We will get user details by calling onSuccess() method in the PDKCallback() object. If there is something wrong or error, we will get error message by calling onFailure() method in PDKClient object.

public class HomeActivity extends AppCompatActivity {

    private final String USER_FIELDS = &quot;id,image,counts,created_at,first_name,last_name,bio&quot;;
    private static boolean DEBUG = true;
    private TextView name;
    private ImageView profile;
    PDKUser user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        // Initialize TextView and ImageView.
        name = (TextView) findViewById(R.id.name_textview);
        profile = (ImageView) findViewById(R.id.profile_imageview);

        // Calling getUserDetails() method
        getUserDetails();
    }

    /**
     * Get authenticated user details by calling getMe() method of PDKClient.
     * Pass the user field and PDKCallback object.
     */
    private void  getUserDetails() {

        PDKClient.getInstance().getMe(USER_FIELDS, new PDKCallback() {

            /**
             * It called, when successfully retrieve details of user.
             * @param response
             */
            @Override
            public void onSuccess(PDKResponse response) {

                if (DEBUG)
                    Log.e(&quot;Response&quot;, String.format(&quot;status: %d&quot;, response.getStatusCode()));

                user = response.getUser();

                // Call setUser() method
                setUser();
            }

            /**
             * It called , when request to get user details failed
             * @param exception
             */
            @Override
            public void onFailure(PDKException exception) {
                if (DEBUG) Log.e(&quot;Exception&quot;, exception.getDetailMessage());
                Toast.makeText(HomeActivity.this, &quot;/me Request failed&quot;, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

 

Step 19

Set User profile

We set user name and user profile image from PDK user.

/**
 *  set User name nad profile image
 */
 private void setUser() {

    name.setText(user.getFirstName() + &quot; &quot; + user.getLastName() );
    Picasso.with(this).load(user.getImageUrl()).into(profile);
 }

 

Step 20

Logout Process

We will logout from Pinterest by calling logout() method of PDKClient class. So, create a logout() method. Within this method, call logout() method of PDKClient class and start MainActivity class.

/**
 * Logout from pinterest and start another activity
 * @param view
 */
 public void logout(View view){

     PDKClient.getInstance().logout();
     Intent intent = new Intent(HomeActivity.this, MainActivity.class);
     startActivity(intent);
     finish();
}

 

Step 21

Display Pin

To display user pin, we will create Another Activity called MyPinsActivity. In the HomeActivity, we need to create a callback myPins() method to start MyPinsActivity activity. We will explain about MyPinsActivity in How to retrieve Pins from Pinterest in Android Tutorial.

public void myPins(View view){
       Intent pin = new Intent(HomeActivity.this, MyPinsActivity.class);
       startActivity(pin);
}

 

Step 22

Final code of HomeActivity class

Here is final code of HomeActivity class

public class HomeActivity extends AppCompatActivity {

    private final String USER_FIELDS = &quot;id,image,counts,created_at,first_name,last_name,bio&quot;;
    private static boolean DEBUG = true;
    private TextView name;
    private ImageView profile;
    PDKUser user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        name = (TextView) findViewById(R.id.name_textview);
        profile = (ImageView) findViewById(R.id.profile_imageview);

        getUserDetails();
    }

    /**
     * Get authenticated user details by calling getMe() method of PDKClient.
     * Pass the user field and PDKCallback object.
     */
    private void  getUserDetails() {

        PDKClient.getInstance().getMe(USER_FIELDS, new PDKCallback() {

            /**
             * It called, when successfully retrieve details of user.
             * @param response
             */
            @Override
            public void onSuccess(PDKResponse response) {

                if (DEBUG)
                    Log.e(&quot;Response&quot;, String.format(&quot;status: %d&quot;, response.getStatusCode()));

                user = response.getUser();

                // Call setUser() method
                setUser();
            }

            /**
             * It called , when request to get user details failed
             * @param exception
             */
            @Override
            public void onFailure(PDKException exception) {
                if (DEBUG) Log.e(&quot;Exception&quot;, exception.getDetailMessage());
                Toast.makeText(HomeActivity.this, &quot;/me Request failed&quot;, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     *  set User name nad profile image
     */
    private void setUser() {

        name.setText(user.getFirstName() + &quot; &quot; + user.getLastName() );
        Picasso.with(this).load(user.getImageUrl()).into(profile);
    }

    public void myPins(View view){
        Intent pin = new Intent(HomeActivity.this, MyPinsActivity.class);
        startActivity(pin);
    }

    /**
     * Logout from pinterest and start another activity
     * @param view
     */
    public void logout(View view){

        PDKClient.getInstance().logout();
        Intent intent = new Intent(HomeActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    }
}

 

Udemy Generic 728x90


 
 

Udemy Generic 728x90

Spread the word. Share this post!

  • Gagandeep Singh

    Thanks!! It worked very well

  • kishan

    i can not redirect on home page please tell me how to solve this problem or where i can did a mistake??

  • Sky andi

    how to get myboards list?