Sunday 29 December 2013

Android make Image Sharper | Android image Blur Issue

Hello Droid Guys,
    Today , I am going to share a sample code which helps you in making image
more sharper and clear also helps you in fixing image Blur issue .This is based on
Convolution Matrix Theorem.

About Convolution Matrix : Check this link

Image Before:


Image After :


 1. ImageHelper.java : This is our helper class which helps in processing image
     sharper/


package com.exampl.imagerun;

import android.graphics.Bitmap;
import android.graphics.Color;
 
public class ImageHelper
{
    public static final int SIZE = 3;
 
    public double[][] Matrix;
    public double Factor = 1;
    public double Offset = 1;
 
   //Constructor with argument of size
    public ImageHelper(int size) {
        Matrix = new double[size][size];
    }
 
    public void setAll(double value) {
        for (int x = 0; x < SIZE; ++x) {
            for (int y = 0; y < SIZE; ++y) {
                Matrix[x][y] = value;
            }
        }
    }
 
    public void applyConfig(double[][] config) {
        for(int x = 0; x < SIZE; ++x) {
            for(int y = 0; y < SIZE; ++y) {
                Matrix[x][y] = config[x][y];
            }
        }
    }
 
    public static Bitmap computeConvolution3x3(Bitmap src, ImageHelper matrix) {
        int width = src.getWidth();
        int height = src.getHeight();
        Bitmap result = Bitmap.createBitmap(width, height, src.getConfig());
 
        int A, R, G, B;
        int sumR, sumG, sumB;
        int[][] pixels = new int[SIZE][SIZE];
 
        for(int y = 0; y < height - 2; ++y) {
            for(int x = 0; x < width - 2; ++x) {
 
                // get pixel matrix
                for(int i = 0; i < SIZE; ++i) {
                    for(int j = 0; j < SIZE; ++j) {
                        pixels[i][j] = src.getPixel(x + i, y + j);
                    }
                }
 
                // get alpha of center pixel
                A = Color.alpha(pixels[1][1]);
 
                // init color sum
                sumR = sumG = sumB = 0;
 
                // get sum of RGB on matrix
                for(int i = 0; i < SIZE; ++i) {
                    for(int j = 0; j < SIZE; ++j) {
                        sumR += (Color.red(pixels[i][j]) * matrix.Matrix[i][j]);
                        sumG += (Color.green(pixels[i][j]) * matrix.Matrix[i][j]);
                        sumB += (Color.blue(pixels[i][j]) * matrix.Matrix[i][j]);
                    }
                }
 
                // get final Red
                R = (int)(sumR / matrix.Factor + matrix.Offset);
                if(R < 0) { R = 0; }
                else if(R > 255) { R = 255; }
 
                // get final Green
                G = (int)(sumG / matrix.Factor + matrix.Offset);
                if(G < 0) { G = 0; }
                else if(G > 255) { G = 255; }
 
                // get final Blue
                B = (int)(sumB / matrix.Factor + matrix.Offset);
                if(B < 0) { B = 0; }
                else if(B > 255) { B = 255; }
 
                // apply new pixel
                result.setPixel(x + 1, y + 1, Color.argb(A, R, G, B));
            }
        }
 
        // final image
        return result;
    }
}

 Now, In our Activity class we need to add following code:

ImageView imageView=(ImageView)findViewById(R.id.image);


Now set image on image view

image.setImageBitmap(sharpenImage(BitmapFactory.

decodeResource(getResources(),images[i]),12));

And, here we are using Convolution Matrix Theorem to make image sharper.

 public Bitmap sharpenImage(Bitmap src, double weight) {
    // set sharpness configuration
    double[][] SharpConfig = new double[][] { { 0, -2, 0 },
    { -2, weight, -2 }, { 0, -2, 0 } };
    // create convolution matrix instance
    ImageHelper convMatrix = new ImageHelper(3);
    // apply configuration
    convMatrix.applyConfig(SharpConfig);
    // set weight according to factor
    convMatrix.Factor = weight - 8;
    return ImageHelper.computeConvolution3x3(src, convMatrix);
 }


Hope this will help some one.
Enjoy Coding :)

Friday 13 December 2013

Android File or Folder listing from Sd Card | Android File explorer |Android folder listing | List file from sd card android

Hello Friends,
            This sample helps you in browsing your Sd Card folder and files. List all your music folder, file and images programmatically .



Here are the code:

1.ListFolder.Java
package com.android.sdcard.folder;

import java.io.File;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.text.DateFormat;

import com.example.fileexplorer.R;

import android.os.Bundle;
import android.app.ListActivity;
import android.content.Intent;
import android.view.View;
import android.widget.ListView;

public class ListFolder extends ListActivity {

 private File currentDir;
 private FileArrayAdapter adapter;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  currentDir = new File("/sdcard/");
  fill(currentDir);
 }

 private void fill(File f) {
  File[] dirs = f.listFiles();
  this.setTitle("Current Dir: " + f.getName());
  List dir = new ArrayList();
  List fls = new ArrayList();
  try {
   for (File ff : dirs) {
    String name = ff.getName();
    Date lastModDate = new Date(ff.lastModified());
    DateFormat formater = DateFormat.getDateTimeInstance();
    String date_modify = formater.format(lastModDate);
    /*
     * Note: Remove this
     * name.equalsIgnoreCase("Covenant and Augment Softsol" if u
     * want to list all ur sd card file and folder
     */
    if (ff.isDirectory()
              && name.equalsIgnoreCase("Covenant and Augment Softsol")) {

     File[] fbuf = ff.listFiles();
     int buf = 0;
     if (fbuf != null) {
      buf = fbuf.length;
     } else
      buf = 0;
     String num_item = String.valueOf(buf);
     if (buf == 0)
      num_item = num_item + " item";
     else
      num_item = num_item + " items";

     // String formated = lastModDate.toString();
     dir.add(new Albumb(ff.getName(), num_item, date_modify, ff
       .getAbsolutePath(), "directory_icon"));
    } else {
     /*
      * Note: Remove this
      * f.getName().equalsIgnoreCase("Covenant and Augment Softsol"
      * if u want to list all ur sd card file and folder
      */
     if (f.getName().equalsIgnoreCase(
       "Covenant and Augment Softsol")) {
      fls.add(new Albumb(ff.getName(), ff.length() + " Byte",
        date_modify, ff.getAbsolutePath(), "file_icon"));
     }
    }
   }
  } catch (Exception e) {

  }
  Collections.sort(dir);
  Collections.sort(fls);
  dir.addAll(fls);
  if (!f.getName().equalsIgnoreCase("sdcard"))
   dir.add(0, new Albumb("..", "Parent Directory", "", f.getParent(),
     "directory_up"));
  adapter = new FileArrayAdapter(ListFolder.this, R.layout.file_view, dir);
  this.setListAdapter(adapter);
 }

 @Override
 protected void onListItemClick(ListView l, View v, int position, long id) {
  // TODO Auto-generated method stub
  super.onListItemClick(l, v, position, id);
  Albumb o = adapter.getItem(position);
  if (o.getImage().equalsIgnoreCase("directory_icon")
    || o.getImage().equalsIgnoreCase("directory_up")) {
   currentDir = new File(o.getPath());
   fill(currentDir);
  }
 }

}



