Sony Arouje

a programmer's log

Posts Tagged ‘Android

Create Facebook Hash Key for Android apps

with 41 comments

Currently doing a small Facebook client for Android. There are several steps we need to do to get the integration working properly. Here I just give a brief of how to create Hash key to update in Facebook. I did a lot of research to get things working, so thought of writing a post that give the details in one place.

Steps to create Hash Key.

  1. Download openssl from Openssl for Windows . I downloaded the Win32 version
  2. Unzip and copy all the files in the bin folder including openssl.exe
  3. Goto to the folder where you installed JDK for me it’s C:\Program Files\Java\jdk1.6.0_21\bin
  4. Paste all the files you copied from Openssl’s bin folder to the Jdk folder.

Now it’s time to run the command to generate the HashKey. You can find more details of Facebook sdk here

keytool -exportcert -alias androiddebugkey  -keystore [Key_store_path] | openssl sha1 -binary | openssl enc -a -e


Above command needs the path to your debug keystore. You can find the Keystore path using Eclipse. Goto Window->Preference->Android->Build will open up a window as shown below.


You can find the Default debug keystore. Copy the path and update in our command, now the command will be like

keytool -exportcert -alias androiddebugkey  -keystore C:\Users\sarouje\.android\debug.keystore | openssl sha1 -binary | openssl enc -a -e

Fire a command prompt and paste the command and run it. Tool will generate a key for you.

Edit: I was not successful in generating right Key Hash using command prompt or cygWin. My search leads to this post explains how to generate right key for the app. Author also provided the Eclipse project contains the source.

Update Hash Key in Facebook

Goto to your Facebook app page and click Edit settings of your app. Click on the Mobile Native section, page will expand and show the section as shown below


Update the HashKey in the Android Key Hash Textbox and click save changes. We are done, go ahead and run your app and it will work fine. No more Invalid key exception


Edit (Jun-24-2014): Nezzar Waleed notified me about one easy solution he found out in stackoverflow, please check it out as well.

Written by Sony Arouje

September 18, 2011 at 3:42 am

Persist domain models in Android using ORMLite

with 9 comments

Recent days I am spending my spare time writing a small app for Android. As usual I have to deal with persistence. I really don’t want to write a persistence mechanism for myself. I started searching for an ORM in Android world. After some evaluation I decided to use ORMLite. It did a pretty good job of mapping my models to db. ORMLite use annotation based configuration, I will go into details later in this post. ORMLite will support entity relationship, lazy loading, etc. Another big advantage is, it’s an open source. Downside is it’s file size, above 200kb (great powers comes with some file size). I felt very comfortable with ORMLite and  decided to use it in my app.

I modified the ContactList test application to see how ORMLite works. Let’s go through in detail.

  1. Download ormlite-android-4.24.jar and ormlite-core-4.24.jar from sourceforge.
  2. Refer the jar files in ContactList project.

Note for non java devs. In Eclipse to refer a jar file, In navigator window right click on the project and select properties. Select Java Build Path from the list and click on Libraries tab. Click on ‘Add External JARs’ button and point to the required jar files.

Next we need to annotate the Contact entity to specify the mapping. Let’s see the Contact entity.

