20 Mar 2014

Popup Menu | List Popup Menu Android Example

Hello Friends,

Popup menu is a modal menu that is anchored on a view. It is either displayed below if there is enough room or above the view. Popup menu is introduced in Android HoneyComb ( API level 11 ) version.
Here is the sample which is work for all android version it is display any position on screen
In this application, a popup menu will be displayed on clicking a button available in the Main Activity.

Output Screen:



SampleActivity.java 


import hb.popupmenu.lib.MenuItem;
import hb.popupmenu.lib.PopupMenu;
import hb.popupmenu.lib.PopupMenu.OnItemSelectedListener;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class SampleActivity extends ListActivity implements OnItemSelectedListener 
{
 private final static int PLAY_SELECTION = 0;
 private final static int ADD_TO_PLAYLIST = 1;
 private final static int SEARCH = 2;

 @Override
 public void onCreate(Bundle savedInstanceState) 
 {
  super.onCreate(savedInstanceState);

  String[] array = new String[] { "a", "b", "c", "d", "e", "f", "g", "h", "i" };
  setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, array));
 }

 @Override
 protected void onListItemClick(ListView l, View v, int position, long id) 
 {
  // Create Instance
  PopupMenu menu = new PopupMenu(this);
  menu.setHeaderTitle("Popup Menu");
  // Set Listener
  menu.setOnItemSelectedListener(this);
  // Add Menu (Android menu like style)
  menu.add(PLAY_SELECTION, R.string.play).setIcon(
    getResources().getDrawable(R.drawable.ic_context_menu_play_normal));
  menu.add(ADD_TO_PLAYLIST, R.string.add_to_playlist).setIcon(
    getResources().getDrawable(R.drawable.ic_context_menu_add_to_playlist_normal));
  menu.add(SEARCH, R.string.search).setIcon(
    getResources().getDrawable(R.drawable.ic_context_menu_search_normal));
  menu.show(v);
 }

 @Override
 public void onItemSelected(MenuItem item) 
 {
  switch (item.getItemId()) 
  {
  case PLAY_SELECTION:
   break;

  case ADD_TO_PLAYLIST:
   break;

  case SEARCH:
   break;

  }
 }
}


Download Full source code from here Popup menu

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)

15 Mar 2014

Android Localization | Support Multiple Language in android Application.

Hello Friends,

In this tutorial we show how to write multilingual Android apps.
To build multilingual Android apps you need to collect the texts into resource files and translate them.

Once you provide the translation, Android OS will choose the resources that match user’s locale. If your application is available in several languages, Android will select the language that the device uses.


Application Localization Process:

Android loads text and media resources from the project’s ‘res’ directory. Additionally, Android can select and load resources from different directories, based on the current device configuration and locale.

For example, if the code loads a string called ‘R.string.title’, Android will choose the correct value for that string at run time by loading the appropriate strings.xml file from a matching ‘res/values’ directory.

There are some predefined codes which you can refer from below tables.


Running and Testing the Localized Application:

Once the localized string and image resources are added to the project workspace, the application is ready for testing. To test it, we can set different locales via Home > Menu > Settings > Locale & text/Language > Select locale.

list of supported languages/locales on Android

Note : The correct format for Android resource folder is not e.g. values-pt_PT but values-pt-rPT. Replace "_" by "-r".
Language / Locale                 Supported since version