2. Albumb.java

package com.android.sdcard.folder;

 public class Albumb implements Comparable{
 private String name;
 private String data;
 private String date;
 private String path;
 private String image;
 
 public Albumb(String name,String date, String dt, String path, String image)
 {
  this.name = name;
  this.data = date;
  this.path = path; 
  this.image = image;
  
 }
 public String getName()
 {
  return name;
 }
 public String getData()
 {
  return data;
 }
 public String getDate()
 {
  return date;
 }
 public String getPath()
 {
  return path;
 }
 public String getImage() {
  return image;
 }
 
 public int compareTo(Albumb o) {
  if(this.name != null)
   return this.name.toLowerCase().compareTo(o.getName().toLowerCase()); 
  else 
   throw new IllegalArgumentException();
 }
}



3. FileArrayAdapter.java

package com.android.sdcard.folder;

import java.util.List;

import com.example.fileexplorer.R;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;

public class FileArrayAdapter extends ArrayAdapter {

 private Context c;
 private int id;
 private List items;

 public FileArrayAdapter(Context context, int textViewResourceId,
   List objects) {
  super(context, textViewResourceId, objects);
  c = context;
  id = textViewResourceId;
  items = objects;
 }

 public Albumb getItem(int i) {
  return items.get(i);
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  View v = convertView;
  if (v == null) {
   LayoutInflater vi = (LayoutInflater) c
     .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   v = vi.inflate(id, null);
  }

  /* create a new view of my layout and inflate it in the row */
  // convertView = ( RelativeLayout ) inflater.inflate( resource, null );

  final Albumb item = items.get(position);
  if (item != null) {
   TextView t1 = (TextView) v.findViewById(R.id.TextView01);
   TextView t2 = (TextView) v.findViewById(R.id.TextView02);
   TextView t3 = (TextView) v.findViewById(R.id.TextViewDate);
   /* Take the ImageView from layout and set the city's image */
   ImageView imageCity = (ImageView) v.findViewById(R.id.fd_Icon1);

   String type = item.getImage();
   if (type.equalsIgnoreCase("directory_icon")) {
    String uri = "drawable/" + item.getImage();
    int imageResource = c.getResources().getIdentifier(uri, null,
      c.getPackageName());
    Drawable image = c.getResources().getDrawable(imageResource);
    imageCity.setImageDrawable(image);
   } else {
    Bitmap bmp = BitmapFactory.decodeFile(item.getPath());
    imageCity.setImageBitmap(bmp);
   }
   if (t1 != null)
    t1.setText(item.getName());
   if (t2 != null)
    t2.setText(item.getData());
   if (t3 != null)
    t3.setText(item.getDate());

  }
  return v;
 }

}


4. AndroidManifest,xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.fileexplorer"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.android.sdcard.folder.ListFolder"
            android:label="@string/title_activity_fileexplorer"
            android:theme="@android:style/Theme.Holo" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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



Download complete code here



Hope this will helps some one.
Enjoy Coidng :)

Wednesday 4 December 2013

Android Play video from SD Card | Populating a listview with videos from sdcard in android

Hello Friends,
            This is an android simple example which list all videos file store in 
device sd card and Play it in Video view .
Android provides a view control android.widget.VideoView that encapsulates
creating and initializing the MediaPlayer.










1. VideoStoredInSDCard.java

