-1

I am trying to login using Linkedin. I have tried the following code:

String linkedinKey = "xxxxxx";    //add your LinkedIn key
    String linkedinSecret = "xxxxxx"; //add your LinkedIn Secret

    final LinkedInOAuthService oauthService = LinkedInOAuthServiceFactory.getInstance().createLinkedInOAuthService(linkedinKey,linkedinSecret); 
    final LinkedInApiClientFactory factory = LinkedInApiClientFactory.newInstance(linkedinKey,linkedinSecret);   
    LinkedInRequestToken LinkedinrequestToken = oauthService.getOAuthRequestToken("x-oauthflow-linkedin://callback");

    String token = LinkedinrequestToken.getToken();  
    String tokenSecret = LinkedinrequestToken.getTokenSecret();  
    String authUrl = LinkedinrequestToken.getAuthorizationUrl();   




    private static Scanner s;
    private void logintoLinkedIn()
{
    String pin;
    HttpContext session = new BasicHttpContext();
    session.setAttribute("LINKEDIN_TOKEN", token);  
    session.setAttribute("LINKEDIN_TOKEN_SECRET", tokenSecret);  
    session.setAttribute("LINKEDIN_REQUEST_TOKEN", requestToken );  
    session.setAttribute("LINKEDIN_AUTH_URL", authUrl );  

    s = new Scanner(System.in);
    pin = s.next();  
   // String oauthVerifier = LinkedinrequestToken.getParameter("oauth_verifier");  
  //Pass the requestToken[session.getAttribute("LINKEDIN_REQUEST_TOKEN")] & oauthVerifier to get accesstoken  
  LinkedInAccessToken accessToken = oauthService.getOAuthAccessToken(LinkedinrequestToken, pin); 

  session.setAttribute("LINKEDIN_ACCESS_TOKEN", accessToken);  
  final LinkedInApiClient client = factory.createLinkedInApiClient(accessToken); 
  Person profile = client.getProfileForCurrentUser(EnumSet.of(ProfileField.ID));  
  Log.d("CurrentUsers Profile-Id >>",profile.getId().toString());
}

But I am getting the error:

Logcat:

11-29 07:42:22.990: E/AndroidRuntime(2212): FATAL EXCEPTION: main
11-29 07:42:22.990: E/AndroidRuntime(2212): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.main.udebate/com.main.udebate.Login}: com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceException: oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: null
11-29 07:42:22.990: E/AndroidRuntime(2212):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at android.os.Looper.loop(Looper.java:137)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at android.app.ActivityThread.main(ActivityThread.java:5041)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at java.lang.reflect.Method.invokeNative(Native Method)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at java.lang.reflect.Method.invoke(Method.java:511)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at dalvik.system.NativeStart.main(Native Method)
11-29 07:42:22.990: E/AndroidRuntime(2212): Caused by: com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceException: oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: null
11-29 07:42:22.990: E/AndroidRuntime(2212):     at com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceImpl.getOAuthRequestToken(LinkedInOAuthServiceImpl.java:180)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at com.main.udebate.Login.<init>(Login.java:95)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at java.lang.Class.newInstanceImpl(Native Method)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at java.lang.Class.newInstance(Class.java:1319)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
11-29 07:42:22.990: E/AndroidRuntime(2212):     ... 11 more
11-29 07:42:22.990: E/AndroidRuntime(2212): Caused by: oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: null
11-29 07:42:22.990: E/AndroidRuntime(2212):     at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:214)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceImpl.getOAuthRequestToken(LinkedInOAuthServiceImpl.java:172)
11-29 07:42:22.990: E/AndroidRuntime(2212):     ... 16 more
11-29 07:42:22.990: E/AndroidRuntime(2212): Caused by: android.os.NetworkOnMainThreadException
11-29 07:42:22.990: E/AndroidRuntime(2212):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:461)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:81)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at libcore.net.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:165)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at oauth.signpost.basic.DefaultOAuthProvider.sendRequest(DefaultOAuthProvider.java:48)
11-29 07:42:22.990: E/AndroidRuntime(2212):     at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:177)
11-29 07:42:22.990: E/AndroidRuntime(2212):     ... 18 more
11-29 07:47:23.132: I/Process(2212): Sending signal. PID: 2212 SIG: 9

Please can someone help me with this.

Thanks,

4 Answers 4

4

Creating a new app in LinkedIn Developer account

Go to https://www.linkedin.com/developer/apps and click on “Create Application” button. A form will open that needs to be filled for proceeding further.

Go to https://developer.linkedin.com/docs/android-sdk and download a Mobile SDK for Android.

Unzip the file and add linkedin-sdk folder in your project.

Adding Linkedin-sdk in depencencies

compile project(':linkedin-sdk')

Add the generated hask key in linkedin developer account

Go to https://www.linkedin.com/developer/apps select your application name and click the Mobile tab. Add the package name and generated hash key in your LinkedIn Application. This hash key will authenticate your mobile application.