English, US (en_US)               1.1
German, Germany (de_DE)           1.1
Chinese, PRC (zh_CN)              1.5
Chinese, Taiwan (zh_TW)           1.5
Czech, Czech Republic (cs_CZ)     1.5
Dutch, Belgium (nl_BE)            1.5
Dutch, Netherlands (nl_NL)        1.5
English, Australia (en_AU)        1.5
English, Britain (en_GB)          1.5
English, Canada (en_CA)           1.5
English, New Zealand (en_NZ)      1.5
English, Singapore(en_SG)         1.5
French, Belgium (fr_BE)           1.5
French, Canada (fr_CA)            1.5
French, France (fr_FR)            1.5
French, Switzerland (fr_CH)       1.5
German, Austria (de_AT)           1.5
German, Liechtenstein (de_LI)     1.5
German, Switzerland (de_CH)       1.5
Italian, Italy (it_IT)            1.5
Italian, Switzerland (it_CH)      1.5
Japanese (ja_JP)                  1.5
Korean (ko_KR)                    1.5
Polish (pl_PL)                    1.5
Russian (ru_RU)                   1.5
Spanish (es_ES)                   1.5
Arabic, Egypt (ar_EG)             2.3
Arabic, Israel (ar_IL)            2.3
Bulgarian, Bulgaria (bg_BG)       2.3
Catalan, Spain (ca_ES)            2.3
Croatian, Croatia (hr_HR)         2.3
Danish, Denmark(da_DK)            2.3
English, India (en_IN)            2.3
English, Ireland (en_IE)          2.3
English, Zimbabwe (en_ZA)         2.3
Finnish, Finland (fi_FI)          2.3
Greek, Greece (el_GR)             2.3
Hebrew, Israel (iw_IL)*           2.3
Hindi, India (hi_IN)              2.3
Hungarian, Hungary (hu_HU)        2.3
Indonesian, Indonesia (in_ID)*    2.3
Latvian, Latvia (lv_LV)           2.3
Lithuanian, Lithuania (lt_LT)     2.3
Norwegian-Bokmol, Norway(nb_NO)   2.3
Portuguese, Brazil (pt_BR)        2.3
Portuguese, Portugal (pt_PT)      2.3
Romanian, Romania (ro_RO)         2.3
Serbian (sr_RS)                   2.3
Slovak, Slovakia (sk_SK)          2.3
Slovenian, Slovenia (sl_SI)       2.3
Spanish, US (es_US)               2.3
Swedish, Sweden (sv_SE)           2.3
Tagalog, Philippines (tl_PH)      2.3
Thai, Thailand (th_TH)            2.3
Turkish, Turkey (tr_TR)           2.3
Ukrainian, Ukraine (uk_UA)        2.3
Vietnamese, Vietnam (vi_VN)       2.3
Download full source code from here LocalizationExample
I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)

3 Mar 2014

Linkedin Integration in android | Android Linkedin Api | Post on Linkedin from Android Application.

Hello Friends,

Android allows your application to connect to Linkedin and share data or any kind of updates on Linkedin.
Today i am going to post important sharing Text and Image from android application to LinkedIn.

Step 1 : Create Application- :

Go to developer site https://www.linkedin.com/secure/developer and create an APP.

Step 2 : Getting API key(Consumer Key)  and Secret key- :



Step 3: Create project :


In_dialog.xml :


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="280dip"
    android:layout_height="420dip"
    android:orientation="vertical" >

    <WebView
        android:id="@+id/webkitWebView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</RelativeLayout>

main.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@android:color/darker_gray"
    android:orientation="vertical" >

    <RelativeLayout
        android:id="@+id/header"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/blue_gradient_header" >

        <Button
            android:id="@+id/logo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="false"
            android:layout_centerVertical="true"
            android:layout_gravity="center"
            android:layout_marginLeft="8dp"
            android:background="@drawable/logo"
            android:padding="4dp"
            android:text="" />

        <TextView
            android:id="@+id/txtTitle"
            android:layout_width="wrap_content"
            android:layout_height="32dp"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:text="Linkedin"
            android:textColor="@android:color/white"
            android:textSize="22sp"
            android:textStyle="bold"
            android:typeface="sans" >
        </TextView>
    </RelativeLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:padding="10dp" >

            <TextView
                android:id="@+id/name"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:padding="15dp"
                android:text="Name"
                android:textColor="@android:color/white"
                android:textSize="16sp"
                android:textStyle="bold"
                android:visibility="invisible" />

            <ImageView
                android:id="@+id/photo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/photo"
                android:visibility="invisible" />
        </LinearLayout>

        <Button
            android:id="@+id/login"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:background="@drawable/btn_active_pressed"
            android:padding="8dp"
            android:text="Login"
            android:textColor="@android:color/white"
            android:textStyle="bold" />

        <Button
            android:id="@+id/share"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="10dp"
            android:background="@drawable/linkedin_share"
            android:visibility="invisible" />
    </LinearLayout>

</LinearLayout>


Config.java:


public class Config 
{
 public static String LINKEDIN_CONSUMER_KEY = "Your API key";
 public static String LINKEDIN_CONSUMER_SECRET = "Your Secret key";
 
 public static String OAUTH_CALLBACK_SCHEME = "x-oauthflow-linkedin";
 public static String OAUTH_CALLBACK_HOST = "callback";
 public static String OAUTH_CALLBACK_URL = OAUTH_CALLBACK_SCHEME + "://" + OAUTH_CALLBACK_HOST;
 
 //Set Scope Params which you checked while create App in LinkedIn Account
 public static String scopeParams="rw_nus+r_basicprofile";

 
}

LinkedinDialog.java:


import java.util.ArrayList;
import java.util.List;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Picture;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebView.PictureListener;
import android.webkit.WebViewClient;
import com.hb.linkedin.R;
import com.google.code.linkedinapi.client.LinkedInApiClientFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthService;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInRequestToken;