package com.example.videoplayer;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class VideoStoredInSDCard extends Activity {
 private Cursor videocursor;
 private int video_column_index;
 ListView videolist;
 int count;
 String[] thumbColumns = { MediaStore.Video.Thumbnails.DATA,
   MediaStore.Video.Thumbnails.VIDEO_ID };

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  init_phone_video_grid();
 }

 @SuppressWarnings("deprecation")
 private void init_phone_video_grid() {
  System.gc();
  String[] proj = { MediaStore.Video.Media._ID,
    MediaStore.Video.Media.DATA,
    MediaStore.Video.Media.DISPLAY_NAME,
    MediaStore.Video.Media.SIZE };
  videocursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
    proj, null, null, null);
  count = videocursor.getCount();
  videolist = (ListView) findViewById(R.id.PhoneVideoList);
  videolist.setAdapter(new VideoAdapter(getApplicationContext()));
  videolist.setOnItemClickListener(videogridlistener);
 }

 private OnItemClickListener videogridlistener = new OnItemClickListener() {
  public void onItemClick(AdapterView parent, View v, int position,
    long id) {
   System.gc();
   video_column_index = videocursor
     .getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
   videocursor.moveToPosition(position);
   String filename = videocursor.getString(video_column_index);
   Intent intent = new Intent(VideoStoredInSDCard.this,
     ViewVideo.class);
   intent.putExtra("videofilename", filename);
   startActivity(intent);
  }
 };

 public class VideoAdapter extends BaseAdapter {
  private Context vContext;

  public VideoAdapter(Context c) {
   vContext = c;
  }

  public int getCount() {
   return count;
  }

  public Object getItem(int position) {
   return position;
  }

  public long getItemId(int position) {
   return position;
  }

  public View getView(int position, View convertView, ViewGroup parent) {
   System.gc();
   ViewHolder holder;
   String id = null;
   convertView = null;
   if (convertView == null) {
    convertView = LayoutInflater.from(vContext).inflate(
      R.layout.listitem, parent, false);
    holder = new ViewHolder();
    holder.txtTitle = (TextView) convertView
      .findViewById(R.id.txtTitle);
    holder.txtSize = (TextView) convertView
      .findViewById(R.id.txtSize);
    holder.thumbImage = (ImageView) convertView
      .findViewById(R.id.imgIcon);

    video_column_index = videocursor
      .getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
    videocursor.moveToPosition(position);
    id = videocursor.getString(video_column_index);
    video_column_index = videocursor
      .getColumnIndexOrThrow(MediaStore.Video.Media.SIZE);
    videocursor.moveToPosition(position);
    // id += " Size(KB):" +
    // videocursor.getString(video_column_index);
    holder.txtTitle.setText(id);
    holder.txtSize.setText(" Size(KB):"
      + videocursor.getString(video_column_index));

    String[] proj = { MediaStore.Video.Media._ID,
      MediaStore.Video.Media.DISPLAY_NAME,
      MediaStore.Video.Media.DATA };
    @SuppressWarnings("deprecation")
    Cursor cursor = managedQuery(
      MediaStore.Video.Media.EXTERNAL_CONTENT_URI, proj,
      MediaStore.Video.Media.DISPLAY_NAME + "=?",
      new String[] { id }, null);
    cursor.moveToFirst();
    long ids = cursor.getLong(cursor
      .getColumnIndex(MediaStore.Video.Media._ID));

    ContentResolver crThumb = getContentResolver();
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 1;
    Bitmap curThumb = MediaStore.Video.Thumbnails.getThumbnail(
      crThumb, ids, MediaStore.Video.Thumbnails.MICRO_KIND,
      options);
    holder.thumbImage.setImageBitmap(curThumb);
    curThumb = null;

   } /*
    * else holder = (ViewHolder) convertView.getTag();
    */
   return convertView;
  }
 }

 static class ViewHolder {

  TextView txtTitle;
  TextView txtSize;
  ImageView thumbImage;
 }
}


2. ViewVideo.java

package com.example.videoplayer;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;

public class ViewVideo extends Activity {
      private String filename;
      VideoView vv;
      @Override
      public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            System.gc();
            Intent i = getIntent();
            Bundle extras = i.getExtras();
            filename = extras.getString("videofilename");
            // vv = new VideoView(getApplicationContext());
            setContentView(R.layout.activity_view);
            vv = (VideoView) findViewById(R.id.videoView);
            vv.setVideoPath(filename);
            vv.setMediaController(new MediaController(this));
            vv.requestFocus();
            vv.start();
      }
}


3. AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.videoplayer"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.videoplayer.VideoStoredInSDCard"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

              <category android:name="android.intent.category.LAUNCHER" />
           </intent-filter>
        </activity>
        <activity android:name=".ViewVideo" >
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>
</manifest>






Enjoy Coding :)

Download Source code Code

Monday 18 November 2013

Android Lazy Image loader Class Error | Image Loader not loading the image

Hello Friends,


One of my friend using Image Loader class to load an image from an url and displaying it
in a list view. She told me that the Image Loader is loading the image on an emulator, when
she run the app on a real device it's not loading any image.(Just showing the default image).

This problem occurs only when we didn't pass the permission in AndroidManifest.xml file.
When I saw her code I found following permission is missing..

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


After adding this , the problem is resolved and the the app is working fine on
both emulator as well as on real device.

This issued is faced by most of the android developer , So always remember add
all permission while using lazy Image loader class.

Enjoy.... :)
Happy Coding....

Thursday 14 November 2013

Invalid android_key parameter - Facebook login | Android Facebook hash key error

Hello Droid Friends,
Today , I stuck in Facebook login Issue. I am doing facebook login in my android
application but I am getting following error:


Invalid android_key parameter. The key 26gUhN_wYCwwxenlSneyTeCY
does not match any allowed key. Configure your app key hashes at 
http://developers.facebook.com/apps/22061641443615

I followed following steps:
1. downloaded openssl from here and set it in your system environment path.
     
2. Uses following command to generate hashkey on my pc.
      keytool -exportcert -alias androiddebugkey -keystore "C:\Users\Acer\.android\debug.keystore"
                                 | openssl sha1 -binary | openssl base64
 

3. Then I created a new Facebook app  and also added the generated hashkey.

4. I got the Facebook App Id Which I am now using in my and application.


After following all above steps , still I am facing the error "Invalid android_key
parameter" . Then I go to the facebook developer site and find few new things which
comes in Facebook SDK 3.5. And Its helps me in fixing the above "Invalid android_key
parameter" Issue. There Are Two way:

Step-1. When you get this error, check the logcat it returns you a different hashkey,
so you just need to replace the previous hashkey with this one. If you did not getting
any hashkey in logcat error then step-2 helps you.

Step-2: I think this is the best way of generating hashkey bcoz it removes the dependency
of debugkeystore.No need to copy and paste the same debugkeystore on each developer
machine.Here we generate hashkey on the basis of android application package name.
Just used following code for generating the hashkey.

try  {

      PackageInfo info = getPackageManager().
           getPackageInfo(this.getPackageName(), PackageManager.GET_SIGNATURES);

      for (Signature signature : info.signatures) {

          MessageDigest md = MessageDigest.getInstance("SHA");
          md.update(signature.toByteArray());
          Log.d("====Hash Key===",Base64.encodeToString(md.digest(), 
                   Base64.DEFA  ULT));

      }

  } catch (NameNotFoundException e) {

      e.printStackTrace();

  } catch (NoSuchAlgorithmException ex) {

      ex.printStackTrace();

  }




And use this generated hashkey.This will fixed your "Invalid android_key parameter" issue.

Enjoy :)
Happy Coding... :)


Sunday 10 November 2013

Android Home key press behavior | Activity stack confused when launching app

Hello Droid Guys
I found an strange issue with the behavior of Home key press in android.Please
check below link if you want more details about this issue.


Actually, I think this is an android bug. If an app is installed via market, market 
update, or download from browser and the user launches the app directly from the
installer (ie: when the installer completes it offers the user the options to launch(open)
and done and when use select open the app now) it is launched in such a way that 
the OS gets confused.