Use the following code in MainActivity. By using this code you can generate hask key. Firstly add the hash key in your linkedin developer account then make login. If once authenticated your application with linkedin remove generateHashkey() method(there is no need again)

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.linkedin.platform.LISessionManager;
import com.linkedin.platform.errors.LIAuthError;
import com.linkedin.platform.listeners.AuthListener;
import com.linkedin.platform.utils.Scope;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MainActivity extends Activity {
    private static final String TAG = MainActivity.class.getSimpleName();
    public static final String PACKAGE = "com.android.app";
                                          // your package name

    Button login_linkedin_btn;

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

        login_linkedin_btn = (Button) findViewById(R.id.login_button);
        login_linkedin_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                login_linkedin();
            }
        });
    }

    // Authenticate with linkedin and intialize Session.

    public void login_linkedin(){
        LISessionManager.getInstance(getApplicationContext()).init(this, buildScope(), new AuthListener() {
            @Override
            public void onAuthSuccess() {

                // Toast.makeText(getApplicationContext(), "success" + LISessionManager.getInstance(getApplicationContext()).getSession().getAccessToken().toString(), Toast.LENGTH_LONG).show();

            }

            @Override
            public void onAuthError(LIAuthError error) {

                Toast.makeText(getApplicationContext(), "failed " + error.toString(),
                                 Toast.LENGTH_LONG).show();
            }
        }, true);
    }

    // After complete authentication start new HomePage Activity

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        LISessionManager.getInstance(getApplicationContext()).onActivityResult(this,
                                      requestCode, resultCode, data);
        Intent intent = new Intent(MainActivity.this,UserProfile.class);
        startActivity(intent);
    }

     // generate the hash key 
     public void generateHashkey(){
        try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    PACKAGE,
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());

                Log.d("Hask key",Base64.encodeToString(md.digest(), Base64.NO_WRAP));

            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.d(TAG, e.getMessage(), e);
        } catch (NoSuchAlgorithmException e) {
            Log.d(TAG, e.getMessage(), e);
        }
    }

    // This method is used to make permissions to retrieve data from linkedin

    private static Scope buildScope() {
        return Scope.build(Scope.R_BASICPROFILE, Scope.R_EMAILADDRESS);
    }
}

Use the following code for UserProfile.java

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.linkedin.platform.APIHelper;
import com.linkedin.platform.LISessionManager;
import com.linkedin.platform.errors.LIApiError;
import com.linkedin.platform.listeners.ApiListener;
import com.linkedin.platform.listeners.ApiResponse;
import com.squareup.picasso.Picasso;

import org.json.JSONObject;

public class UserProfile extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private static final String host = "api.linkedin.com";
    private static final String topCardUrl = "https://" + host + "/v1/people/~:" +
            "(email-address,formatted-name,phone-numbers,public-profile-url,picture-url,picture-urls::(original))";
    ProgressDialog progress;
    ImageView profile_pic;
    TextView user_name,user_email;
    NavigationView navigation_view;
    Button logout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_userprofile);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        logout = (Button) findViewById(R.id.logout);
        setSupportActionBar(toolbar);
        progress= new ProgressDialog(this);
        progress.setMessage("Retrieve data...");
        progress.setCanceledOnTouchOutside(false);
        progress.show();
        getUserData();

        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();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open,
                 R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        setNavigationHeader();
        navigation_view.setNavigationItemSelectedListener(this);

        // this is used for clear session i.e logout from linkedin

        logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LISessionManager.getInstance(getApplicationContext()).clearSession();
                Intent intent = new Intent(UserProfile.this, MainActivity.class);
                startActivity(intent);
            }
        });
    }

    /*Once User's can authenticated,
      It make an HTTP GET request to LinkedIn's REST API using the currently authenticated user's credentials.
      If successful, A LinkedIn ApiResponse object containing all of the relevant aspects of the server's response will be returned.
     */

    public void getUserData(){
        APIHelper apiHelper = APIHelper.getInstance(getApplicationContext());
        apiHelper.getRequest(UserProfile.this, topCardUrl, new ApiListener() {
            @Override
            public void onApiSuccess(ApiResponse result) {
              try {

                  setUserProfile(result.getResponseDataAsJson());
                  progress.dismiss();

              } catch (Exception e){
                 e.printStackTrace();
              }

            }

            @Override
            public void onApiError(LIApiError error) {
               // ((TextView) findViewById(R.id.error)).setText(error.toString());

            }
        });
    }
    /*
       Set Navigation header by using Layout Inflater.
     */

    public void setNavigationHeader(){

        navigation_view = (NavigationView) findViewById(R.id.nav_view);

        View header = LayoutInflater.from(this).inflate(R.layout.nav_header_user_profile, null);
        navigation_view.addHeaderView(header);

        user_name = (TextView) header.findViewById(R.id.username);
        profile_pic = (ImageView) header.findViewById(R.id.profile_pic);
        user_email = (TextView) header.findViewById(R.id.email);
    }

    /*
       Set User Profile Information in Navigation Bar.
     */

    public  void  setUserProfile(JSONObject response){

        try {

            user_email.setText(response.get("emailAddress").toString());
            user_name.setText(response.get("formattedName").toString());

            Picasso.with(this).load(response.getString("pictureUrl"))
                    .into(profile_pic);

        } catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.user_profile, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}