/**
 * @author hasmukh Bhadani
 */

@SuppressWarnings("deprecation")
public class LinkedinDialog extends Dialog 
{
 private ProgressDialog progressDialog = null;

 public static LinkedInApiClientFactory factory;
 public static LinkedInOAuthService oAuthService;
 public static LinkedInRequestToken liToken;

 /**
  * Construct a new LinkedIn dialog
  * 
  * @param context
  *            activity {@link Context}
  * @param progressDialog
  *            {@link ProgressDialog}
  */
 public LinkedinDialog(Context context, ProgressDialog progressDialog) 
 {
  super(context);
  this.progressDialog = progressDialog;
 }

 @Override
 protected void onCreate(Bundle savedInstanceState) 
 {
  requestWindowFeature(Window.FEATURE_NO_TITLE);// must call before super.
  super.onCreate(savedInstanceState);
  setContentView(R.layout.ln_dialog);

  setWebView();
 }

 /**
  * set webview.
  */
 @SuppressWarnings("deprecation")
 private void setWebView() 
 {
  LinkedinDialog.oAuthService = LinkedInOAuthServiceFactory.getInstance()
    .createLinkedInOAuthService(Config.LINKEDIN_CONSUMER_KEY,Config.LINKEDIN_CONSUMER_SECRET);
  LinkedinDialog.factory = LinkedInApiClientFactory.newInstance(
    Config.LINKEDIN_CONSUMER_KEY, Config.LINKEDIN_CONSUMER_SECRET);

  LinkedinDialog.liToken = LinkedinDialog.oAuthService
    .getOAuthRequestToken(Config.OAUTH_CALLBACK_URL);

  WebView mWebView = (WebView) findViewById(R.id.webkitWebView1);  
  mWebView.getSettings().setJavaScriptEnabled(true);

  Log.i("LinkedinSample", LinkedinDialog.liToken.getAuthorizationUrl());
  mWebView.loadUrl(LinkedinDialog.liToken.getAuthorizationUrl());
  mWebView.setWebViewClient(new HelloWebViewClient());

  mWebView.setPictureListener(new PictureListener() 
  {
   @Override
   public void onNewPicture(WebView view, Picture picture) 
   {
    if (progressDialog != null && progressDialog.isShowing()) 
    {
     progressDialog.dismiss();
    }

   }
  });

 } 
 class HelloWebViewClient extends WebViewClient 
 {
  @Override
  public boolean shouldOverrideUrlLoading(WebView view, String url) 
  {
   if (url.contains(Config.OAUTH_CALLBACK_URL)) 
   {
    Uri uri = Uri.parse(url);
    String verifier = uri.getQueryParameter("oauth_verifier");

    cancel();

    for (OnVerifyListener d : listeners) 
    {
     // call listener method
     d.onVerify(verifier);
    }
   } 
   else if (url.contains("https://www.google.co.in/")) 
   {
    cancel();
   } 
   else 
   {
    Log.i("LinkedinSample", "url: " + url);
    view.loadUrl(url);
   }

   return true;
  }
 }

 /**
  * List of listener.
  */
 private List<OnVerifyListener> listeners = new ArrayList<OnVerifyListener>();

 /**
  * Register a callback to be invoked when authentication have finished.
  * 
  * @param data
  *            The callback that will run
  */
 public void setVerifierListener(OnVerifyListener data)
 {
  listeners.add(data);
 }

 /**
  * Listener for oauth_verifier.
  */
 interface OnVerifyListener 
 {
  /**
   * invoked when authentication have finished.
   * 
   * @param verifier
   *            oauth_verifier code.
   */
  public void onVerify(String verifier);
 }
}

LinkedInSampleActivity.java :

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.hb.linkedin.R;
import com.google.code.linkedinapi.client.LinkedInApiClient;
import com.google.code.linkedinapi.client.LinkedInApiClientFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInAccessToken;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthService;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInRequestToken;
import com.google.code.linkedinapi.schema.Person;
import com.hb.linkedin.LinkedinDialog.OnVerifyListener;

/**
 * @author Hasmukh Bhadani
 */
public class LinkedInSampleActivity extends Activity 
{
 Button login;
 Button share; 
 TextView name;
 ImageView photo;

 LinkedInRequestToken liToken;
 LinkedInApiClient client;
 LinkedInAccessToken accessToken = null;


 public static final String OAUTH_CALLBACK_HOST = "litestcalback";