If, after the app is launched, the user presses the HOME key to return to the home 
screen and then tries to return to the app by selecting it from the list of applications 
(or by putting a shortcut on the home screen and then selecting the shortcut), the OS
launches the root activity of the app AGAIN, bringing the existing task to the foreground
and placing ANOTHER instance of the root activity on top of the existing activity stack.

This behavior is extremely difficult to debug and has certainly caused countless hours 
of head-scratching by developers.

Note: I too found the same issue when I install an app from my mail and directly launch
the app.Go to Activity "A" then goes to Activity "B" and then I pressed "Home button".
Then ,When I open the same app pressing the app launcher on home screen,Instead of 
taking me directly to Activity "B" where I left it last time , It loads the app from the start.



It takes lots of my time to fixed this issue but finally I did that. I found the
way to resolve this problme :) .
I Added following code in the onCreate() method of my launcher activity and then Its
works fine for me.


protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);

if (!isTaskRoot()) {
           Intent intent = getIntent();
           String action = intent.getAction();
           if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && action != null &&                           action.equals(Intent.ACTION_MAIN)) {
               finish();
               return;
           }
    }
}

Hope, my above code will save some one time.
Enjoy Coding :)

Saturday 9 November 2013

Android ListView Background Color Changes on Scrolling

Hello Friends,
This is very common issue I saw in android with Listview. In one of my app I am using a
listview for displaying the list of Items.I set the background of Listview as blue. Below is 
the Listview code which I am using.

 <ListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:background="#0000FF"/>


But, some times when I scroll the Listview the background color will be automatically change
to black or white. Then, I found a solution I added below line in my Listview(in xml file).

android:cacheColorHint="#00000000"
        OR
android:cacheColorHint="@android:color/transparent"


And Finally my Listview code contains following code.....

<ListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:cacheColorHint="#00000000"
        android:choiceMode="singleChoice"
        android:background="#2A323D"/>

OR at java code,use below line of code

listview.setCacheColorHint(Color.TRANSPARENT);


After adding the above one line in my xml or java file , the Listview background color 
change on scrolling issue will be gone.

Hope , the above code helps some one.
Enjoy coding......




Sunday 21 July 2013

android listview adapter getview() called multiple times

Hello Droid Guys,
Today , I found a strange issue in android custom listView adapter. I found that
the adapter getview() method called multiple times.

adapter getview() called multiple times

On my listview I am showing following Item:
1. User facebook image
2. His|Her Name
3. Some description

As, I told you that getview() method calls multiple time, due to this behavior the Image on
list item some times remain unchanged or same profile picture will be attach on different
user , in listview.
First of all I think that this was an issue of lazy image loader library But I was wronged.
After spent few times on google for searching this issue , I found this link

http://stackoverflow.com/questions/2618272/custom-listview-adapter-getview-method-being-called-multiple-times-and-in-no-co

Then After I checked my xml file and I found I am using height = wrap_content in listview.

<ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="3dp"
        android:layout_marginRight="3dp"
        android:padding="5dp"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
         android:layout_below="@+id/facebook_friend_list_header" >
    </ListView>

And when I changed this to fill_parent

        android:layout_height="fill_parent"

then all problem is resolved and now the getview() method will be called only once.
Also the user profile picture issue will be resolved.

Android Guys , still I was not cleared about the above tricks. Please let me know why
getview() method called multiple times when I am using
android:layout_height="wrap_content" . If some one know the reason then
please let me know.

Thanks in advance.
Enjoy Coding :)

Friday 12 July 2013

ActionBarSherlock with custom View | Changing sherlock action bar menu item background

Hello Friends,
Today , I am going to share my another android tutorial which is based on the
Sherlock Action Bar. ABS(Action Bar Sherlock) is an support library which helps
to use action bar design pattern over all android devices.

Initially , Action bar is supportable over android version 3.0. But if you want to
provide the interactive user interface on lower version of device too, then
ABS comes in a role.

 
sherlock action barandroid action bar
       

1. MainActivity.java

package com.example.actionbar;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.SubMenu;

public class MainActivity extends SherlockActivity {

 private SubMenu mGoItem;

 private static final int GO_ITEM_ID = 1;

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

  ActionBar ab = getSupportActionBar();
  ab.setBackgroundDrawable(getApplicationContext().getResources()
    .getDrawable(R.drawable.bg_titlebar_tile));
  ab.setLogo(getResources().getDrawable(R.drawable.logo));
  ab.setDisplayShowTitleEnabled(false);
 }

 @SuppressLint("InlinedApi")
 @Override
 public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {

  mGoItem = menu.addSubMenu(0, GO_ITEM_ID, 0, null);
  mGoItem.setIcon(R.drawable.setting_icon);
  // SubMenu sub = menu.addSubMenu("Theme");
  mGoItem.add(0, R.style.Theme_Sherlock, 0, "View Profile");
  mGoItem.add(0, R.style.Theme_Sherlock_Light, 0, "Account Privacy");
  mGoItem.add(0, R.style.Theme_Sherlock_Light_DarkActionBar, 0,
    "Logout");
  mGoItem.getItem().setShowAsAction(
    MenuItem.SHOW_AS_ACTION_ALWAYS
      | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

  return true;
 }

 @SuppressLint("InlinedApi")
 @Override
 public boolean onOptionsItemSelected(
   com.actionbarsherlock.view.MenuItem item) {

  switch (item.getItemId()) {
  case GO_ITEM_ID:
   Toast.makeText(MainActivity.this,
     "You have Pressed 'Setting' Menu Button", Toast.LENGTH_LONG)
     .show();
   return true;
  }

  return false;
 }

}

2.activity_main.xml


<RelativeLayout 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:background="@android:color/white"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textColor="@android:color/black"
        android:textStyle="bold"
        android:text="@string/hello_action_bar" />

</RelativeLayout>


Download the complete source code: Here

Friday 28 June 2013

Asserting Toast message using Robolectric | Testing Toast message Android

Hello Friends,
Today , I am sharing my another android tutorial. In this tutorial I am going to show
how to write the test case for android Toast message using Roboelectric and Junit.


 @Test
 public void testToastMesaage() throws Exception{
    Helper.showBadServerNotification(activity);
     assertThat( ShadowToast.getTextOfLatestToast(),equalTo(
              shadowActivity.getString(R.string.bad_server_response)));

 }

Sunday 23 June 2013

