Friday 3 February 2017

LinkedIn Login Integration in Android



1. Creating a new app in LinkedIn Developer account

Go to https://www.linkedin.com/developer/apps  and click “Create Application” button.


2.Create a New Application From

        Company Name, Name, Description, App Logo, App Use, Website URL, Business Email, Business Phone and checked Linkedin API Terms of Use and Click Submit Button.



3. Set the Application Permission

you have to select check box “r_basicprofile” and “r_emailaddress” and click on the “update” button to set the permission.



4. Generate hash Key

       4.1 activity_main.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.linkedinlogin.MainActivity">
    <LinearLayout       
            android:layout_width="wrap_content"       
            android:layout_height="wrap_content"        
            android:orientation="vertical"       
            android:layout_marginTop="47dp"       
            android:layout_below="@+id/linearLayout"       
            android:layout_alignParentLeft="true"       
            android:layout_alignParentStart="true">
        <TextView           
           android:layout_width="wrap_content"           
           android:layout_height="wrap_content"           
           android:text="Package info" />
        <View            
           android:layout_width="fill_parent"           
           android:layout_height="1dp"            
           android:background="@android:color/darker_gray" />
        <Button           
           android:id="@+id/show_hash"           
           android:layout_width="wrap_content"            
           android:layout_height="wrap_content"            
           android:text="show pack / hash" />
        <TextView            
           android:id="@+id/package_name"           
           android:layout_width="wrap_content"            
           android:layout_height="wrap_content" />
        <TextView            
           android:id="@+id/hash_key"            
           android:layout_width="wrap_content"            
           android:layout_height="wrap_content" />
        <TextView            
           android:id="@+id/error"            
           android:layout_width="wrap_content"            
           android:layout_height="wrap_content" />

    </LinearLayout>

</RelativeLayout>


       4.2 MainActivity.java

package com.linkedinlogin;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.support.v7.app.AppCompatActivity;
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 AppCompatActivity {

    Button hask_key,login_linkedin_btn;
    private static final String TAG = MainActivity.class.getSimpleName();
    public static final String PACKAGE = "com.linkedinlogin";

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

        hask_key = (Button) findViewById(R.id.show_hash);
        hask_key.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                generateHashkey();
            }
        });
    }

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

                ((TextView) findViewById(R.id.package_name)).setText(info.packageName);
                ((TextView) findViewById(R.id.hash_key)).setText(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);
        }
    }
}

4.3 Adding hash key in your LinkedIn Developer account

       Go to https://www.linkedin.com/developer/apps/4908705/mobile  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.



5. Download Mobile LinkedIn SDK

       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.



6. Include Linkedin SDK in setting.gradle file

Open setting.gradle file in your project and include linkedin-sdk folder in your project.
        include ':app',':linkedin-sdk'




7. Adding library in depencencies

       compile project(':linkedin-sdk')
       compile 'com.squareup.picasso:picasso:2.5.2'       compile 'de.hdodenhof:circleimageview:1.3.0'       compile 'com.android.support:design:23.1.1'

synchronize your project.

8. AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.linkedinlogin">

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

    <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:supportsRtl="true"        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".WelcomePage"></activity>
    </application>

</manifest>

9. activity_main.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.linkedinlogin.MainActivity">
    <LinearLayout        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:orientation="vertical"        android:id="@+id/linearLayout">
        <TextView            android:id="@+id/welcome_li"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="LinkedIn"            android:textSize="20dp"            android:layout_marginBottom="20dp"/>
        <Button            android:id="@+id/login_button"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:background="@drawable/button"            android:layout_marginBottom="15dp"/>
    </LinearLayout>

    <LinearLayout        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:orientation="vertical"        android:layout_marginTop="47dp"        android:layout_below="@+id/linearLayout"        android:layout_alignParentLeft="true"        android:layout_alignParentStart="true">
        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="Package info" />
        <View            android:layout_width="fill_parent"            android:layout_height="1dp"            android:background="@android:color/darker_gray" />
        <Button            android:id="@+id/show_hash"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="show pack / hash" />
        <TextView            android:id="@+id/package_name"            android:layout_width="wrap_content"            android:layout_height="wrap_content" />
        <TextView            android:id="@+id/hash_key"            android:layout_width="wrap_content"            android:layout_height="wrap_content" />
        <TextView            android:id="@+id/error"            android:layout_width="wrap_content"            android:layout_height="wrap_content" />
    </LinearLayout>

</RelativeLayout>

10.activity_welcome_page.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_welcome_page"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.linkedinlogin.WelcomePage">

    <ImageView        android:layout_width="200dp"        android:layout_height="200dp"        android:id="@+id/profile_pic"        android:layout_marginTop="34dp"        android:layout_alignParentTop="true"        android:layout_centerHorizontal="true"        android:src="@drawable/ic_launcher"/>

    <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/username"        android:hint="User Name"        android:gravity="center"        android:layout_below="@+id/profile_pic"        android:layout_alignParentLeft="true"        android:layout_alignParentStart="true"        android:layout_marginTop="35dp"        android:textSize="25dp"/>

    <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:textSize="25dp"        android:hint="Email"        android:gravity="center"        android:layout_below="@+id/username"        android:layout_alignParentLeft="true"        android:layout_alignParentStart="true"        android:layout_marginTop="18dp"        android:id="@+id/email" />

    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="logout"        android:id="@+id/logout"        android:layout_alignParentBottom="true"        android:layout_alignParentLeft="true"        android:layout_alignParentStart="true" />

</RelativeLayout>

11.MainActivity.java

