Getting the last inserted record id of a database table in java

Getting the last inserted record id of a database table in java

The new JDBC-3.0 method getGeneratedKeys() which is now the preferred method to use if you need to retrieve AUTO_INCREMENT keys.
PreparedStatement ps = con.prepareStatement("insert into emp values(?,?)", Statement.RETURN_GENERATED_KEYS);
            ps.setInt(1, e.getId());
            ps.setString(2, e.getName());
            ps.executeUpdate();
            ResultSet rset = ps.getGeneratedKeys();
           while (rset.next()) {
           int i = rset.getInt(1);
           System.out.println("key=" + i);
            }

Another way

PreparedStatement ps=con.prepareStatement("insert into emp values(?,?)");
            ps.setInt(1,e.getId());
            ps.setString(2,e.getName());
            ps.executeUpdate();
            Statement stmt = con.createStatement();
            ResultSet rset = stmt.executeQuery("SELECT last_insert_id()");
            while (rset.next()) {
            System.out.println("key="+rset.getInt(1));
            }

Database Table

CREATE TABLE `emp` (
 `eid` int(11) NOT NULL auto_increment,
 `ename` varchar(20) default NULL,
 PRIMARY KEY  (`eid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

MultiActionController with Command Class in Spring


 MultiActionController with Command Class


How one can use command class Object while working with MultiActionController?
MultiActionController is used to group logically related behaviours (operations) in single Controller. It is something like struts DispatchAction but provides more flexibility.
In below example take two numbers from user and display result as addition or subtraction or multiplication based on which button is clicked. All of three operations are handled by a single Controller class.


Steps
1.       Create a new project and add Spring Web MVC library
2.       Create input page like below

Index.jsp

<body>
       <h3> Enter Numbers:</h3>
        <form action="send.htm"  method="post">
            Num1<input type="text" name="num1"/><br>
            Num2<input type="text" name="num2"/><br>
            <p>
            <input type="submit" value="add" name="method">
            <input type="submit" value="sub" name="method">
            <input type="submit" value="mult" name="method"></p>
        </form>
    </body>

3.       Create a Controller class by sub classing MultiActionController class and provides method for all above three operations which are defined in index.jsp page. Method name must be the same as value of submit button with two essential parameters request, response and third optional parameter is name of command class.

public class MyController extends MultiActionController {
 public ModelAndView add(HttpServletRequest request, HttpServletResponse respone, Num num) {
        int n1= num.getNum1();
        int n2= num.getNum2();
        int n3=n1+n2;
        return new ModelAndView("home", "msg", "Sum=" + n3);
    }

 public ModelAndView sub(HttpServletRequest request, HttpServletResponse respone,   Num num) {
        int n1= num.getNum1();
        int n2= num.getNum2();
        int n3=n1-n2;
        return new ModelAndView("home", "msg", "Sub=" + n3);
    }

 public ModelAndView mult(HttpServletRequest request, HttpServletResponse respone, Num num) {
        int n1= num.getNum1();
        int n2= num.getNum2();
        int n3=n1*n2;
        return new ModelAndView("home", "msg", "Mult=" + n3);
    }
}

4.       Create command class by sub classing MultiActionController class and provides getter and setter methods.

public class Num extends MultiActionController
{
    int num1;
    int num2;

    public int getNum1() {
        return num1;
    }

    public void setNum1(int num1) {
        this.num1 = num1;
    }

    public int getNum2() {
        return num2;
    }

    public void setNum2(int num2) {
        this.num2 = num2;
    }

}

5.       Configure ParameterMethodNameResolver class to resolve method name in Controller

<beans>
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="index.htm">indexController</prop>
                <prop key="send.htm">multiController</prop>
            </props>
        </property>
    </bean>

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" />

    <!--
    The index controller.
    -->
    <bean name="indexController"
          class="org.springframework.web.servlet.mvc.ParameterizableViewController"
          p:viewName="index" />
    <!--
    The multi action controller.
    -->
    <bean id="multiController" class="pack.MyController">
        <property name="methodNameResolver">
            <ref bean="mresolver"/>
        </property>
             
    </bean>
    <!--
    Method resolver
    -->
    <bean id="mresolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
        <property name="paramName">
            <value>method</value>
        </property>
    </bean>
</beans>

6.       Create output page home.jsp to view result

<body>
        <h1>${msg}</h1>
    </body>

You might notice the difference between usage of command class in SimpleFormController and MultiActionController.











SimpleFormController in Spring with Validator


SimpleFormController


How will be provide valid form data to the Controller in Spring , answer is SimpleFormController.
This class provided very customizable or simple way to process form data in spring. Which is describe diagrammatically below.




The SimpleFormController creates and populates a command bean, which contains all the parameters from the form as JavaBean properties accessible via getters and setters. The command bean will be validated if validation is enabled, and if no errors are found, the command bean will be processed. Otherwise, the original form page will be shown again, this time with the errors from validation.

Septs:
1.       Create new project and include Spring MVC library
2.       Create input page like below



Spring Form tags is used for input designing

Index.jsp
<%@taglib  uri="http://www.springframework.org/tags/form" prefix="form" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      </head>
    <body bgcolor="cyan">
        <h2 style="background-color: yellow">Enter User Details</h2>
        <form:form commandName="reg" method="POST">
           User Name: <form:input path="username"/><font color="red">
               <form:errors path="username"/></font><br>
           Password: <form:password path="password"/><font color="red">
           <form:errors path="password"/></font><br>
           First Name: <form:input path="fname"/><br>
           Last Name: <form:input path="lname"/><br>
           Gender: <form:radiobutton path="gender" value="male"/>Male
               <form:radiobutton path="gender" value="female"/>Female<br>
               Country :<form:select path="country" size="3" >
                       <form:option value="india">India</form:option>
                       <form:option value="india">USA</form:option>
                       <form:option value="india">Australia</form:option>
                   </form:select><br>
                   Address: <form:textarea path="addr"/><br>
                       Select any :<form:checkbox path="cb" value="checkbox1"/>
                       Check Box1
                       <form:checkbox path="cb" value="checkbox2"/>
                       Check Box2<br>
            <input type="submit" value="submit"/>
        </form:form>
    </body>
</html>
3.       Create Command Bean class

public class Registration {
   private String username;
    private String password;
    private String fname;
    private String lname;
    private String gender;
    private String country;
    private String addr;
    private String cb;

    public String getAddr() {
        return addr;
    }

    public void setAddr(String addr) {
        this.addr = addr;
    }

    public String getCb() {
        return cb;
    }

    public void setCb(String cb) {
        this.cb = cb;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Registration() {
    }

    public String getFname() {
        return fname;
    }

    public void setFname(String fname) {
        this.fname = fname;
    }

    public String getLname() {
        return lname;
    }

    public void setLname(String lname) {
        this.lname = lname;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

}

4.       Create Controller class by sub classing SimpleFormController

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class RegistrationFormController extends SimpleFormController {

@Override
    protected ModelAndView onSubmit(Object command) throws Exception {

        Registration reg=(Registration)command;

        String uname=reg.getUsername();
        String fname=reg.getFname();
        String lname=reg.getLname();

        String gender=reg.getGender();
        String country=reg.getCountry();
        String cb=reg.getCb();
        String addr=reg.getAddr();

         ModelAndView mv = new ModelAndView(getSuccessView());

          mv.addObject("uname",uname);
          mv.addObject("fname",fname);
          mv.addObject("lname",lname);
          mv.addObject("gender",gender);
          mv.addObject("country",country);
          mv.addObject("cb",cb);
          mv.addObject("addr",addr);

        return mv;
    }

}

5.       Create registration validator by implementing Validator interface



import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

public class registrationValidator implements Validator
{

    public boolean supports(Class cl) {
        return Registration.class.isAssignableFrom(cl);

    }

    public void validate(Object ob, Errors errors) {
       Registration reg=(Registration)ob;
       if (reg.getUsername() == null || reg.getUsername().length() == 0) {

            errors.rejectValue("username", "error.empty.username");
        }

       else if (reg.getPassword() == null || reg.getPassword().length() == 0) {
            errors.rejectValue("password", "error.empty.password");

        }

    }

}
6.       Create properties file messages.properties

error.empty.username=Please Enter User name
error.empty.password=Please Enter Password

7.       Configure above all beans in configuration file
<beans>
  <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

    <bean id="urlMapping"            class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="index.htm">registrationController</prop>
            </props>
        </property>
    </bean>

    <bean id="registrationValidator" class="registrationValidator"/>

    <bean id="registrationController" class="RegistrationFormController">

        <property name="sessionForm"><value>false</value></property>

        <property name="commandName" value="reg"></property>

        <property name="commandClass" value="Registration"></property>

        <property name="validator"><ref bean="registrationValidator"/></property>
        <property name="formView"><value>index</value></property>

        <property name="successView"><value>success</value></property>

    </bean>

    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="messages"/>
    </bean>
   

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" />

</beans>

8.       Output page

success.jsp

<body bgcolor="DDDDDD">
        <h1>Details of User</h1>
        <h2>
            User Name: ${uname}<br>
            First Name: ${fname}<br>
            Last Name: ${lname}<br>
            Gender: ${gender}<br>
            Country: ${country}<br>
            Address: ${addr}<br>
            Selected Check box: ${cb}
        </h2>

    </body>

9.       Run project



Output



Table per class hierarchy mapping in hibernate


Representing an inheritance relationship using Table per class hierarchy

An entire class hierarchy could be mapped to a single table. This table would include columns for all properties of all classes in the hierarchy. The concrete subclass represented by a particular row is identified by the value of a type discriminator column. This mapping strategy is a winner in terms of both performance and simplicity


How to persist object of Details in database
Steps:
1.       Create hibernate application and include hibernate library
2.       Create java bean class which represent inheritance relationship

public class User {

    String uname;
    String upass;

     public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public String getUpass() {
        return upass;
    }

    public void setUpass(String upass) {
        this.upass = upass;
    }
}

public class Detail extends User {

    String urole;
    String state;

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getUrole() {
        return urole;
    }

    public void setUrole(String urole) {
        this.urole = urole;
    }
}

3.       Create configuration file

<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/data</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
    <mapping resource="tableperclass/hibernate.hbm.xml"/>
  </session-factory>
</hibernate-configuration>


4.       Create mapping file

<subclass> sub element of <class> is used to represent the relationship with super class

<hibernate-mapping>
<class name="tableperclass.User" table="user" catalog="data">
    <id name="uname" column="uname" type="string" length="20">
        <generator class="assigned" />
    </id>
    <discriminator column="desc" type="string" length="20"/>
    <property name="upass" column="upass" type="string" length="20"/>
    <subclass name="tableperclass.Detail" discriminator-value="dc">
        <property name="state" column="state" type="string" length="20"/>
        <property name="urole" column="urole" type="string" length="20"/>
    </subclass>
</class>
</hibernate-mapping>

5.       Create persistence object
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Session session = null;
        Transaction tx = null;
        SessionFactory factory = null;
        try {
            Configuration cfg = new Configuration().configure();
            factory = cfg.buildSessionFactory();
            session = factory.openSession();
            tx = session.beginTransaction();
            Detail d = new Detail();
            d.setUname("raju");
            d.setUpass("pass");
            d.setUrole("admin");
            d.setState("bihar");
            session.save(d);
            tx.commit();
        } catch (Exception e) {
            System.err.println(e);
            if (tx != null) {
                try {
                    tx.rollback();
                } catch (Exception e1) {
                    System.out.print("Error" + e1);
                }
            }

        } finally {
            if (session != null) {
                try {
                    session.flush();
                    session.close();
                } catch (Exception e2) {
                    System.out.print("Error" + e2);
                }
            }
        }

    }
}


CREATE TABLE `user` (
  `uname` varchar(20) NOT NULL,
  `upass` varchar(20) default NULL,
  `urole` varchar(20) default NULL,
  `state` varchar(20) default NULL,
  `desc` varchar(20) default NULL,
  PRIMARY KEY  (`uname`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

ListView, ListActivity and Custom Adapter in Android


ListView 

A view that shows items in a vertically scrolling list. The items come from the ListAdapter associated with this view.

ListAdapter defines layout for individual row of the list and provide data to the ListView via setAdapter() method of ListView.

Android provides several standard adapters; the most important are ArrayAdapter and CursorAdapter.

ArrayAdapter can handle data based on Arrays or Lists while SimpleCursorAdapter handle database related data.
In this example ArrayAdapter is used, ArrayAdapter  provide constructor with four parameters to construct an ArrayAdapter

For Example:

ArrayAdapter(this, android.R.layout.simple_list_item_1,  android.R.id.text1,  name);

Explanation of arguments:

First parameter    : The current Context
Second parameter   : ID for a row layout to use when instantiating views
Third parameter -  : The id of the TextView within the layout resource to be populated
Forth parameter    : the Array or list of data
 
 
Android provides some standard row layout . These are defined in the R.layout class, and have names such as simple_list_item_1, simple_list_item_2, and two_line_list_item

The id of the TextView within this layout is android.R.id.text1, android.R.id.text2. If nothing is specified the adapter use the android.R.id.text1 ID as default id of the Textview to which the data is written.
In below Example a  layout file conation a ListView and An Activity class try to populate elements from an array to this view
UI Output

                                             
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
   
    <ListView android:id="@+id/mylist"
               android:layout_width="match_parent"
               android:layout_height="match_parent"
               android:background="#aa0000"
               android:layout_weight="1"
               android:drawSelectorOnTop="false"/>
   

</LinearLayout>    

SimpleListActivity.java
                                                             
package org.nk;

import android.app.Activity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class SimpleListActivity extends Activity {
             String[] name;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ListView listView = (ListView) findViewById(R.id.mylist);
        name = new String[] { "Raj", "Vivek", "Manish","Shyam", "Dinesh", "Rahul", "Mukesh", "Naveen" };
        ArrayAdapter<String> adp=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,android.R.id.text1,name);
       listView.setAdapter(adp);
        listView.setOnItemClickListener(onClick);
    }
    OnItemClickListener onClick=new OnItemClickListener() {

                        @Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,n  long id) {
                        Toast.makeText(getApplicationContext(),name[position], Toast.LENGTH_LONG)
                                                            .show();
                                   
                        }
};

ListActivity

The ListActivity class which extends the Activity class was designed to simplify the handling of ListViews.

Default Layout

ListActivity has a default layout that consists of a single, full-screen list in the center of the screen. Therefore you are not required to use the setContentView() to assign a layout in your Activity’s  onCreate() method.
It defines the onListItemClick() method for handling selection of list items. Internally the ListActivity registers an OnItemClickListener on the ListView.
ListActivity allows to set the adapter to the ListView via the setListAdapter() method.
Same above example using ListActivity( not needs of main.xml file for layout )
SimpleListActivity.java

package org.nk;


import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class SimpleListActivity extends ListActivity {
             String[] name;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // not  provide layout
      //setContentView();

        name = new String[] { "Raj", "Vivek", "Manish","Shyam", "Dinesh", "Rahul", "Mukesh", "Naveen" };
        ArrayAdapter<String> adp=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,android.R.id.text1,name);
       setListAdapter(adp);
       
    }
            @Override
            protected void onListItemClick(ListView l, View v, int position, long id) {
                        Toast.makeText(getApplicationContext(),name[position], Toast.LENGTH_LONG)
                        .show();
            }
           
}

Customize the screen layout

However, if you desire, you can customize the screen layout by setting your own view layout with setContentView() in onCreate(). To do this, your own view MUST contain a ListView object with the id "@android:id/list"
In the same above example now create a layout file


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
   
    <ListView android:id="@android:id/list"
               android:layout_width="match_parent"
               android:layout_height="match_parent"
               android:background="#aa0000"
               android:layout_weight="1"
               android:drawSelectorOnTop="false"/>

</LinearLayout>
Now, modify above activity code to provide mylayout
package org.nk;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class MyListActivity extends ListActivity {

               public void onCreate(Bundle icicle) {
                               super.onCreate(icicle);
// now provide layout
setContentView(R.layout.mylayout);

String[] name = new String[] { "Raj", "Vivek", "Manish","Shyam", "Dinesh", "Rahul", "Mukesh", "Naveen" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                                                             android.R.layout.simple_list_item_1,name);
setListAdapter(adapter);

               }
}

You can define own layout for the row

newlayout.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" >
 
        <TextView
        android:id="@+id/mytext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hello text"
        android:textSize="18px" >
    </TextView>
 
</LinearLayout>

Now, change default row layout and provides newlayout and ID of the View to which the data is written is mytext

package org.nk;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class MyListActivity extends ListActivity {

               public void onCreate(Bundle icicle) {
                               super.onCreate(icicle);
// no more this
// setContentView();

String[] name = new String[] { "Raj", "Vivek", "Manish","Shyam", "Dinesh", "Rahul", "Mukesh", "Naveen" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                                                             R.layout.newlayout,R.id.mytext, name);
setListAdapter(adapter);

               }
}

An ArrayAdapte is backed by an array of arbitrary objects. By default this class expects that the provided resource id references a single TextView. If you want provided resource id references more than one TextView, custom adapter can be used.

Custom Adapter


main.xml

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

    <TextView
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"       
        android:text="@string/hello" />
    <TextView
        android:id="@+id/edu"
        android:layout_width="fill_parent"       
        android:layout_height="wrap_content"
        android:text="@string/hello" />
    <TextView
        android:id="@+id/sex"
        android:layout_width="fill_parent"       
        android:layout_height="wrap_content"
        android:text="@string/hello" />
     <TextView
        android:id="@+id/sep"
        android:layout_width="fill_parent"
        android:layout_height="2dp"
        android:background="#00aa00"
        android:text=" " />

</LinearLayout>

Create a Adapter class by sub classing ArrayAdapter and override getView() method

MyListAdapter

package org.nk;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MyListAdapter extends ArrayAdapter<User>{
            private final Context context;
            private final List<User> objects;
            public MyListAdapter(Context context,List<User> objects) {
                        super(context,R.layout.main, objects);
                        this.context=context;
                        this.objects=objects;
                       
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                        LayoutInflater inflater = (LayoutInflater) context
                                                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                        //           Inflate a new view hierarchy from the specified xml resource
                                    View rowView = inflater.inflate(R.layout.main, parent, false);
                                    TextView nameView = (TextView) rowView.findViewById(R.id.name);
                                    TextView eduView = (TextView) rowView.findViewById(R.id.edu);
                                    TextView sexView = (TextView) rowView.findViewById(R.id.sex);
                                    User u=objects.get(position);
                                    nameView.setText("Name : "+u.getName());
                                    eduView.setText("Edu : "+u.getEdu());
                                    sexView.setText("Sex : "+u.getSex());
                        return rowView;
            }
}
package org.nk;
public class User {
String name;
String edu;
String sex;
public User(String name, String edu) {
            super();
            this.name = name;
            this.edu = edu;
}

public User(String name, String edu, String sex) {
            super();
            this.name = name;
            this.edu = edu;
            this.sex = sex;
}

public String getSex() {
            return sex;
}

public void setSex(String sex) {
            this.sex = sex;
}

public String getName() {
            return name;
}
public void setName(String name) {
            this.name = name;
}
public String getEdu() {
            return edu;
}
public void setEdu(String edu) {
            this.edu = edu;
}

}

MyListActivity.java
package org.nk;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
public class MyListActivity extends ListActivity {
    List<User> ulist;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ulist=new ArrayList<User>();
        ulist.add(new User("Raj","MCA","Male"));
        ulist.add(new User("Rani","MBA","Female"));
        ulist.add(new User("Ranjeet","BCA","Male"));
        ulist.add(new User("Puja","BBA","Male"));
        ulist.add(new User("Sima","BBA","Female"));      
        setListAdapter(new MyListAdapter(this, ulist));
    }
    protected void onListItemClick(ListView l, View v, int position, long id) {              
                        //get selected items
                        User user = (User) getListAdapter().getItem(position);
                        Toast.makeText(this, user.getName(), Toast.LENGTH_SHORT).show();

            }
}