Activity Life Cycle | Android Activity Life Cycle

Hello Droid Guys,

1. If an activity in the foreground of the screen (at the top of the stack), it is active or running.
2. If an activity has lost focus but is still visible (that is, a new non-full-sized or transparent
    activity has focus on top of your activity), it is paused. A
    paused activity is completely alive (it maintains all state and member information and
    remains attached to the window manager), but can be killed by the system in extreme
    low memory situations.
3. If an activity is completely obscured by another activity, it is stopped. It still retains all
    state and member information, however, it is no longer visible to
    the user so its window is hidden and it will often be killed by the system when memory
    is needed elsewhere.
4. If an activity is paused or stopped, the system can drop the activity from memory by
    either asking it to finish, or simply killing its process. When it is displayed again to the
    user, it must be completely restarted and restored to its previous state.

android life cycle


1. onCreate() : Called when the activity is first created. This is where you should do all of
    your normal static set up: create views, bind data to lists,etc.  This method also provides
    you with a Bundle containing the activity's previously frozen state, if there was one.
    Always followed by onStart()

 2. onRestart() : Called after your activity has been stopped, prior to it being started again.
     Always followed by onStart()

 3. onStart() : Called when the activity is becoming visible to the user.
                     Followed by onResume() if the activity comes to the foreground, or onStop()
                      if it becomes hidden.                

 4. onResume() :  Called when the activity will start interacting with the user. At this point
                           your activity is at the top of the activity stack, with user input going to it.
     Always followed by onPause().      

 5. onPause() : Called when the system is about to start resuming a previous activity.
     This is typically used to commit unsaved changes to persistent data,stop animations
     and other things that may be consuming CPU, etc. Implementations of this method
     must be very quick because the next activity will not be resumed until this method
     returns.Followed by either onResume() if the activity returns back to the front, or
     onStop() if it becomes invisible to the user.  

 6. onStop() : Called when the activity is no longer visible to the user, because another
     activity has been resumed and is covering this one. This may happen either because a new activity is being started, an existing one is being brought in front of this one, or this one is being destroyed.Followed by either onRestart() if this activity is coming back to interact with the user, or onDestroy() if this activity is going away.

 7. onDestroy() : The final call you receive before your activity is destroyed. This can
     happen either because the activity is finishing (someone called finish() on it, or
     because the system is temporarily destroying this instance of the activity to save space.
    You can distinguish between these two scenarios with the isFinishing() method.  


Monday 27 May 2013

Android Calendar Sync | Android Custom Calendar | Android Calendar event!Android Custom Calendar View

    Hello Friends,

   Have you Searching for Android calender syncing in your android app.Displaying
   all the events, birthday, reminder and meeting In your android app. Today I am sharing my
   another android tutorial for android custom calendar view and listing all the calendar
   event in my own android app. It is a small sample application for syncing of android
   calender events.


android calender
android calender



Calander syncing
android calander syncing




 
 1. CalendarView.java


package com.examples.android.calendar;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.Locale;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class CalendarView extends Activity {

 public GregorianCalendar month, itemmonth;// calendar instances.

 public CalendarAdapter adapter;// adapter instance
 public Handler handler;// for grabbing some event values for showing the dot
       // marker.
 public ArrayList items; // container to store calendar items which
         // needs showing the event marker
 ArrayList event;
 LinearLayout rLayout;
 ArrayList date;
 ArrayList desc;

 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.calendar);
  Locale.setDefault(Locale.US);

  rLayout = (LinearLayout) findViewById(R.id.text);
  month = (GregorianCalendar) GregorianCalendar.getInstance();
  itemmonth = (GregorianCalendar) month.clone();

  items = new ArrayList();

  adapter = new CalendarAdapter(this, month);

  GridView gridview = (GridView) findViewById(R.id.gridview);
  gridview.setAdapter(adapter);

  handler = new Handler();
  handler.post(calendarUpdater);

  TextView title = (TextView) findViewById(R.id.title);
  title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));

  RelativeLayout previous = (RelativeLayout) findViewById(R.id.previous);

  previous.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    setPreviousMonth();
    refreshCalendar();
   }
  });

  RelativeLayout next = (RelativeLayout) findViewById(R.id.next);
  next.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    setNextMonth();
    refreshCalendar();

   }
  });

  gridview.setOnItemClickListener(new OnItemClickListener() {
   public void onItemClick(AdapterView parent, View v,
     int position, long id) {
    // removing the previous view if added
    if (((LinearLayout) rLayout).getChildCount() > 0) {
     ((LinearLayout) rLayout).removeAllViews();
    }
    desc = new ArrayList();
    date = new ArrayList();
    ((CalendarAdapter) parent.getAdapter()).setSelected(v);
    String selectedGridDate = CalendarAdapter.dayString
      .get(position);
    String[] separatedTime = selectedGridDate.split("-");
    String gridvalueString = separatedTime[2].replaceFirst("^0*",
      "");// taking last part of date. ie; 2 from 2012-12-02.
    int gridvalue = Integer.parseInt(gridvalueString);
    // navigate to next or previous month on clicking offdays.
    if ((gridvalue > 10) && (position < 8)) {
     setPreviousMonth();
     refreshCalendar();
    } else if ((gridvalue < 7) && (position > 28)) {
     setNextMonth();
     refreshCalendar();
    }
    ((CalendarAdapter) parent.getAdapter()).setSelected(v);

    for (int i = 0; i < Utility.startDates.size(); i++) {
     if (Utility.startDates.get(i).equals(selectedGridDate)) {
      desc.add(Utility.nameOfEvent.get(i));
     }
    }

    if (desc.size() > 0) {
     for (int i = 0; i < desc.size(); i++) {
      TextView rowTextView = new TextView(CalendarView.this);

      // set some properties of rowTextView or something
      rowTextView.setText("Event:" + desc.get(i));
      rowTextView.setTextColor(Color.BLACK);

      // add the textview to the linearlayout
      rLayout.addView(rowTextView);

     }

    }

    desc = null;

   }

  });
 }

 protected void setNextMonth() {
  if (month.get(GregorianCalendar.MONTH) == month
    .getActualMaximum(GregorianCalendar.MONTH)) {
   month.set((month.get(GregorianCalendar.YEAR) + 1),
     month.getActualMinimum(GregorianCalendar.MONTH), 1);
  } else {
   month.set(GregorianCalendar.MONTH,
     month.get(GregorianCalendar.MONTH) + 1);
  }

 }

 protected void setPreviousMonth() {
  if (month.get(GregorianCalendar.MONTH) == month
    .getActualMinimum(GregorianCalendar.MONTH)) {
   month.set((month.get(GregorianCalendar.YEAR) - 1),
     month.getActualMaximum(GregorianCalendar.MONTH), 1);
  } else {
   month.set(GregorianCalendar.MONTH,
     month.get(GregorianCalendar.MONTH) - 1);
  }

 }

 protected void showToast(String string) {
  Toast.makeText(this, string, Toast.LENGTH_SHORT).show();

 }

 public void refreshCalendar() {
  TextView title = (TextView) findViewById(R.id.title);

  adapter.refreshDays();
  adapter.notifyDataSetChanged();
  handler.post(calendarUpdater); // generate some calendar items

  title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));
 }

 public Runnable calendarUpdater = new Runnable() {

  @Override
  public void run() {
   items.clear();

   // Print dates of the current week
   DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
   String itemvalue;
   event = Utility.readCalendarEvent(CalendarView.this);
   Log.d("=====Event====", event.toString());
   Log.d("=====Date ARRAY====", Utility.startDates.toString());

   for (int i = 0; i < Utility.startDates.size(); i++) {
    itemvalue = df.format(itemmonth.getTime());
    itemmonth.add(GregorianCalendar.DATE, 1);
    items.add(Utility.startDates.get(i).toString());
   }
   adapter.setItems(items);
   adapter.notifyDataSetChanged();
  }
 };
}




2. CalendarAdapter.java
package com.examples.android.calendar;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CalendarAdapter extends BaseAdapter {
 private Context mContext;

 private java.util.Calendar month;
 public GregorianCalendar pmonth; // calendar instance for previous month
 /**
  * calendar instance for previous month for getting complete view
  */
 public GregorianCalendar pmonthmaxset;
 private GregorianCalendar selectedDate;
 int firstDay;
 int maxWeeknumber;
 int maxP;
 int calMaxP;
 int lastWeekDay;
 int leftDays;
 int mnthlength;
 String itemvalue, curentDateString;
 DateFormat df;

 private ArrayList items;
 public static List dayString;
 private View previousView;

 public CalendarAdapter(Context c, GregorianCalendar monthCalendar) {
  CalendarAdapter.dayString = new ArrayList();
  Locale.setDefault(Locale.US);
  month = monthCalendar;
  selectedDate = (GregorianCalendar) monthCalendar.clone();
  mContext = c;
  month.set(GregorianCalendar.DAY_OF_MONTH, 1);
  this.items = new ArrayList();
  df = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
  curentDateString = df.format(selectedDate.getTime());
  refreshDays();
 }

 public void setItems(ArrayList items) {
  for (int i = 0; i != items.size(); i++) {
   if (items.get(i).length() == 1) {
    items.set(i, "0" + items.get(i));
   }
  }
  this.items = items;
 }

 public int getCount() {
  return dayString.size();
 }

 public Object getItem(int position) {
  return dayString.get(position);
 }

 public long getItemId(int position) {
  return 0;
 }

 // create a new view for each item referenced by the Adapter
 public View getView(int position, View convertView, ViewGroup parent) {
  View v = convertView;
  TextView dayView;
  if (convertView == null) { // if it's not recycled, initialize some
         // attributes
   LayoutInflater vi = (LayoutInflater) mContext
     .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   v = vi.inflate(R.layout.calendar_item, null);

  }
  dayView = (TextView) v.findViewById(R.id.date);
  // separates daystring into parts.
  String[] separatedTime = dayString.get(position).split("-");
  // taking last part of date. ie; 2 from 2012-12-02
  String gridvalue = separatedTime[2].replaceFirst("^0*", "");
  // checking whether the day is in current month or not.
  if ((Integer.parseInt(gridvalue) > 1) && (position < firstDay)) {
   // setting offdays to white color.
   dayView.setTextColor(Color.WHITE);
   dayView.setClickable(false);
   dayView.setFocusable(false);
  } else if ((Integer.parseInt(gridvalue) < 7) && (position > 28)) {
   dayView.setTextColor(Color.WHITE);
   dayView.setClickable(false);
   dayView.setFocusable(false);
  } else {
   // setting curent month's days in blue color.
   dayView.setTextColor(Color.BLUE);
  }

  if (dayString.get(position).equals(curentDateString)) {
   setSelected(v);
   previousView = v;
  } else {
   v.setBackgroundResource(R.drawable.list_item_background);
  }
  dayView.setText(gridvalue);

  // create date string for comparison
  String date = dayString.get(position);

  if (date.length() == 1) {
   date = "0" + date;
  }
  String monthStr = "" + (month.get(GregorianCalendar.MONTH) + 1);
  if (monthStr.length() == 1) {
   monthStr = "0" + monthStr;
  }

  // show icon if date is not empty and it exists in the items array
  ImageView iw = (ImageView) v.findViewById(R.id.date_icon);
  if (date.length() > 0 && items != null && items.contains(date)) {
   iw.setVisibility(View.VISIBLE);
  } else {
   iw.setVisibility(View.INVISIBLE);
  }
  return v;
 }

 public View setSelected(View view) {
  if (previousView != null) {
   previousView.setBackgroundResource(R.drawable.list_item_background);
  }
  previousView = view;
  view.setBackgroundResource(R.drawable.calendar_cel_selectl);
  return view;
 }

 public void refreshDays() {
  // clear items
  items.clear();
  dayString.clear();
  Locale.setDefault(Locale.US);
  pmonth = (GregorianCalendar) month.clone();
  // month start day. ie; sun, mon, etc
  firstDay = month.get(GregorianCalendar.DAY_OF_WEEK);
  // finding number of weeks in current month.
  maxWeeknumber = month.getActualMaximum(GregorianCalendar.WEEK_OF_MONTH);
  // allocating maximum row number for the gridview.
  mnthlength = maxWeeknumber * 7;
  maxP = getMaxP(); // previous month maximum day 31,30....
  calMaxP = maxP - (firstDay - 1);// calendar offday starting 24,25 ...
  /**
   * Calendar instance for getting a complete gridview including the three
   * month's (previous,current,next) dates.
   */
  pmonthmaxset = (GregorianCalendar) pmonth.clone();
  /**
   * setting the start date as previous month's required date.
   */
  pmonthmaxset.set(GregorianCalendar.DAY_OF_MONTH, calMaxP + 1);

  /**
   * filling calendar gridview.
   */
  for (int n = 0; n < mnthlength; n++) {

   itemvalue = df.format(pmonthmaxset.getTime());
   pmonthmaxset.add(GregorianCalendar.DATE, 1);
   dayString.add(itemvalue);

  }
 }

 private int getMaxP() {
  int maxP;
  if (month.get(GregorianCalendar.MONTH) == month
    .getActualMinimum(GregorianCalendar.MONTH)) {
   pmonth.set((month.get(GregorianCalendar.YEAR) - 1),
     month.getActualMaximum(GregorianCalendar.MONTH), 1);
  } else {
   pmonth.set(GregorianCalendar.MONTH,
     month.get(GregorianCalendar.MONTH) - 1);
  }
  maxP = pmonth.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);

  return maxP;
 }

}


3. Utility.java


package com.examples.android.calendar;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

public class Utility {
 public static ArrayList nameOfEvent = new ArrayList();
 public static ArrayList startDates = new ArrayList();
 public static ArrayList endDates = new ArrayList();
 public static ArrayList descriptions = new ArrayList();

 public static ArrayList readCalendarEvent(Context context) {
  Cursor cursor = context.getContentResolver()
    .query(Uri.parse("content://com.android.calendar/events"),
      new String[] { "calendar_id", "title", "description",
        "dtstart", "dtend", "eventLocation" }, null,
      null, null);
  cursor.moveToFirst();
  // fetching calendars name
  String CNames[] = new String[cursor.getCount()];

  // fetching calendars id
  nameOfEvent.clear();
  startDates.clear();
  endDates.clear();
  descriptions.clear();
  for (int i = 0; i < CNames.length; i++) {

   nameOfEvent.add(cursor.getString(1));
   startDates.add(getDate(Long.parseLong(cursor.getString(3))));
   endDates.add(getDate(Long.parseLong(cursor.getString(4))));
   descriptions.add(cursor.getString(2));
   CNames[i] = cursor.getString(1);
   cursor.moveToNext();

  }
  return nameOfEvent;
 }

 public static String getDate(long milliSeconds) {
  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
  Calendar calendar = Calendar.getInstance();
  calendar.setTimeInMillis(milliSeconds);
  return formatter.format(calendar.getTime());
 }
}



   Download the complete Source code 
   Calenderview.zip

   Enjoy coding :)

Sunday 19 May 2013

Linkedin Integration in android | Android Linkedin Api | Post on Linkedin | Android Linkedin Integration Tutorial|LinkedIn Integration in Android App



Hello Friends,

I am going to share the steps of LinkedIn Integration in android.

Steps for LinkedIn Integration :

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


  2. Getting API key(Consumer Key)  and Secret key:
   
linkedin



  3. Add following code in Your app and don't forgot to replace the key
      from the config.java file.
     





1. LinkedInSampleActivity

package com.example.linkedin;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.EnumSet;

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.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.linkedin.R;
import com.google.code.linkedinapi.client.LinkedInApiClient;
import com.google.code.linkedinapi.client.LinkedInApiClientFactory;
import com.google.code.linkedinapi.client.enumeration.ProfileField;
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.mukesh.linkedin.LinkedinDialog.OnVerifyListener;
import com.squareup.picasso.Picasso;

/**
 * @author Mukesh Kumar Yadav
 */
public class LinkedInSampleActivity extends Activity {
 Button login;
 Button share;
 EditText et;
 TextView name,profile;
 ImageView photo;
 public static final String OAUTH_CALLBACK_HOST = "litestcalback";

 final LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory
            .getInstance().createLinkedInOAuthService(
                    Config.LINKEDIN_CONSUMER_KEY,Config.LINKEDIN_CONSUMER_SECRET);
 final LinkedInApiClientFactory factory = LinkedInApiClientFactory
   .newInstance(Config.LINKEDIN_CONSUMER_KEY,
     Config.LINKEDIN_CONSUMER_SECRET);
 LinkedInRequestToken liToken;
 LinkedInApiClient client;
 LinkedInAccessToken accessToken = null;

 @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);
  profile = (TextView) findViewById(R.id.profile);
  et = (EditText) findViewById(R.id.et_share);
  login = (Button) findViewById(R.id.login);
  photo = (ImageView) findViewById(R.id.photo);

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

  // share on linkedin
  share.setOnClickListener(new OnClickListener() {

   public void onClick(View v) {
    String share = et.getText().toString();
    if (null != share && !share.equalsIgnoreCase("")) {
     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>"+ share +"</comment><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();
     }
    }else {
     Toast.makeText(LinkedInSampleActivity.this,
       "Please enter the text to share",
       Toast.LENGTH_SHORT).show();
    }
    
    /*String share = et.getText().toString();
    if (null != share && !share.equalsIgnoreCase("")) {
     client = factory.createLinkedInApiClient(accessToken);
     client.postNetworkUpdate(share);
     et.setText("");
     Toast.makeText(LinkedInSampleActivity.this,
       "Shared sucessfully", Toast.LENGTH_SHORT).show();
    } else {
     Toast.makeText(LinkedInSampleActivity.this,
       "Please enter the text to share",
       Toast.LENGTH_SHORT).show();
    }*/
   }
  });
 }

 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() {
   @SuppressLint("NewApi")
   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);
     // client.postNetworkUpdate("Testing by Mukesh!!! LinkedIn wall post from Android app");
     Log.i("LinkedinSample",
       "ln_access_token: " + accessToken.getToken());
     Log.i("LinkedinSample",
       "ln_access_token: " + accessToken.getTokenSecret());
     //Person p = client.getProfileForCurrentUser();
     Person p =  client.getProfileForCurrentUser(EnumSet.of(
       ProfileField.ID, ProfileField.FIRST_NAME,
       ProfileField.PHONE_NUMBERS, ProfileField.LAST_NAME,
       ProfileField.HEADLINE, ProfileField.INDUSTRY,
       ProfileField.PICTURE_URL, ProfileField.DATE_OF_BIRTH,
       ProfileField.LOCATION_NAME, ProfileField.MAIN_ADDRESS,
        ProfileField.LOCATION_COUNTRY));
     Log.e("create access token secret", client.getAccessToken()
       .getTokenSecret());

     if(p!=null) {
      name.setText("Welcome " + p.getFirstName() + " "
        + p.getLastName());
      name.setVisibility(0);
      profile.setText("Profile:"+p.getHeadline());
      profile.setVisibility(0);
      String id = p.getId();
      String url = p.getPictureUrl();
      if(url != null && !url.isEmpty()) {
       Picasso.with(LinkedInSampleActivity.this).load(url).into(photo);
       photo.setVisibility(0);
      }
      login.setVisibility(4);
      share.setVisibility(0);
      et.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();
 }
}