 final LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory
   .getInstance().createLinkedInOAuthService(Config.LINKEDIN_CONSUMER_KEY,
     Config.LINKEDIN_CONSUMER_SECRET, Config.scopeParams);
 final LinkedInApiClientFactory factory = LinkedInApiClientFactory.newInstance(
   Config.LINKEDIN_CONSUMER_KEY,Config.LINKEDIN_CONSUMER_SECRET);


 @TargetApi(Build.VERSION_CODES.GINGERBREAD)
 @SuppressLint("NewApi")
 @Override
 public void onCreate(Bundle savedInstanceState) 
 { 
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  if( Build.VERSION.SDK_INT >= 9)
  {
   StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
   StrictMode.setThreadPolicy(policy); 
  }
  share = (Button) findViewById(R.id.share);
  name = (TextView) findViewById(R.id.name);  
  login = (Button) findViewById(R.id.login);
  photo = (ImageView) findViewById(R.id.photo);

  login.setOnClickListener(new OnClickListener() 
  {
   @Override
   public void onClick(View v) 
   {
    linkedInLogin();
   }
  });

  // share on linkedin
  share.setOnClickListener(new OnClickListener() 
  {
   @Override
   public void onClick(View v) 
   {    
    OAuthConsumer consumer = new CommonsHttpOAuthConsumer(Config.LINKEDIN_CONSUMER_KEY, Config.LINKEDIN_CONSUMER_SECRET);
    consumer.setTokenWithSecret(accessToken.getToken(), accessToken.getTokenSecret());
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost post = new HttpPost("https://api.linkedin.com/v1/people/~/shares");

    try 
    {
     consumer.sign(post);
    }
    catch (OAuthMessageSignerException e) 
    {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } 
    catch (OAuthExpectationFailedException e) 
    {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } 
    catch (OAuthCommunicationException e) 
    {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } 
    // here need the consumer for sign in for post the share
    post.setHeader("content-type", "text/XML");

   String myEntity="<share>"
   +"<comment>Check out the LinkedIn Share API!</comment>"
   +"<content>"
   +"<title>LinkedIn Developers Documentation On Using the Share API</title>"
   +"<description>Leverage the Share API to maximize engagement on user-generated content on LinkedIn</description>"
   +"<submitted-url>https://developer.linkedin.com/documents/share-api</submitted-url>"
   +"<submitted-image-url>http://m3.licdn.com/media/p/3/000/124/1a6/089a29a.png</submitted-image-url>" 
   +"</content>"
   +"<visibility> "
   +" <code>anyone</code>" 
   +"</visibility>"
   +"</share>";

    try 
    {
     post.setEntity(new StringEntity(myEntity));
     org.apache.http.HttpResponse response = httpclient.execute(post);

     Toast.makeText(LinkedInSampleActivity.this,"Shared sucessfully", Toast.LENGTH_SHORT).show();
    } 
    catch (UnsupportedEncodingException e) 
    {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } 
    catch (ClientProtocolException e) 
    {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } 
    catch (IOException e) 
    {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }    
  });
 }

 private void linkedInLogin() 
 {
  ProgressDialog progressDialog = new ProgressDialog(LinkedInSampleActivity.this);

  LinkedinDialog d = new LinkedinDialog(LinkedInSampleActivity.this,progressDialog);
  d.show();

  // set call back listener to get oauth_verifier value
  d.setVerifierListener(new OnVerifyListener() 
  {
   @Override
   public void onVerify(String verifier)
   {
    try {
    Log.i("LinkedinSample", "verifier: " + verifier);

 accessToken = LinkedinDialog.oAuthService.getOAuthAccessToken(LinkedinDialog.liToken,verifier);
 LinkedinDialog.factory.createLinkedInApiClient(accessToken);
 client = factory.createLinkedInApiClient(accessToken);

 Log.i("LinkedinSample","ln_access_token: " + accessToken.getToken());
 Log.i("LinkedinSample","ln_access_token: " + accessToken.getTokenSecret());

 Person p = client.getProfileForCurrentUser();
 name.setText("Welcome " + p.getFirstName() + " "+ p.getLastName());


     name.setVisibility(0);
     login.setVisibility(4);
     share.setVisibility(0);     

    } 
    catch (Exception e) 
    {
     Log.i("LinkedinSample", "error to get verifier");
     e.printStackTrace();
    }
   }
  });

  // set progress dialog
  progressDialog.setMessage("Loading...");
  progressDialog.setCancelable(true);
  progressDialog.show();
 }
}


LinkedIn Dialog Screen:




See, here is the Post in LinkedIn Account.

Out Put:




Note- Don't forget to add Permission Manifest File-
<uses-permission android:name="android.permission.INTERNET" />

Download Full source code from here LinkedInSharing

More reference for LinkedIn API:
LinkedIn Api Document:

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)