Sunday, March 31, 2013

Android Common Utilities

Hi guys,

In android projects there are many programs/commands we use frequently. Most of the time we implement these programs from scratch or take these program files from existing projects and refactor to adapt into new projects, This process take time. So I decide to put these programs together as much I can. So that developers can use them and reduce their development time. These days I am looking at every possibility to decrease the development time. This is one of my steps.

Pre-req: You should know how to create android project. Then download AndroidCommonUtils.jar jar and put into your project.

In this package we have these classes

    1. ActivityDTO
            Use Map (data structure) in this class, To pass data from activities to other components, Because I have seen under the development cycle, Most of the time we need to refactor functions and need to add or remove parameters, and some time functions took large number of parameters. So adding removing function parameters takes time. So this is my suggestion you can do following thing.
                ActivityDTO activityDTO = new ActivityDTO();
       activityDTO.getMap().put("activity", this);
       activityDTO.getMap().put("progressBarThread", progressBarThread);
       activityDTO.getMap().put("appDebuger",appDebuger);
       activityDTO.getMap().put("userConfigDb",userConfigDb);
     
LoginTask loginTask = new LoginTask(activityDTO);
loginTask.execute(userDTO);
Above example demonstrates how I am  sending different objects into  LoginTask constructor.And inside constructor I can get back these objects.

public LoginTask(ActivityDTO activityDTO) {
activity = (LoginActivity)activityDTO.getMap().get("activity");
progressBarThread =(ProgressThreadUtils)activityDTO.getMap().get("progressBarThread");
appDebuger = (AppDebuger)activityDTO.getMap().get("appDebuger");
userConfigDb = (UserConfigDb)activityDTO.getMap().get("userConfigDb");
}

     2.  AppDebuger
         This utility has methods to print logs on screen for purpose of debugung. I am using Singleton Pattern, Developer can on/off debuging from any where.
          AppDebuger appDebuger = AppDebuger.init();
          appDebuger.setOn(true);
          appDebuger.printInfo("Printhing from blog" , "1234");

    3. CommonMessagesUtils 
        This class has methods to show Toast messages and Dialog Messages.

    4. CommonValidationsUtils
        This class has methods to validate email, strings, password, convert stream into string, check strings are alpha numeric, decimal adjustment. ect

     5. DAOTemplate
           This class has method to insert, delete, remove, update, open close db connections almost every method that will help you to play with you database.
To use do like this
    
    6.  PrivateSharedPrefeqencesForStringsUtils
        This class has methods to save,remove and get presistant strings from android SharedPrefeqences.

    7.  ProgressThreadUtils
         This is a thread utility to manage progress dialog on you activities, State of thread is mentioned in ProgressThreadState enum. Inside your activity use this thread like this


    8.   SDCardUtils

        This class has all methods to save, retrieve files from sd card, you can download resources from internet into sd card and retrieve these as file or bitmap


Download source.


Friday, March 15, 2013

Use HTTPS connection in android app

Note : For this tutorial I am using Ubuntu platform 


1) If you are working on android application with client - server model. And services expose by servers are on SSL connection (i.e https://myserver/login?email=&password) then you need settings in your android applications.


1) Download the certificate. for demonstration I am using a link (i.e https://www.google.com) and chrome browser.
  a) Open chrome and this link : https://www.google.com
  b) Press Lock icon on you url bar and then select Connection tab
  c) Then select Certificate information
  d) You will see a pop up. Select details tab and Select top of Hierarchy under  Certificate Hierarchy section.
   e) press export button and save certificate in you directory.


f)  Certificate will be like :
-----BEGIN CERTIFICATE-----
MIIDIDCCAomg..........................................
-----END CERTIFICATE-----

2) Download  BouncyCastle Provider and put it will you SSL certificate file.
3) Open terminal and open your Oracle JDK bin folder
    cd /usr/lib/jvm/java-7-oracle/bin

4) use blow command to create a keystore file mykeystore.bks with

 password mysecret

keytool -importcert -v -trustcacerts -file "/path/Builtin Object Token:Equifax Secure CA" -alias IntermediateCA -keystore "/path/mykeystore.bks" -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath "/path/bcprov-jdk16-145.jar" -storetype BKS -storepass mysecret
5) To verify mykeystore.bks use below command on same terminal
keytool -list -keystore "/path/mykeystore.bks" -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath "/path/bcprov-jdk16-145.jar" -storetype BKS -storepass mysecret

you will get result like
Keystore type: BKS
Keystore provider: BC

Your keystore contains 1 entry

IntermediateCA, Mar 14, 2013, trustedCertEntry,
Certificate fingerprint (SHA1): D2:32:09:AD:23:D3:14:23:21:74:E4:0D:7F:9D:62:13:97:86:63:3A
 6) Now put mykeystore.bks in to your android project/res/raw/mykeystore.bks


7) Now use  mykeystore.bks into get response input stream from your request.
    you can get code here 

private static InputStream getHttpInputStream(String urlAddress,Context ctx)  throws KeyManagementException, NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException, UnrecoverableKeyException{
        TrustManagerFactory tmf;
       
        KeyStore trustedStore = loadClientKeyStore(ctx);
        tmf = TrustManagerFactory.getInstance("X509");
        tmf.init(trustedStore);

        SSLContext ssl_context = SSLContext.getInstance("TLS");
        ssl_context.init(null, tmf.getTrustManagers(), null);
       
       
        HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER;
       
        URL u = new URL(urlAddress);
        HttpsURLConnection urlConnection = (HttpsURLConnection) u.openConnection();
        urlConnection.setSSLSocketFactory(ssl_context.getSocketFactory());
        urlConnection.setHostnameVerifier(hostnameVerifier);
        urlConnection.connect();
       
        return (InputStream)urlConnection.getInputStream(); 
    }

    private static KeyStore loadClientKeyStore(Context context) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
            InputStream in =  context.getResources().openRawResource(R.raw.mykeystore);
            KeyStore trusted = null;
            trusted = KeyStore.getInstance("BKS");
            trusted.load(in, "mysecret".toCharArray());
            in.close();
            return trusted;
    }





Wednesday, March 13, 2013

Eclipse & maven setup for android development

I am using ubuntu. So developers of windows or mac should Google respective  softwares for their platforms.


1) Download latest an Eclipse.(I prefer Helios)
2) Download Android sdk.
3) Install ADT plugin in your eclipse follow this link.

4) Install maven using terminal
  • wget http://mirror.olnevhost.net/pub/apache/maven/binaries/apache-maven-3.0.4-bin.tar.gz
  • Run command above from the dir you want to extract maven to (e.g. /usr/local/apache-maven)
  • tar xvf apache-maven-3.0.4-bin.tar.gz
  • Export maven path:
    export M2_HOME=/usr/local/apache-maven/apache-maven-3.0.4
    export M2=$M2_HOME/bin
    export PATH=$M2:$PATH
  • Verify
    mvn -version
   
 5) Install M2e plugin (maven integration for eclipse)



 5.1) Go Window -> preferences > choose Maven from left menu -> Installations
       -> Add the path of installed folder form maven (you did in step 4)

5.2) Now in same menu select User settings and then browse path of maven you installed in step 4 and select cofig/settings.xml (i.e /usr/share/maven/conf/settings.xml)

6) Install Android configrator for m2e (From eclipse market place)
(Open help -> eclipse marketplace.. -> search for this plugin)




7) Select window -> Preferences -> Archetypes --> Add local catelog
   and add this  file  from your machine



Thats all you configuration for maven and eclipse of complete