2
  • 1
    There is NO MOBILE TAB in current developer account. Commented Dec 20, 2019 at 5:13
  • @ShurvirMori Exactly There is NO MOBILE TAB in current developer account..How to solve this issue.. Commented Jan 17, 2020 at 13:27
1

Apart from errors related to your Linkedin authentication notice the log says "Caused by: android.os.NetworkOnMainThreadException". You are making request to the server on your main activity which is not right as your main activity will look like its stuck to users even though your application is fetching information in background. Use AsyncTask instead. check out the documentation: http://developer.android.com/reference/android/os/AsyncTask.html

0

You should do in following manner to communicate with Linkedin API: Step 1:

Get pin by using API

oauthService= LinkedInOAuthServiceFactory.getInstance().createLinkedInOAuthService(consumerKeyValue, consumerSecretValue);   
    requestToken= oauthService.getOAuthRequestToken();
    //requestToken=oauthService.getOAuthRequestToken();
    //getOAuthRequestToken(""); 
    autoToken= requestToken.getToken();  
    authoTokenSecret = requestToken.getTokenSecret();  
    authUrl= requestToken.getAuthorizationUrl();
    Log.i("Tok", autoToken);
    Log.i("Tok", authoTokenSecret);
    Log.i("Tok", authUrl);

    webview.loadUrl(authUrl);

Step 2:

webview will show pin after login to linked in now use your pin to got access token and using access token you can get profile and update status

String pin = pin_edit.getText().toString();
    System.out.println("Fetching access token from  LinkedIn...");        
    LinkedInAccessToken accessToken =  oauthService.getOAuthAccessToken(requestToken, pin);
    System.out.println("Access token: " +  accessToken.getToken());
    System.out.println("Token secret: " +  accessToken.getTokenSecret());
    final LinkedInApiClientFactory factory =  LinkedInApiClientFactory.newInstance(consumerKeyValue,  consumerSecretValue);
    final LinkedInApiClient client =  factory.createLinkedInApiClient(accessToken);

    Person profile = client.getProfileForCurrentUser();
    profile.setCurrentStatus("Hello all my friends ,I am missing you all"); 
    client.updateCurrentStatus("Hello all going");
3
  • use your pin to got access token and using access token you can get profile and update status
    – Imran
    Commented Nov 29, 2013 at 8:24
  • but what is pin_edit. I don't have webview also. Do I need to make changes in the xml file.
    – asifa
    Commented Nov 29, 2013 at 8:26
  • But i don't want to change my xml file. Can't it be done using http
    – asifa
    Commented Nov 29, 2013 at 8:28
-1
     private void retrieveBasicProfile(String token) {
    
            try {
                String profileUrl = "https://api.linkedin.com/v2/me?projection=(id,firstName,lastName,profilePicture(displayImage~:playableStreams))";
                String result = RequestHandler.sendGet(profileUrl, token);
                 if (result != null) {
 JSONObject jsonObject = new JSONObject(result);

            String linkedInUserId = jsonObject.getString("id");
            String country = jsonObject.getJSONObject("firstName").getJSONObject("preferredLocale").getString("country");
            String language = jsonObject.getJSONObject("firstName").getJSONObject("preferredLocale").getString("language");
            String firstNameKey = language + "_" + country;
            String linkedInUserFirstName = jsonObject.getJSONObject("firstName").getJSONObject("localized").getString(firstNameKey);
            String linkedInUserLastName = jsonObject.getJSONObject("lastName").getJSONObject("localized").getString(firstNameKey);
            String linkedInUserProfile = jsonObject.getJSONObject("profilePicture").getJSONObject("displayImage~").getJSONArray("elements").getJSONObject(0).getJSONArray("identifiers").getJSONObject(0).getString("identifier");


               }
            } catch (Exception e) {
                pd.dismiss();
                 
            }
    
        }

Blockquote

private void retrieveEmailFromAPI(String token)   {

        Log.e("retrieveEmailFromAPI", token);
        try {
            String emailUrl = "https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))";
            String result = RequestHandler.sendGet(emailUrl, token);
            if (result != null) {
                JSONObject jsonObject = new JSONObject(result);
                String email = jsonObject.getJSONArray("elements").getJSONObject(0).getJSONObject("handle~").getString("emailAddress");
                 if(email!=null) {
                     AppRecords.social_user.put("email", email);
                     retrieveBasicProfile(token);
                 }

            } else {
                pd.dismiss();
            }
        }catch (Exception e){
            retrieveBasicProfile(token);

        }
    }

Linkedin integration :

https://medium.com/walkinthecode/linkedin-integration-with-v2-in-android-using-rest-api-9face97b7525

HttpClient won't import in Android Studio

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.