package com.contactlist;

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
public class Contact {
    Contact(){//used by ORMLite}
    public Contact(String id, String displayName)
    private String _id;
    private String _displayName;
    public String getId(){return _id;}
    public String getDisplayName(){return _displayName;}

As you can see the Contact class is annotated with DatabaseTable and specified the table to map. Also the private field is annotated with DatabaseField to map, columnName is optional. If not mentioned then ORMLite will use the variable name as the table column name. Another advantage is, ORMLite works on private variable, so we can make our class immutable.

You can see the basics of using ORMLite in Android here. As per the guideline we need to create a dbHelper extends from OrmLiteSqliteOpenHelper. Let’s see the db helper of ContactList app.

package com.contactlist.repository;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.contactlist.*;
import com.j256.ormlite.table.TableUtils;

public class DBHelper extends OrmLiteSqliteOpenHelper  {

    private static DBHelper _helperInstance;
    public static DBHelper getInstance(Context context)
            _helperInstance=new DBHelper(context);
        return _helperInstance;
    public DBHelper(Context context) 
        super(context, AppConstants.DATABASE_NAME, null, AppConstants.DATABASE_VERSION);
    public void onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource)
            TableUtils.createTable(connectionSource, Contact.class);
        catch (Exception e) {
            Log.e(AppConstants.LOG_NAME, "could not create table Contact",e);
    public void  onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion)

    public void close()

When we implement dbHelper we need to override onCreate and onUpgrade as shown below. onCreate will get called when the app is installed for the first time. onUpgrade will get called when and upgrade to the app, so that we can add scripts for creating new tables, etc. In the above code in onCreate I created the table called contact using one of the class provided by ORMLite.

I done with all the infrastructure stuff. It’s the time to create our repository class to persist our Contacts to a Sqlite db.

package com.contactlist.repository;

import java.sql.SQLException;
import java.util.List;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;
import com.contactlist.*;
import com.j256.ormlite.dao.Dao;

 * @author sony arouje
public class ContactRepository {
    private ContentResolver _contentResolver;

    private Context _context;
    public ContactRepository(ContentResolver contentResolver, Context context) {
        this._contentResolver = contentResolver;

    public List<Contact> getContacts() {
        ContactList contactList = new ContactList();
        Uri uri = ContactsContract.Contacts.CONTENT_URI;
        String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
                + " COLLATE LOCALIZED ASC";
        Cursor cur = _contentResolver.query(uri, null, null, null, sortOrder);
        if (cur.getCount() > 0) {
            String id;
            String name;
            while (cur.moveToNext()) {
                id = cur.getString(cur
                name = cur
                Contact c = new Contact(id,name);
        return contactList.getContacts();

    public void saveContacts(List<Contact> contacts) throws SQLException
        OrmLiteSqliteOpenHelper dbHelper= DBHelper.getInstance(_context);
        Dao<Contact, Integer> daoContact=dbHelper.getDao(Contact.class);
        for (Contact contact : contacts) {

In the above code I persist the Contacts using saveContacts(). I don’t think it really need any explanation, it’s a pretty simple function.

For testing I called the save function ContactListActivity as shown below

_contactRepo=new ContactRepository(getContentResolver(),getApplicationContext());
List<Contact> contactList=_contactRepo.getContacts();

try {
} catch (SQLException e) {


If you want to verify your db, you can do it very easily through eclipse. You can find a detailed step by step description here to view the db created in the emulator. I use SQLiteSpy to browse the SQlite db.

Download source here (

Written by Sony Arouje

August 3, 2011 at 2:52 pm

Posted in Android

Tagged with , , , ,

List Contacts–My first Android app

with 21 comments

Last couple of days I am trying to get a hang on Android development. My first task is to setup the dev environment, I started with Intellij IDEA. Google considered Eclipse as their dev platform for Android. So I moved to Eclipse. Initially Android world is bit challenging as I am from .NET world. When I start working in Android, I feel comfortable. If you develop in Silverlight/WPF using MVVM then it’s not a big deal to create View and Activities in Android. I gone through one of the free ebook available for Android, now it’s time to practice what I learned.

Let’s go through my first app. Listing of contacts, obviously it’s a simple one. Below is my requirement.

  • List all the contact’s Display name
  • Click event on the list should also give ID of the contact not just name. So can able to load details of the contact by querying with ID.
  • Each contact should display with a graphics or an arrow or something. This will help me to learn binding view to ListView.

Output in emulator



Code walkthrough

I think it’s better start with the main activity and move forward. In this simple app I have only one activity called Oh forgot to tell you, activity is just like the viewmodels in MVVM (Silverlight/WPF). Activity handles all the UI related stuffs. Let’s see how the ContactListActivity looks


     1:  public class ContactListActivity extends ListActivity {

   2:      /** Called when the activity is first created. */
   3:      @Override
   4:      public void onCreate(Bundle savedInstanceState) {
   5:          super.onCreate(savedInstanceState);
   6:          ContactList contactList=this.getContacts();
   7:          ArrayAdapter<Contact> adapter=new ContactAdapter(this,contactList.getContacts());
   8:          setListAdapter(adapter);
   9:      }
  11:      @Override
  12:      protected void onListItemClick(ListView l, View v, int position, long id)
  13:      {
  14:          super.onListItemClick(l, v, position, id);
  15:          Object o=this.getListAdapter().getItem(position);
  16:          Contact c=(Contact)o;
  17:          Toast.makeText(this, c.getDisplayName(), Toast.LENGTH_SHORT).show();
  18:      }
  20:      private ContactList getContacts()
  21:      {
  22:          ContactList contactList=new ContactList();
  23:          Uri uri=ContactsContract.Contacts.CONTENT_URI;
  24:          ContentResolver cr=getContentResolver();
  25:          String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
  26:          Cursor cur=cr.query(uri, null, null, null, sortOrder);
  27:          if(cur.getCount()>0)
  28:          {
  29:              String id;
  30:              String name;
  31:              while(cur.moveToNext())
  32:              {
  33:                  Contact c =new Contact();
  34:                  id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
  35:                  name=cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
  36:                  c.setId(id);
  37:                  c.setDisplayName(name);
  38:                  contactList.addContact(c);
  39:              }
  40:          }
  41:          cur.close();
  42:          return contactList;
  43:      }
  44:  }

I don’t have any complex View for this activity so no xml file to link here. Normally an activity will have view that has textbox, button etc. It’s a good practice to define the layout (view) in xml file and Link to Activity. I will explain that later.

The above activity just list down all the contacts, so I inherited from ListActivity. As you can see I override onCreate method. This method will execute when activity get created. First thing I did in onCreate is get a list of contacts. Ignore where I created getContacts(), anyway it’s a test project so leave it.

In getContacts() you can see ContactList and Contact those two are domain class. Rest of the things are easy to understand if you have some knowledge in Android. If you are new to Android world better go through the book I mentioned at the begning of this post. getContacts() return ContactList object contains list of Contacts.

Next step is to bind the Contacts to ListView. Android uses Adapters to bind any kind of list to items control. Here in this case I am not just binding a string array, I am going to bind a view. So I created new Adapter extends from ArrayAdapter called ContactAdapter.


   1:  public class ContactAdapter extends ArrayAdapter<Contact> {
   3:      private final List<Contact> _contacts;
   4:      private final Activity _context;
   6:      public ContactAdapter(Activity context, List<Contact> contacts)
   7:      {
   8:          super(context,R.layout.contactlistitem,contacts);
   9:          this._contacts=contacts;
  10:          this._context=context;
  11:      }
  12:      static class ViewHolder {
  13:          protected TextView text;
  14:          private Contact  _contact;
  15:          protected void setContact(Contact contact)
  16:          {
  17:              text.setText(contact.getDisplayName());
  18:              _contact=contact;
  19:          }
  20:          protected Contact getContact() {return _contact;}
  21:      }
  22:      @Override
  23:      public Contact getItem(int position)
  24:      {
  25:          return _contacts.get(position);
  26:      }
  27:      @Override
  28:      public View getView(int position, View convertView, ViewGroup parent)
  29:      {
  30:          View view=null;
  31:          if(convertView==null)
  32:          {
  33:              LayoutInflater inflater=_context.getLayoutInflater();
  34:              view=inflater.inflate(R.layout.contactlistitem, null);
  35:              final ViewHolder viewHolder=new ViewHolder();
  36:              viewHolder.text=(TextView)view.findViewById(;
  37:              viewHolder.setContact(_contacts.get(position));
  38:              view.setTag(viewHolder);
  39:          }
  41:          return view;
  42:      }
  43:  }


As you can see in Line#8, I mentioned the View. So this adapter uses the specified view and bind it to ListView. You can find more about LayoutInflater here.

contactlistitem is an xml file and I defined in Layout folder.

<?xml version="1.0" encoding="utf-8"?>
  android:layout_height="match_parent" android:orientation="horizontal" android:weightSum="1">
    <TextView android:textAppearance="?android:attr/textAppearanceMedium" 
    <TextView android:textAppearance="?android:attr/textAppearanceLarge" 

R.* is an auto generated file contains the index to different stuffs in the project like Layout, controld identifier, etc.

Note: To create contacts in emulator you need to specify Virtual SD Card size say 200 Mib while creating the AVD through Android SDK and AVD Manager.

Download Source Code (

Written by Sony Arouje

July 29, 2011 at 4:02 pm

Posted in Android

Tagged with ,

%d bloggers like this: