Singleton Design Pattern

Singleton design pattern shall be the first pattern a java programmer learned.If somebody ask me about design pattern the first pattern comes to my mind is the singleton.Its a very simple design pattern ryt !.

The singleton design pattern is meant to have a single instance of a class through out our application.

Do you think that you know it very well !.

If so, more surprise are waiting for you.please read a head.

Let me demonstrate you a sample singleton class Calculator, which do have an addition method.

public class Calculator {
private static Calculator calculator = null;
private Calculator() {
}
public static Calculator getInstance() {
if (calculator == null) {
 calculator = new Calculator();
 }
return calculator;
 }
public int add(int a, int b) {
return a + b;
}
}

you can create the instance of Calculator like

Calculator calculator = Calculator.getInstance();

We made the constructor private so it can't be initiated from outside and did a lazy initialization.Once Calculator.getInstance() invoked its object will be created.So no more object can be created their after.That what we need right.

What will happen when multiple threads call Calculator.getInstance() at the same time ? Think.

.

.

.

Got it ! Yes as you think multiple instance will be created even though we have a null check over their.
It will break the singleton concept.So what to do.

Lets make the getInstance() method synchronized.

Synchronization can be of :

  1. Method level
  2. Block level.

Method level can be as follows:

public static synchronized  Calculator getInstance() {
if (calculator == null) {
calculator = new Calculator();
}
return calculator;
}

Block level can be as follows:

public static Calculator getInstance() {
synchronized (Calculator.class) {
if (calculator == null) {
calculator = new Calculator();
}
return calculator;
}
}

Both don't have any performance difference. But i prefer method level because its more readable.

Ok.Now threads cant break our singleton concept.

Let think of scenario where we clone our singleton class.

Clone means we can get a copy of the class.

It can be of

  1. Shallow copy
  1. Deep copy.

For cloning just implement the marker interface Cloneable.Marker interface means it don't have any abstract methods.Its presence  only need for JVM to do the job for us.

So cloning too break our singleton concept ryt.

what will we do.The solution is just override the clone method like :

@Override
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}

ya that's it we did the job .Now nobody can break our singleton concept.Are you sure..Think !

.

.

.

OK.What will happen if some class extends our Calculator class.In order to avoid further complication make our Calculator class final.So no class can subclass it.

The below program shows the final Implementation of our Calculator class

public final class Calculator {

private static Calculator calculator = null;

private Calculator() {
}

public static Calculator getInstance() {
synchronized (Calculator.class) {
if (calculator == null) {
calculator = new Calculator();
}
return calculator;
}
}

public int add(int a, int b) {
return a + b;
}

@Override
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}

Thread Safe EntityManager in A Web Application

You must be familiar with JPA concepts before going through this post.

JPA(Java Persistance API) is a tool for ORM(Object Relational Mapping).Its a way for persisting Java Object To Relational database.

Their are different implementaion for JPA

1.Hibernate

2.Top Link

3.EclipseLink

Hibernate is the mostly used JPA Implementaion.

JPA is bound on Four aspects:

EntityManagementFactory(EMF)

EntityManager(EM)

EntityTransaction(ET)

Entity

EM Represents a connection towards a Database.Its responsible for CRUD(Create Read Update Delete) operations.

EMF is responsible for instantiating EM.It is constructed for a specific Database.Their should be only one EMF for an application.Creating a EMF is a costly operation.So if created, please reuse it .Its thread safe.On the other hand EM is not thread safe.Its creation is not costly,so create it when needed and close it after use.

An EMF instance is obtained by using a static factory method of the JPA bootstrap class, Persistance:

EntityManagementFactory entityManagerFactory 
= Persistence.createEntityManagerFactory(Constants.MYSQL_PERSISTNCE_UNIT);

when the application finished using EMF it should be close


entityManagerFactory.close(); 

An EM instance may represent either a remote connection to a remote database server (in client-server mode) or a local connection to a local database file (in embedded mode). The functionality in both cases is the same. Given an EntityManagerFactory emf, a short term connection to the database might have the following form:

EntityManager em = emf.createEntitymanager();
  try {
      // TODO: Use the EntityManager to access the database
  }
  finally {
      em.close();
  }

EntityTransaction

Operations that affect the content of the database (store, update, delete) must be performed within an active transaction. The EntityTransaction  interface represents and manages database transactions. Every Entitymanager  holds a single attached EntityTransaction instance that is available via the getTransaction  method:

try {
      em.getTransaction().begin();
      // Operations that modify the database should come here.
      em.getTransaction().commit();
  }
  finally {
      if (em.getTransaction().isActive())
          em.getTransaction().rollback();
  }

Entity represents a physical object in the database.It actually represents a Table. The following diagram shows Entity Life Cycle: There are couple of ways we can use to make an EntityManager ThreadSafe:

  1. Create an EJB and let the container manage the lifecycle of EntityManager. if we are getting EntityManager like emf.getEntityManager() we are reponsible for manage its lifecycle. Or we can create using @PersistanceContext. PersistnceContext represents collections of Entities an EntityManager Manages. Create an @Local Stateless Ejb and create EM like @PersistanceContext.
  2. Create a servlet and inject the EntitymanagerFactory using @Persistanceunit annotation, and in the service you can manage the EM lifecycle.
  3. Manage EM using ThreadLocal and a request filter.

we are going to focus on the 3rd method.

Using ThreadLocal class we can create EM for each request.We will specify the EMF creating the filter init method and close it in the destroy method. In the doFilter method we will create an EntityManager and Add to ThreadLocal Class So we can get a local EntityManager for every Request.After requset processing we can close EM in the filter it self.

Lets see our project structure:

In persistance.xml we will specify the datasource,Entities etc.

We can enable the cache feature here :

There are two level of cache

  1. L1
  2. L2

L1 is the Entitymanager Persistance Context.

L2 is the EMF context .It can be shared with all Enitymanagers in the application.

Persistance.xml


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

<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence  http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">

<persistence-unit  name="mysqlPersistanceUnit" transaction-type="RESOURCE_LOCAL" >

<provider>org.hibernate.ejb.HibernatePersistence</provider>

<non-jta-data-source>java:/MySQLDS</non-jta-data-source>

<!--

<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>

-->

<class>com.opensourzesupport.middleware.services.ws.model.Product</class>

<properties>

<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />

<property name="hibernate.hbm2ddl.auto"

value="create-drop" />

<property name="hibernate.transaction.factory_class" value="org.hibernate.transaction.JTATransactionFactory"/>

<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.JBossTransactionManagerLookup"/>

<property name="hibernate.show_sql" value="true"/>

<!--

<property name="hibernate.cache.use_second_level_cache" value="true" />

L2 cache

Level 2  (L2) cache of entity objects, which is managed by the EntityManagerFactory

and shared by all its EntityManager objects

NONE - cache is disabled.

ENABLE_SELECTIVE - cache is disabled except for selected entity classes (see below).

DISABLE_SELECTIVE - cache is enabled except for selected entity classes (see below).

ALL (the default) - cache is enabled for all the entity classes.

<property name="javax.persistence.sharedCache.mode" value="ALL"/>

-->

</properties>

</persistence-unit>

</persistence>

Web.xml


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

<web-app id="WebApp_ID" version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<display-name>jpa-rest</display-name>

<listener>

<listener-class>

org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap

</listener-class>

</listener>

<filter>

<filter-name>request-filter</filter-name>

<filter-class>com.opensourzesupport.middleware.services.ws.request.filter.EntityManagerFilter</filter-class>

</filter>

<filter-mapping>

<filter-name>request-filter</filter-name>

<url-pattern>/rest/*</url-pattern>

</filter-mapping>

<servlet>

<servlet-name>resteasy-servlet</servlet-name>

<servlet-class>

org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher

</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>resteasy-servlet</servlet-name>

<url-pattern>/rest/*</url-pattern>

</servlet-mapping>

<context-param>

<param-name>resteasy.servlet.mapping.prefix</param-name>

<param-value>rest</param-value>

</context-param>

<context-param>

<param-name>resteasy.scan</param-name>

<param-value>true</param-value>

</context-param>

</web-app>

jboss-web.xml


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

<jboss-web>

<context-root>/ws</context-root>

</jboss-web>

PersistanceService.java


package com.opensourzesupport.middleware.service.persistance;

import java.util.List;

/**

*

* @author Prasobh.K

*/

public interface PersistanceService {

public void saveObject(Object obj) throws Exception;

public Object getSingleResultSet(String namedQuery);

public List getResultsList(String namedQuery) throws Exception;

public List getpaginatedResultList(String namedQuery, int startIndex, int maxResult) throws Exception;

}

PersistanceServiceImpl.java


package com.opensourzesupport.middleware.service.persistance;

import com.opensourzesupport.middleware.util.EntityManagerUtil;

import java.util.List;

import javax.persistence.EntityManager;

import javax.persistence.Query;

/**

*

* @author Prasobh.K

*/

public class PersistanceServiceImpl implements PersistanceService {

private static PersistanceServiceImpl persistanceService = null;

public static synchronized PersistanceServiceImpl getIntance() {

if (persistanceService == null) {

persistanceService = new PersistanceServiceImpl();

}

return persistanceService;

}

public void saveObject(Object obj) throws Exception {

EntityManager em = EntityManagerUtil.getEntityManager();

try {

em.getTransaction().begin();

em.persist(obj);

em.getTransaction().commit();

} catch (Exception e) {

if (em.getTransaction().isActive()) {

em.getTransaction().rollback();

}

throw e;

}

}

public Object getSingleResultSet(String namedQuery) {

EntityManager em = EntityManagerUtil.getEntityManager();

Query query = null;

try {

query = em.createNamedQuery(namedQuery);

} catch (Exception ex) {

return ex;

}

return query.getSingleResult();

}

public List getResultsList(String namedQuery) throws Exception {

EntityManager em = EntityManagerUtil.getEntityManager();

Query query = null;

try {

query = em.createNamedQuery(namedQuery);

} catch (Exception ex) {

throw ex;

}
return query.getResultList();

}

public List getpaginatedResultList(String namedQuery, int startIndex, int maxResult) throws Exception {

EntityManager em = EntityManagerUtil.getEntityManager();

Query query = null;

try {

query = em.createNamedQuery(namedQuery).setFirstResult(startIndex).setMaxResults(maxResult);

} catch (Exception ex) {

throw ex;

}
return query.getResultList();
}
}

ProductResource.java

package com.opensourzesupport.middleware.service.ws;

import com.opensourzesupport.middleware.services.ws.model.Product;

import java.util.List;

import javax.ws.rs.GET;

import javax.ws.rs.Path;

import javax.ws.rs.PathParam;

import javax.ws.rs.Produces;

import javax.ws.rs.core.MediaType;

/**

*

* @author Prasobh.K

*/

@Path("/services")

public interface ProductResource {

&nbsp;

@GET

@Produces({MediaType.APPLICATION_XML})

@Path("/products/xml")

public Product getXML();

&nbsp;

@GET

@Produces({MediaType.TEXT_PLAIN})

@Path("/product/save/{id}")

public String saveProduct(@PathParam("id") String id);

&nbsp;

@GET

@Produces({MediaType.APPLICATION_JSON})

@Path("/product/get")

public Product getProduct();

@GET

@Produces({MediaType.APPLICATION_JSON})

@Path("/product/get/{startIndex}/{maxResult}")

public List<Product> getPaginatedProduct(@PathParam("startIndex") int startIndex, @PathParam("maxResult") int maxResult);

@GET

@Produces({MediaType.APPLICATION_JSON})

@Path("/products/json")

public List<Product> getJSON();

@GET

@Produces({MediaType.TEXT_HTML})

@Path("/html")

public List<Product> getHTML();

}

ProductResourceService.java


package com.opensourzesupport.middleware.service.ws;

import com.opensourzesupport.middleware.service.persistance.PersistanceService;

import com.opensourzesupport.middleware.service.persistance.PersistanceServiceImpl;

import com.opensourzesupport.middleware.services.ws.model.Product;

import com.opensourzesupport.middleware.util.Constants;

import java.util.ArrayList;

import java.util.Date;

import java.util.List;

import java.util.logging.Level;

import java.util.logging.Logger;

import javax.servlet.ServletContext;

import javax.ws.rs.PathParam;

import javax.ws.rs.WebApplicationException;

import javax.ws.rs.core.Context;

import javax.ws.rs.core.Response;

/**

*

* @author Prasobh.K

*/

public class ProductResourceService implements ProductResource {

private PersistanceService persistanceService;

@Context

ServletContext servletContext;

@Override

public Product getXML() {

Product product = new Product();

product.setName("TestProduct");

product.setDescription("testing Persistance");

return product;

}

@Override

public String saveProduct(@PathParam("id") String id) {

System.out.println("requset got id[" + id + "]");
Product product = new Product();

product.setName(id);

product.setDescription("testing Persistance");

product.setUsedTime(new Date());

String status = "Failed";

try {

System.out.println("Current Thread " + Thread.currentThread());

System.out.println("persistanceService " + persistanceService);

persistanceService = PersistanceServiceImpl.getIntance();

persistanceService.saveObject(product);

status = "Success";

} catch (Exception e) {

System.out.println("Error" + e);

status = e.getMessage();

}

return status;

}

@Override

public Product getProduct() {

List<Product> p = null;

long startTme = System.currentTimeMillis();

try {

p = (List<Product>) PersistanceServiceImpl.getIntance().getResultsList(Constants.GET_PRODUCT);

} catch (Exception e) {

System.out.println("Error" + e);

}

if (p == null) {

throw new WebApplicationException(Response.Status.NOT_FOUND);

}

System.out.println("time took to process " + (System.currentTimeMillis() - startTme));

System.out.println("Size " + p.size());

return p.iterator().next();
}

public List<Product> getPaginatedProduct(@PathParam("startIndex") int startIndex, @PathParam("maxResult") int maxResult) {

List<Product> products = null;

try {

products = PersistanceServiceImpl.getIntance().getpaginatedResultList(Constants.GET_PRODUCT, startIndex, maxResult);

} catch (Exception ex) {

Logger.getLogger(ProductResourceService.class.getName()).log(Level.SEVERE, null, ex);

}

return products;

}
@Override

public List<Product> getJSON() {

return getRoot();

}

@Override

public List<Product> getHTML() {
return getRoot();
}

public List<Product> getRoot() {

List<Product> root = new ArrayList<Product>();

Product product1 = new Product();

product1.setName("IOS");

product1.setDescription("Mobile");

root.add(product1);

Product product2 = new Product();

product2.setName("Android");

product2.setDescription("Mobile");

root.add(product2);

Product product3 = new Product();

product3.setName("BlacBerry");

product3.setDescription("Mobile");

root.add(product3);

Product product4 = new Product();

product4.setName("J2ME");

product4.setDescription("Mobile");

root.add(product4);

return root;

}

}

Product.java


package com.opensourzesupport.middleware.services.ws.model;

import com.opensourzesupport.middleware.util.Constants;

import java.util.Date;

import javax.persistence.*;

import javax.xml.bind.annotation.XmlAccessType;

import javax.xml.bind.annotation.XmlAccessorType;

import javax.xml.bind.annotation.XmlRootElement;

/**

*

* @author Prasobh.K

*/

@XmlRootElement

@Entity

@EntityListeners(ProductListener.class)

@NamedQueries({

@NamedQuery(name = Constants.GET_PRODUCT,

query = "select T from Product T")})

@XmlAccessorType(XmlAccessType.FIELD)

public class Product {

@Column

@Id

private String name;

@Column

private static String description;

@Temporal(TemporalType.DATE)

private Date usedTime;

public String getDescription() {

return description;

}

public void setDescription(String description) {

this.description = description;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public Date getUsedTime() {

return usedTime;

}

public void setUsedTime(Date usedTime) {

this.usedTime = usedTime;

}
}

ProductListener.java


package com.opensourzesupport.middleware.services.ws.model;

import javax.persistence.*;

/**

*

* @author Prasobh.K

*/

public class ProductListener {

@PrePersist

public void prePersist(Object o) {

System.out.println("In PrePersist name[" + ((Product)o).getName() + "]");

}

@PostPersist

public void postPersist(Object o) {

System.out.println("In PostPersist name[" + ((Product)o).getName() + "]");

}

@PreRemove

public void preRemove(Object o) {

System.out.println("In preRemove name[" + ((Product)o).getName() + "]");

}

@PostRemove

public void postRemove(Object o) {

System.out.println("In postRemove name[" + ((Product)o).getName() + "]");

}

@PreUpdate

public void preUpdate(Object o) {

System.out.println("In preUpdate name[" + ((Product)o).getName() + "]");

}

@PostUpdate

public void postUpdate(Object o) {

System.out.println("In postUpdate name[" + ((Product)o).getName() + "]");

}

@PostLoad

public void postLoad(Object o) {

System.out.println("In PostLoad name[" + ((Product)o).getName() + "]");

}

}

EntityManagerFilter.java


package com.opensourzesupport.middleware.services.ws.request.filter;

import com.opensourzesupport.middleware.util.Constants;

import com.opensourzesupport.middleware.util.EntityManagerUtil;

import java.io.IOException;

import javax.persistence.EntityManager;

import javax.persistence.EntityManagerFactory;

import javax.persistence.Persistence;

import javax.servlet.*;

/**

*

* @author Prasobh.K

*/

public class EntityManagerFilter implements Filter {

private static EntityManagerFactory entityManagerFactory = null;

@Override

public void init(FilterConfig fc) throws ServletException {

destroy();

entityManagerFactory = Persistence.createEntityManagerFactory(Constants.COCO_ORACLE_PERSISTNCE_UNIT);

}

@Override

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

EntityManager em = null;

try {

em = entityManagerFactory.createEntityManager();

EntityManagerUtil.ENTITY_MANAGERS.set(em);

chain.doFilter(request, response);

EntityManagerUtil.ENTITY_MANAGERS.remove();

} finally {

try {

if (em != null) {

em.close();

}

} catch (Throwable t) {

System.out.println("Error " + t);

}
}
}

@Override

public void destroy() {

{

if (entityManagerFactory != null) {

entityManagerFactory.close();
}
}
}
}

Constants.java


package com.opensourzesupport.middleware.util;

/**

*

* @author Prasobh.K

*/

public class Constants {

public static final String GET_PRODUCT = "get.product.like";

public static final String COCO_ORACLE_PERSISTNCE_UNIT = "mysqlPersistanceUnit";

}

EntityManagerUtil.java


package com.opensourzesupport.middleware.util;

import javax.persistence.EntityManager;
/**

*

* @author Prasobh.K

*/

public class EntityManagerUtil {

public static final ThreadLocal<EntityManager> ENTITY_MANAGERS = new ThreadLocal<EntityManager>();

/**

* Returns a fresh EntityManager

*/

public static EntityManager getEntityManager() {

return ENTITY_MANAGERS.get();

}

}

Output :

http://localhost:8080/ws/rest/services/product/save/iphone

INFO  [STDOUT] core.SynchronousDispatcher - PathInfo: /services/product/save/iphone

INFO  [STDOUT] requset got id[iphone]

INFO  [STDOUT] Current Thread Thread[http-127.0.0.1-8080-1,5,jboss]

INFO  [STDOUT] In PrePersist name[iphone]

INFO  [STDOUT] Hibernate: insert into Product (usedTime, name) values (?, ?)

INFO  [STDOUT] In PostPersist name[iphone]

http://localhost:8080/ws/rest/services/product/get

&nbsp;

{"name":"iphone","description":"testing Persistance","usedTime":"2012-10-30"}

http://localhost:8080/ws/rest/services/product/get/1/3

<pre>[{"name":"android","description":"testing Persistance","usedTime":"2012-10-30"},{"name":"backbery","description":"testing Persistance","usedTime":"2012-10-30"},{"name":"j2me","description":"testing Persistance","usedTime":"2012-10-30"}]</pre>

Persisting Object to a file

Persist means saving the state.State not only can be saved to file but also too DB,remote locations etc.If we want to persist a custom object, we need that class to implement Serializable .

For persisting an object you class must implement Serializable interface.It is a marker interface,it means it don’t have any abstract method . It’s presence only need for JVM to serialize an Object.

Following example will persist a map object to a file and reads it back.


/**
  *
  * @author prasobh
  */
 import java.io.*;
 import java.util.*;

 public class ExerciseSerializable {

     public static void main(String... aArguments) {
         //  create a Serializable Map
         Map<Integer, String> names = new HashMap<Integer, String>();
         names.put(1, "prasobh");
         names.put(2, "mohanlal");
         names.put(3, "mammokka");

         try {
             //  use buffering
             OutputStream file = new FileOutputStream("names.store");
             OutputStream buffer = new BufferedOutputStream(file);
             ObjectOutput output = new ObjectOutputStream(buffer);
             try {
                 output.writeObject(names);
             } finally {
                 output.close();
             }
         } catch (IOException ex) {
             System.out.println("Exception " + ex);
         }

         // deserialize the quarks.ser file

         try {
             //use buffering
             InputStream file = new FileInputStream("names.store");
             InputStream buffer = new BufferedInputStream(file);
             ObjectInput input = new ObjectInputStream(buffer);
             try {
                 //deserialize the List

                 Map<Integer, String> recoverednames = (Map<Integer, String>) input.readObject();

                 //display its data

                 System.out.println("recoverednames: " + recoverednames);

             } finally {
                 input.close();
             }
         } catch (ClassNotFoundException ex) {
             System.out.println("Exception " + ex);
         } catch (IOException ex) {
             System.out.println("Exception " + ex);
         }
     }
 }

HashMap implements Serializable so we are able to persist the map.

If class is not Serializable JVM will throw :

NotSerializableException

Serializable is not only the way for persistance.We can use another interface Externalizable which extends Serializable.

It have two absctract methods.

1.void writeExternal(ObjectOutput out) throws IOException;

2.void readExternal(ObjectInput in) throws IOException, ClassNotFoundException;

We will get callback during the serialization and de-serialization process.So we have a controll over serialization.

Only state of an object shoul be saved.That means Instance variable data.

If we do not want to save a state of variable it can be marked with transient keyword.If a variable is transient it state will not be persisted.

What if a variable is static ?

static variables have nothing to do with the state.So if a variable is static you should make it as transient.Else the static data will be persistedbut no meaning in it !.

Note : If a variable in an Object is transient and if the Object Persisted and retried back the transient field data will be initialed with default value.

Displaying list with image and text

See following class :


package com.example;

 import android.app.Activity;
 import android.app.AlarmManager;
 import android.app.ListActivity;
 import android.content.Context;
 import android.database.Cursor;
 import android.net.Uri;
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.Message;
 import android.provider.ContactsContract;
 import android.view.LayoutInflater;
 import android.view.Menu;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.ArrayAdapter;
 import android.widget.ImageView;
 import android.widget.ListView;
 import android.widget.TextView;

 import java.util.ArrayList;

 public class ListWithImage extends ListActivity {

 String[] scrips;

 //for running task in background
 Handler handler = new Handler() {
 @Override
 public void handleMessage(Message msg) {
 setListAdapter(new Scripdapter(getApplicationContext(), R.layout.main, scrips));
 }

 };

 /**
 * Called when the activity is first created.
 */
 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 scrips = getResources().getStringArray(R.array.scrip);
 upadateList();

 }

 public void upadateList() {
 Thread t = new Thread(new Runnable() {
 public void run() {
 handler.handleMessage(handler.obtainMessage());
 }
 });
 t.start();
 }

class Scripdapter extends ArrayAdapter {

 private String[] items;

 Scripdapter(Context context, int textViewResourceId, String[] items) {
 super(context, textViewResourceId, items);
 this.items = items;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
 View row = convertView;
 if (row == null) {
 LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 row = vi.inflate(R.layout.main, null);

 }

 String item = items[position];
 if (item != null) {
 TextView txtV = (TextView) row.findViewById(R.id.scripList);
 ImageView imgV = (ImageView) row.findViewById(R.id.scripimage);
 if(txtV != null){
 txtV.setText(item);
 }
 if (item.equals("sbi") || item.equals("unitech")) {
 imgV.setImageResource(R.drawable.red);
 } else if (item.equals("BNP paribas") || item.equals("wipro")) {
 imgV.setImageResource(R.drawable.green);
 } else if (item.equals("dlf") || item.equals("nokia")) {
 imgV.setImageResource(R.drawable.green);
 } else {
 imgV.setImageResource(R.drawable.icon);
 }
 }
 return row;
 }
 }

main.xml

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content">
     <ImageView android:layout_height="wrap_content"
                android:src="@drawable/icon"
                android:layout_width="22px"
                android:layout_marginTop="4px"
                android:layout_marginRight="4px"
                android:layout_marginLeft="4px"
                android:id="@+id/scripimage">
     </ImageView>
     <TextView android:text="@+id/TextView01"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:id="@+id/scripList"
               android:textSize="30px"></TextView>
 </LinearLayout>

string.xml

<resources>
     <string name="app_name">ContactsView</string>
     <string-array name="scrip">
         <item>sbi</item>
         <item>Geojit</item>
         <item>BNP paribas</item>
         <item>dlf</item>
         <item>unitech</item>
         <item>suzlon</item>
         <item>axis bank</item>
         <item>wipro</item>
         <item>infosis</item>
         <item>nokia</item>
     </string-array>
 </resources>

Output :

Staring Android programming using IntelliJIdea

Prerequisite

Install following:-

1. JDK                :  http://www.oracle.com/
2. IntelliJIdea       :http://www.jetbrains.com/idea      (Community Edition)
3 .Android SDK   : http://developer.android.com

Open IntelliJIdea .Select file > New project,the click select project from scratch as shown below :

 

Click ok.

Then type Project name as HellowWorld in Name textbox,then choose Android module from select type.Click Ok

check create source and click next.

Browse android sdk.

Click + button as shown above to browse android sdk .select jdk too.click ok.Then home sceen will show as follows:

Click edit configuration above to select/create andoird virtual device.

Check select device manually or select listed device you previously created.If suggest to use choose manually,so that we can select preferred config device at run time.click ok.Now click run.Then you are supposed to create a device if not created previously.Click launch emulator.Noe create one as follows.

Click ok.Click launch emulator.Noe emulator will launch as follows:

Unlock Virtual phone.Click on green color lock and drag to right will unlock virtual phone.

Now you can see HellowWold Application on screen.Click that icon.

That’s it.Great you did it well.Now you can have a simle, your first android application launched ryt.

Note : Don’t close emulator just do changes in code and click run it will automatically reflect  in emulator.

 

How to Copy Entire directory ?

See following example :


public void copyDirectory(File srcDir, File dstDir) throws IOException {
         if (srcDir.isDirectory()) {
             if (!dstDir.exists()) {
                 dstDir.mkdir();
             }

             String[] children = srcDir.list();
             for (int i = 0; i < children.length; i++) {
                 copyDirectory(new File(srcDir, children[i]),
                         new File(dstDir, children[i]));
             }
         } else {
             // This method is implemented in Copying a File
             copyFiles(srcDir, dstDir);
         }
     }

 public static void copyFiles(File src, File dest) throws IOException {
     //Check to ensure that the source is valid...
     if (!src.exists()) {
         throw new IOException("copyFiles: Can not find source: " + src.getAbsolutePath()+".");
     } else if (!src.canRead()) { //check to ensure we have rights to the source...
         throw new IOException("copyFiles: No right to source: " + src.getAbsolutePath()+".");
     }
     //is this a directory copy?
     if (src.isDirectory())     {
         if (!dest.exists()) { //does the destination already exist?
             //if not we need to make it exist if possible (note this is mkdirs not mkdir)
             if (!dest.mkdirs()) {
                 throw new IOException("copyFiles: Could not create direcotry: " + dest.getAbsolutePath() + ".");
             }
         }
         //get a listing of files...
         String list[] = src.list();
         //copy all the files in the list.
         for (int i = 0; i < list.length; i++)
         {
             File dest1 = new File(dest, list[i]);
             File src1 = new File(src, list[i]);
             copyFiles(src1 , dest1);
         }
     } else {
         //This was not a directory, so lets just copy the file
         FileInputStream fin = null;
         FileOutputStream fout = null;
         byte[] buffer = new byte[4096]; //Buffer 4K at a time (you can change this).
         int bytesRead;
         try {
             //open the files for input and output
             fin =  new FileInputStream(src);
             fout = new FileOutputStream (dest);
             //while bytesRead indicates a successful read, lets write...
             while ((bytesRead = fin.read(buffer)) >= 0) {
                 fout.write(buffer,0,bytesRead);
             }
         } catch (IOException e) { //Error copying file...
             IOException wrapper = new IOException("copyFiles: Unable to copy file: " +
                         src.getAbsolutePath() + "to" + dest.getAbsolutePath()+".");
             wrapper.initCause(e);
             wrapper.setStackTrace(e.getStackTrace());
             throw wrapper;
         } finally { //Ensure that the files are closed (if they were open).
             if (fin != null) { fin.close(); }
             if (fout != null) { fout.close(); }
         }
     }
 }