package com.linkedinlogin;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.support.v7.app.AppCompatActivity;
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 AppCompatActivity {

    Button hask_key,login_linkedin_btn;
    private static final String TAG = MainActivity.class.getSimpleName();
    public static final String PACKAGE = "com.linkedinlogin";

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

        hask_key = (Button) findViewById(R.id.show_hash);
        hask_key.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                generateHashkey();
            }
        });
        //Compute application package and hash        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();                login_linkedin_btn.setVisibility(View.GONE);
            }
            @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,WelcomePage.class);
        startActivity(intent);
    }

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

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

                ((TextView) findViewById(R.id.package_name)).setText(info.packageName);
                ((TextView) findViewById(R.id.hash_key)).setText(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);
        }
    }
}


12. WelcomePage.java

package com.linkedinlogin;

import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
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 WelcomePage extends AppCompatActivity {

    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;
    Button logout;

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

        user_name = (TextView) findViewById(R.id.username);
        profile_pic = (ImageView) findViewById(R.id.profile_pic);
        user_email = (TextView) findViewById(R.id.email);
        logout = (Button) findViewById(R.id.logout);

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

        progress = new ProgressDialog(this);
        progress.setMessage("Retrieve data...");
        progress.setCanceledOnTouchOutside(false);
        progress.show();
        getUserData();
    }

    public void getUserData() {
        APIHelper apiHelper = APIHelper.getInstance(getApplicationContext());
        apiHelper.getRequest(WelcomePage.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());

            }
        });

    }

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

}

Thursday 2 February 2017

Spinner DropDown List Example using PHP MySQL



SQL File



PHP File

<?php
  $DB_USER='YOUR USER'; 
$DB_PASS='YOUR PASSWORD'; 
$DB_HOST='localhost';
$DB_NAME='YOUR DATABASE NAME';

   $mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
   /* check connection */
   if (mysqli_connect_errno())
                   {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
   }
   $mysqli->query("SET NAMES 'utf8'");

   $sql="SELECT iname FROM Spinnertest";

   $result=$mysqli->query($sql);
    while($e=mysqli_fetch_assoc($result))
                     {
$output[]=$e; 
     }
print(json_encode($output)); 
$mysqli->close();
?>

gradle Files

include android {....} brfore buildToolsVersion 

useLibrary 'org.apache.http.legacy'

incclude dependencies{....}

compile 'com.loopj.android:android-async-http:1.4.5'
compile 'com.android.support:design:23.0.0'

Android Files

     1. AndroidManifest.xml

Include user permission in your AndroidManifest File
<uses-permission android:name="android.permission.INTERNET" />

     2. spinner_layout.xml

<?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/txt"        
       android:layout_width="match_parent"        
       android:layout_height="wrap_content"      
       android:padding="10dp"        
       android:textSize="30dp"
       android:textColor="#000000" />
</LinearLayout>


     3. activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
xmlns:tools="http://schemas.android.com/tools"    
android:layout_width="match_parent"    
android:layout_height="match_parent"    
android:orientation="vertical"    
android:padding="10dp"    
tools:context=".MainActivity"    
android:weightSum="1">
   <TextView
    android:layout_width="match_parent"    
    android:layout_height="wrap_content"
    android:text="Click Spinner"
    android:gravity="center"
    android:textSize="25dp" />

   <Spinner
      android:id="@+id/spinner"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_weight="0.07">
   </Spinner>
</LinearLayout>

4. MainActivity.java

package com.spinnerexample;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity{
    ArrayList<String> listItems=new ArrayList<>();
    ArrayAdapter<String> adapter;
    Spinner sp;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sp=(Spinner)findViewById(R.id.spinner);
        adapter=new ArrayAdapter<String>(this,R.layout.spinner_layout,R.id.txt,listItems);
        sp.setAdapter(adapter);
        sp.setOnItemSelectedListener(
                new AdapterView.OnItemSelectedListener() {
                    public void onItemSelected(
                            AdapterView<?> parent, View view, int position, long id) {
                        Toast.makeText(getApplicationContext(),listItems.get(position),Toast.LENGTH_LONG).show();
                    }
                    public void onNothingSelected(AdapterView<?> parent) {
                    }
                });

    }
    public void onStart(){
        super.onStart();
        BackTask bt=new BackTask();
        bt.execute();
    }



    private class BackTask extends AsyncTask<Void,Void,Void> {
        ProgressDialog loading;
        ArrayList<String> list;
        protected void onPreExecute(){
            super.onPreExecute();
            loading = ProgressDialog.show(MainActivity.this, "Please Wait",null, true, true);
            list=new ArrayList<>();
        }
        protected Void doInBackground(Void...params){
            InputStream is=null;
            String result="";
            try{
                HttpClient httpclient=new DefaultHttpClient();
                HttpPost httppost= new HttpPost("http://krishscs.esy.es/Spinner_test.php");
                HttpResponse response=httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                // Get our response as a String.
                is = entity.getContent();
            }catch(IOException e){
                e.printStackTrace();
            }

            //convert response to string            try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    result+=line;
                }
                is.close();
                //result=sb.toString();
            }catch(Exception e){
                e.printStackTrace();
            }
            // parse json data
            try{
                JSONArray jArray =new JSONArray(result);
                for(int i=0;i<jArray.length();i++){
                    JSONObject jsonObject=jArray.getJSONObject(i);
                    // add interviewee name to arraylist
                    list.add(jsonObject.getString("iname"));
                }
            }
            catch(JSONException e){
                e.printStackTrace();
            }
            return null;
        }
        protected void onPostExecute(Void result){
            listItems.addAll(list);
            adapter.notifyDataSetChanged();
            loading.dismiss();

            Toast.makeText(getApplicationContext(),"Loading Completed",Toast.LENGTH_LONG).show();
        }
    }
}