2.LinkedinDialog:
package com.example.linkedin;

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.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;

/**
 * Linkedin dialog
 * 
 * @author Mukesh Kumar Yadav
 */
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.
  */
 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();
    }

   }
  });

 }

 /**
  * webview client for internal url loading
  */
 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.linkedin.com/uas/oauth/mukeshyadav4u.blogspot.in")) {
    cancel();
   } else {
    Log.i("LinkedinSample", "url: " + url);
    view.loadUrl(url);
   }

   return true;
  }
 }

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

 /**
  * 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);
 }
}
3: Config.java
package com.example.linkedin;

public class Config {

 public static String LINKEDIN_CONSUMER_KEY = "your consumer key here";
 public static String LINKEDIN_CONSUMER_SECRET = "your consumer secret here
";


public static String scopeParams = "rw_nus+r_basicprofile";
 
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;
}

4. main.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/blue_bg_rect"
    android:orientation="vertical" >
    <RelativeLayout
        android:id="@+id/header"
       
android:layout_width="fill_parent"
       
  android:layout_height="wrap_content"
       
  android:background="@drawable/blue_gradient_header"
        android:orientation="horizontal"
  >
        <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>
    <TextView
        android:id="@+id/name"
       
 android:layout_width="wrap_content"
       
  android:layout_height="wrap_content"
       
  android:layout_below="@+id/header"
        android:padding="15dp"
        android:text="Name"
       
  android:textColor="@android:color/white"
        android:textSize="16sp"
        android:textStyle="bold"
        android:visibility="invisible"
 />
    <Button
        android:id="@+id/share"
       
  android:layout_width="wrap_content"
       
  android:layout_height="wrap_content"
       
  android:layout_alignParentRight="true"
       
  android:layout_below="@+id/et_share"
        android:layout_marginTop="22dp"
       
  android:background="@drawable/linkedin_share"
        android:visibility="invisible"
  />
    <Button
        android:id="@+id/login"
       
  android:layout_width="wrap_content"

       
  android:layout_height="wrap_content"

       
  android:layout_centerHorizontal="true"
       
  android:layout_centerInParent="true"
       
  android:layout_centerVertical="true"
       
  android:background="@drawable/btn_active_pressed"
       
  android:gravity="center_vertical|center_horizontal"
        android:padding="8dp"
        android:text="Login"
       
  android:textColor="@android:color/white"
        android:textStyle="bold" />
    <ImageView
        android:id="@+id/photo"
        android:layout_width="72dp"
        android:layout_height="72dp"
       
  android:layout_alignRight="@+id/et_share"
       
  android:layout_alignTop="@+id/name"

        android:layout_marginTop="22dp"

       
  android:background="@drawable/photo"

        android:padding="5dp"

        android:visibility="invisible"
  />



    <EditText
        android:id="@+id/et_share"
       
 android:layout_width="match_parent"
        android:layout_height="100dp"
       
  android:layout_alignBottom="@+id/login"
       
  android:layout_alignParentRight="true"
        android:ems="10"
       
  android:gravity="top|center_vertical"
        android:hint="Enter Your Text to
  Share"
        android:visibility="invisible"
  >

        <requestFocus />
    </EditText>
</RelativeLayout>

finally the AndroidManifest.xml file:

5. AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<manifest
  xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.linkedin"

    android:versionCode="1"

    android:versionName="1.0" >



    <uses-sdk

        android:minSdkVersion="8"

        android:targetSdkVersion="16"
  />



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

    <application

        android:allowBackup="true"

       
  android:icon="@drawable/ic_launcher"

       
  android:label="@string/app_name"

        android:theme="@style/AppTheme"
  >

        <activity

           
  android:name="com.example.linkedin.LinkedInSampleActivity"

           
  android:label="@string/app_name" >

           
  <intent-filter>

               
  <action android:name="android.intent.action.MAIN" />



               
  <category android:name="android.intent.category.LAUNCHER"
  />

           
  </intent-filter>

        </activity>

    </application>



</manifest>

NoteWhile Sending or Posting message on LinkedIn , Or shairing message on
           LinkedIn you found following error to:      


I am obtaining the following error when using the resource client.sendMessage():

com.google.code.linkedinapi.client.LinkedInApiClientException: Throttle limit for calls to this resource is reached.
com.google.code.linkedinapi.client.impl.BaseLinkedInApiClient.createLinkedInApiClientException(BaseLinkedInApiClient.java:3906)
com.google.code.linkedinapi.client.impl.BaseLinkedInApiClient.callApiMethod(BaseLinkedInApiClient.java:3846)
com.google.code.linkedinapi.client.impl.BaseLinkedInApiClient.sendMessage(BaseLinkedInApiClient.java:1829)
org.apache.jsp.linkedin_005fEmail_jsp._jspService(linkedin_005fEmail_jsp.java:149)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:337)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)

This is because on LinkedIn there is a few limits, the number of message you can
share on linkedIn. Check below two links for more knowledge:

1. http://developer.linkedin.com/forum/what-throttle-limit-calls-clientsendmessage
2http://developer.linkedin.com/documents/throttle-limits---see the per day limit

Few Other links
1. http://developer.linkedin.com/documents/libraries-and-tools
2. https://code.google.com/p/linkedin-j/downloads/list



Download the Complete Source Code : LinkedInDemo

Hope this post Helps you.
Enjoy Coding :)


 

Copyright @ 2013 Android Developers Blog.