Friday, October 28, 2011

Some of important SQlite queries in android

 /**
     *  method that get category data from database table
     *
     */
    public ArrayList<String>getCategories(){

        SQLiteDatabase database = this.getWritableDatabase();
        ArrayList<String> results = new ArrayList<String>();
        Cursor data = database.rawQuery("SELECT category_name from catalog2 where parent_id=0;",null);

        if (data != null)
        {
            Log.d("database",database.toString());
            if (data.moveToFirst())
            {
                do
                {
                    String catagoryName = data.getString(data.getColumnIndex("category_name"));

                    Log.e("catagery name",""+catagoryName);
                    results.add(catagoryName  );
                } while (data.moveToNext());
            }
            data.close();


            return results;
        }
        else
            return null;

    }
/**
     *  method that get sub-category from database table, here we passing categoryName which search in catlog2 table and returns category_id, from it we search all these data from catlog table ie [category_name,category_id,parent_id, is_leaf]
     *
     */
    public ArrayList<Category>getSubCategories( CharSequence categoryName){

        ArrayList<Category> results = new ArrayList<Category>();
        SQLiteDatabase database = this.getWritableDatabase();

        String parent=null;
        Cursor data = database.query("catalog2", new String[] {"category_id"},new String("category_name"+"=?"),new String[]{categoryName.toString()}, null, null, null);

        if (data.moveToFirst())
        {

            {
           
                parent = data.getString(data.getColumnIndex("category_id"));
                Log.e("parent",""+parent);
            }
        }

        data.close();

        data = database.rawQuery("SELECT category_name,category_id,parent_id, is_leaf from catalog2 where parent_id="+parent,null);

        if (data.moveToFirst())
        {
            do
            {   
                String category_id=data.getString(data.getColumnIndex("category_id"));
                String catagoryName = data.getString(data.getColumnIndex("category_name"));
                String parent_id = data.getString(data.getColumnIndex("parent_id"));
                String isleaf=data.getString(data.getColumnIndex("is_leaf"));

                Category c=new Category();
                c.category_name=catagoryName;
                Log.e("catagoryName",""+catagoryName);
                c.category_id=category_id;
                c.is_leaf=isleaf;
                c.parent_id=parent_id;
                results.add(c);
            } while (data.moveToNext());
        }

        data.close();
        database.close();

        return results;

    }





Code for getting multiple table data :

/**
     *  method that get service provider profile  from database table
     *
     */
    public ArrayList<ServiceProvider> getProviderProfiles(String profile_id){
        ArrayList<ServiceProvider> profiles = new ArrayList<ServiceProvider>();
        SQLiteDatabase database = this.getWritableDatabase();
        ArrayList<UserComments> usercommentsList=new ArrayList<UserComments>();
        UserComments userComments;
        EmailIds emailid;
        ArrayList<EmailIds> emailidList=new ArrayList<EmailIds>();
        String sp_profileid=null;
        Service1 service;
        ArrayList<Service1> servicesList=new ArrayList<Service1>();
        ArrayList<Phnos> PhnosList=new ArrayList<Phnos>();
        Phnos pHno;
        Log.e("nu_profileid",""+profile_id);
        //    Cursor data2 =database.rawQuery("SELECT * form nu_subscriptions where nu_profile_id="+profile_id,null);
        Cursor data2 = database.query("nu_subscriptions", new String[] {"sp_profile_id"},new String("nu_profile_id"+"=?"),new String[]{profile_id.toString()}, null, null, null);


        if (data2!= null)
        {
            //    Log.d(TAG+"database",database.toString());


            if (data2.moveToFirst()){
                do{
                    sp_profileid=data2.getString(data2.getColumnIndex("sp_profile_id"));
                    Log.e("sp_profileid",""+sp_profileid);
                    //Cursor data1 = database.rawQuery("select profile_name,profile_des,country,city,profile_id,rating,is_online,acno,bankname, acname from SM_profile1 where profile_id="+sp_profileid, null);
                    Cursor data1=database.query("SM_profile1", new String[] {"profile_name","profile_des","country","city","profile_id","rating","is_online","acno","bankname", "acname"},new String("profile_id"+"=?"),new String[]{sp_profileid.toString()}, null, null, null);
                    Cursor data4 = database.query("SM_email_id1", new String[] {"email_id"},new String("profile_id"+"=?"),new String[]{sp_profileid.toString()}, null, null, null);
                    Cursor data5 = database.query("SM_phone_numbers", new String[] {"contact_number"},new String("profile_id"+"=?"),new String[]{sp_profileid.toString()}, null, null, null);
                    Cursor data3 = database.query("SM_user_comments1", new String[] {"user_comments"},new String("profile_id"+"=?"),new String[]{sp_profileid.toString()}, null, null, null);
                    Cursor data6 = database.query("nu_subscriptions", new String[] {"service_id","service_name" ,"service_charge","sp_profile_id"},new String("sp_profile_id"+"=?"),new String[]{sp_profileid.toString()}, null, null, null);
                    ServiceProvider pf=new ServiceProvider();
                    if (data6.moveToFirst()){
                        do{
                    //    servicesList=new ArrayList<Service1>();
                            //servicesList.clear();
                        String service_id= data6.getString(data6.getColumnIndex("service_id"));
                        Log.e("service_id",""+service_id);
                        String service_name= data6.getString(data6.getColumnIndex("service_name"));
                        String sp_profile_id= data6.getString(data6.getColumnIndex("sp_profile_id"));
                        //String payment_timestamp= data2.getString(data2.getColumnIndex("payment_timestamp"));
                        String service_charge= data6.getString(data6.getColumnIndex("service_charge"));
                        service=new Service1();
                        service.service_id =service_id ;
                       
                        service.service_charge = service_charge;
                        service.service_name= service_name;
                        service.sp_profile_id=sp_profile_id;
                        //     service.service_des= service_des;
                        servicesList.add(service);
                        pf.serviceList=servicesList;
                        //pf.serviceList.clear();
                        Log.e(TAG,""+pf.serviceList.size());
                        for(int i=0;i<pf.serviceList.size();i++){
                        Log.e(TAG,pf.serviceList.get(i).service_id);
                        }
                        }while (data6.moveToNext());
                    }
                    if (data4.moveToFirst()){
                        String emailid1=data4.getString(data4.getColumnIndex("email_id"));
                        emailid=new EmailIds();
                        Log.e(" emailid", emailid1);
                        emailid.emailid =emailid1;
                        emailidList.add(emailid);
                        pf.email_idList=emailidList;
                    }
                    if (data5.moveToFirst()){
                        String contactnumber=data5.getString(data5.getColumnIndex("contact_number"));
                        pHno=new Phnos(null);
                        Log.e("contactnumber",contactnumber);
                        pHno.phno =contactnumber;
                        PhnosList.add(pHno);
                        pf.phnoList=PhnosList;
                    }
                    if (data3.moveToFirst())
                    {
                        String userComment1=data3.getString(data3.getColumnIndex("user_comments"));
                        userComments=new UserComments();
                        userComments.userComments = userComment1;
                        usercommentsList.add( userComments);
                        pf.usercommentsList=usercommentsList;
                    }
                    if (data1!= null)
                    {
                        Log.d(TAG+"database",database.toString());


                        if (data1.moveToFirst()){
                            //do{
                            Log.d(TAG,"am in curser data1");
                            String provider = data1.getString(data1.getColumnIndex("profile_name"));

                            String Country = data1.getString(data1.getColumnIndex("country"));
                            String profileid = data1.getString(data1.getColumnIndex("profile_id"));
                            String rating = data1.getString(data1.getColumnIndex("rating"));
                            String is_online= data1.getString(data1.getColumnIndex("is_online"));
                            //    String usercomments=data1.getString(data1.getColumnIndex("usercomments"));
                            String acname=data1.getString(data1.getColumnIndex("acname"));
                            String bankname=data1.getString(data1.getColumnIndex("bankname"));
                            String acno=data1.getString(data1.getColumnIndex("acno"));
                            pf.country=Country;
                            Log.d("pf.country",pf.country);
                            pf.profile_id=profileid;
                            Log.d("profile_id",pf.profile_id);
                            pf.profile_name=provider;
                            Log.d("profile_name",pf.profile_name);
                            pf.is_online=is_online;
                            pf.acname=acname;
                            pf.acno=acno;
                            pf.bankname=bankname;
                            pf.rating=rating;
                            //pf.videoid=videoid;
                            //    Log.d(TAG,pf.videoid);


                            //}while (data1.moveToNext());

                        }

                        //database.close();
                    }

                    profiles.add(pf);
                }while (data2.moveToNext());
                Log.e(TAG+"profiles size",""+profiles.size());
                data2.close();
                //    data1.close();
            }

        }



        return profiles;
    }


CRUD Database with Sqlite3 creating database using SQlite manager tool and accessing path

DBAdapter.java

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class DBAdapter extends SQLiteOpenHelper {

    private static String DB_PATH = "";
    private static final String DB_NAME = "user.sqlite";
    private SQLiteDatabase myDataBase;
    private final Context myContext;

    private static DBAdapter mDBConnection;

    /**
     * Constructor 
     * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
     * @param context
     */
    private DBAdapter(Context context) {
        super(context, DB_NAME, null, 1);
        this.myContext = context;
        DB_PATH = "/data/data/"
                + context.getApplicationContext().getPackageName()
                + "/databases/";
        // The Android's default system path of your application database is
        // "/data/data/mypackagename/databases/"
    }
   
    /**
     * getting Instance
     * @param context
     * @return DBAdapter
     */
    public static synchronized DBAdapter getDBAdapterInstance(Context context) {
        if (mDBConnection == null) {
            mDBConnection = new DBAdapter(context);
        }
        return mDBConnection;
    }

    /**
     * Creates an empty database on the system and rewrites it with your own database.
     **/
    public void createDataBase() throws IOException {
        boolean dbExist = checkDataBase();
        if (dbExist) {
            // do nothing - database already exist
        } else {
            // By calling following method 
            // 1) an empty database will be created into the default system path of your application 
            // 2) than we overwrite that database with our database.
            this.getReadableDatabase();
            try {
                copyDataBase();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        }
    }

    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase() {
        SQLiteDatabase checkDB = null;
        try {
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null,
                    SQLiteDatabase.OPEN_READONLY);

        } catch (SQLiteException e) {
            // database does't exist yet.
        }
        if (checkDB != null) {
            checkDB.close();
        }
        return checkDB != null ? true : false;
    }

    /**
     * Copies your database from your local assets-folder to the just created
     * empty database in the system folder, from where it can be accessed and
     * handled. This is done by transfering bytestream.
     * */
    private void copyDataBase() throws IOException {
            // Open your local db as the input stream
        InputStream myInput = myContext.getAssets().open(DB_NAME);
            // Path to the just created empty db
        String outFileName = DB_PATH + DB_NAME;
            // Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);
            // transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }
            // Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();
    }
 
    /**
     * Open the database
     * @throws SQLException
     */
    public void openDataBase() throws SQLException {
        String myPath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);       
    }

    /**
     * Close the database if exist
     */
    @Override
    public synchronized void close() {
        if (myDataBase != null)
            myDataBase.close();
        super.close();
    }

    /**
     * Call on creating data base for example for creating tables at run time
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
    }

    /**
     * can used for drop tables then call onCreate(db) function to create tables again - upgrade
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    // ----------------------- CRUD Functions ------------------------------
   
    /**
     * This function used to select the records from DB.
     * @param tableName
     * @param tableColumns
     * @param whereClase
     * @param whereArgs
     * @param groupBy
     * @param having
     * @param orderBy
     * @return A Cursor object, which is positioned before the first entry.
     */
    public Cursor selectRecordsFromDB(String tableName, String[] tableColumns,
            String whereClase, String whereArgs[], String groupBy,
            String having, String orderBy) {
        return myDataBase.query(tableName, tableColumns, whereClase, whereArgs,
                groupBy, having, orderBy);
    }
   
    /**
     * select records from db and return in list
     * @param tableName
     * @param tableColumns
     * @param whereClase
     * @param whereArgs
     * @param groupBy
     * @param having
     * @param orderBy
     * @return ArrayList<ArrayList<String>>
     */
    public ArrayList<ArrayList<String>> selectRecordsFromDBList(String tableName, String[] tableColumns,
            String whereClase, String whereArgs[], String groupBy,
            String having, String orderBy) {       
       
        ArrayList<ArrayList<String>> retList = new ArrayList<ArrayList<String>>();
          ArrayList<String> list = new ArrayList<String>();
          Cursor cursor = myDataBase.query(tableName, tableColumns, whereClase, whereArgs,
                    groupBy, having, orderBy);        
          if (cursor.moveToFirst()) {
             do {
                 list = new ArrayList<String>();
                 for(int i=0; i<cursor.getColumnCount(); i++){                     
                     list.add( cursor.getString(i) );
                 }     
                 retList.add(list);
             } while (cursor.moveToNext());
          }
          if (cursor != null && !cursor.isClosed()) {
             cursor.close();
          }
          return retList;

    }   

    /**
     * This function used to insert the Record in DB. 
     * @param tableName
     * @param nullColumnHack
     * @param initialValues
     * @return the row ID of the newly inserted row, or -1 if an error occurred
     */
    public long insertRecordsInDB(String tableName, String nullColumnHack,
            ContentValues initialValues) {
        return myDataBase.insert(tableName, nullColumnHack, initialValues);
    }

    /**
     * This function used to update the Record in DB.
     * @param tableName
     * @param initialValues
     * @param whereClause
     * @param whereArgs
     * @return true / false on updating one or more records
     */
    public boolean updateRecordInDB(String tableName,
            ContentValues initialValues, String whereClause, String whereArgs[]) {
        return myDataBase.update(tableName, initialValues, whereClause,
                whereArgs) > 0;               
    }
   
    /**
     * This function used to update the Record in DB.
     * @param tableName
     * @param initialValues
     * @param whereClause
     * @param whereArgs
     * @return 0 in case of failure otherwise return no of row(s) are updated
     */
    public int updateRecordsInDB(String tableName,
            ContentValues initialValues, String whereClause, String whereArgs[]) {
        return myDataBase.update(tableName, initialValues, whereClause, whereArgs);       
    }

    /**
     * This function used to delete the Record in DB.
     * @param tableName
     * @param whereClause
     * @param whereArgs
     * @return 0 in case of failure otherwise return no of row(s) are deleted.
     */
    public int deleteRecordInDB(String tableName, String whereClause,
            String[] whereArgs) {
        return myDataBase.delete(tableName, whereClause, whereArgs);
    }

    // --------------------- Select Raw Query Functions ---------------------
   
    /**
     * apply raw Query
     * @param query
     * @param selectionArgs
     * @return Cursor
     */
    public Cursor selectRecordsFromDB(String query, String[] selectionArgs) {
        return myDataBase.rawQuery(query, selectionArgs);       
    }
   
    /**
     * apply raw query and return result in list
     * @param query
     * @param selectionArgs
     * @return ArrayList<ArrayList<String>>
     */
    public ArrayList<ArrayList<String>> selectRecordsFromDBList(String query, String[] selectionArgs) {          
          ArrayList<ArrayList<String>> retList = new ArrayList<ArrayList<String>>();
          ArrayList<String> list = new ArrayList<String>();
          Cursor cursor = myDataBase.rawQuery(query, selectionArgs);            
          if (cursor.moveToFirst()) {
             do {
                 list = new ArrayList<String>();
                 for(int i=0; i<cursor.getColumnCount(); i++){                     
                     list.add( cursor.getString(i) );
                 }     
                 retList.add(list);
             } while (cursor.moveToNext());
          }
          if (cursor != null && !cursor.isClosed()) {
             cursor.close();
          }
          return retList;
       }

}

gridview which scrolls horizontally with network call

/**
 * Class Name : CategoryMenu
 *
 * Parent Class :Activity
 *
 * Interfaces: None
 *
 * Description:This class displays the categories and
   subcategories menu to the user. Categories will bedisplayed
    as a one line horizontal gallery and Subcategories as a list.

 */

import java.util.ArrayList;
import java.util.List;

import com.ServiceMessenger.R;




import com.inception.dataparser.Category;
import com.inception.dataparser.ServiceProvider;
import com.inception.dataparser.UserProfiles;
import com.inception.dataprovider.DatabaseHelper;
import com.inception.network.MessageAlertService;
import com.inception.network.NetworkService;
import com.inception.network.NetworkUtilService;
import com.inception.sm.ApplicationManager;
import com.inception.sm.Globals;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView.ScaleType;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;


public class CategoryMenu extends Activity {
    /** Called when the activity is first created. */

    ArrayList<UserProfiles> mUserProfiles = new ArrayList<UserProfiles>();
    public List<String> mList = null;
    private ArrayList<ServiceProvider> mProfileList = new ArrayList<ServiceProvider>();
    public static String mUProfilrid;
    private static final int INDETERMINATE = 0;
   
    String mProfileid;


    ///    public static boolean mLogin_status=false;

    private int  mLoadingFirst;
    SharedPreferences mSettings;
    SharedPreferences mSettings1;
    public static SharedPreferences mLogin_status;
    static Boolean mStatus;


    private int mCatvs;
    private int mCurrentv;
    private int mCatv1;
    private LayoutInflater mInflater;
    private NotificationManager mNotificationManager;
    private ProgressDialog mProgDlg;
    private static ApplicationManager mAppMgr;
    private DatabaseHelper mDBHelper;
    final Messenger mMessenger = new Messenger(new IncomingHandler());
    Messenger mService = null;

    //wedgets
    Intent i;
    Bitmap viewBgrnd;
    Integer[] mThumbIds;
    ImageButton img ;
    Button button;
    ImageView img1;
    TextView tx;
    Button b1;
   
    //gallery wedgets
    private ScrollView nsv;
    private HorizontalScrollView sv;
    private LinearLayout llh;
    private LinearLayout.LayoutParams layoutParamsTV;
    private LinearLayout.LayoutParams layoutParamsLL;
    private LinearLayout.LayoutParams layoutParamsLLD;
    private LinearLayout llv;
   
    static int  total;
    private Category mCat = new Category();
    /**
     * Class Name :IncomingHandler
     *
     * Parent Class :Handler
     *
     * Interfaces: None
     *
     * Description:Handler class for handling
     *
     *  incoming messages from server

     */

    class IncomingHandler extends Handler {

        /**
         * Callback method to handle messages coming from server
         *
         */

        @Override
        public void handleMessage(Message msg) {
            Log.e("UIAct","handleMessage");
            switch (msg.what) {
            case NetworkService.MSG_CATALOG_AVAILABLE:
                mList= new ArrayList<String>();
               
                Log.e("MSG_CATALOG_AVAILABLE",""+mList.size());
               
                mList=mAppMgr.getCategories();
                horizontalScrollGalleryLayout(mList);
                mProgDlg.dismiss();
                //mGallery.setAdapter(new ImageAdapter(CategoryMenu.this));
                break;


            default:
                super.handleMessage(msg);
            }
        }


    }
    /**
     * Callback method to get connection from server
     *
     */
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            mService = new Messenger(service);

            try {
                Log.e("UIAct","onServiceConnected");

                Message msg = Message.obtain(null, NetworkService.MSG_REGISTER_CLIENT);
                msg.replyTo = mMessenger;
                mService.send(msg);
                //Log.e("mCatv in 2nd if","xyz"+mCatvs);
                //Log.e("mCurrentv in 2nd if",""+mCurrentv);
                //msg.replyTo = mMessenger;
                msg = Message.obtain(null, NetworkService.MSG_GET_CATALOG);
                msg.replyTo = mMessenger;
                mService.send(msg);
                Log.d("connecting to","categories service");
                //    }


            } catch (RemoteException e) {
                // In this case the service has crashed before we could even do anything with it
            }

        }

        /**
         * Callback method to get disconnect from server
         *
         */

        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
            mService = null;
            Log.e("UIAct","onServiceDisconnected");
        }
    };

    /**
     * Callback method to launch the Acitivity
     *
     */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSettings = this.getSharedPreferences(Globals.PREFS_NAME, 0);
        mLogin_status = this.getSharedPreferences(Globals.PREFS_NAME, 0);
        mStatus=mLogin_status.getBoolean("status", false);
        mSettings1 = this.getSharedPreferences(Globals.PREFS_NAME, 0);
       
       
        Context context = getApplicationContext();
        nsv=new ScrollView(this);
        sv = new HorizontalScrollView(this);
        llh = new LinearLayout(this);
        llh.setOrientation(LinearLayout.HORIZONTAL);
        layoutParamsTV = new LinearLayout.LayoutParams(80,80);
        layoutParamsTV.setMargins(15, 30, 15, 15);

        layoutParamsLL = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutParamsLLD = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
        mDBHelper = new DatabaseHelper(this);
        mAppMgr = ApplicationManager.getApplicationMgrInstance(this.getApplicationContext());
        mList =new ArrayList<String>();
        mList =mAppMgr.getCategories();
        total=0;
        //horizontalScrollGalleryLayout1(mList);
        Log.i("mList",""+mList.size());

        if(mList.size()==0){
            boolean check_con=NetworkUtilService.getInstance(this).isOnline(this);            Log.i("check_con",""+check_con);
            if (NetworkUtilService.getInstance(this).isOnline(this)) {
                Log.e("binding to","service");
                showDialog(INDETERMINATE);
                //mLoadingFirst=1;
                bindService(new Intent(CategoryMenu.this, NetworkService.class), mConnection, Context.BIND_AUTO_CREATE);
                Log.e("loading first time","for catalog");       
                //horizontalScrollGalleryLayout(mList);
                mProgDlg.dismiss();
            }
            else
            { 
               
                AlertDialog.Builder dialog1 = new AlertDialog.Builder(CategoryMenu.this);
                dialog1.setTitle("ALERT");
                dialog1.setMessage("No Connection! Try Later");
                dialog1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog1, int id) {

                        CategoryMenu.this.finish();
                        //dialog1.cancel();
                    }
                });
                /*dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                       
                        dialog.cancel();
                    }
                });*/
                AlertDialog alert =dialog1.create();
                // Title for AlertDialog
                alert.setTitle("OUT OF CONNECTION");
                // Icon for AlertDialog
                alert.setIcon(R.drawable.icon);
                alert.show();
            }



        }
        else
        {
            horizontalScrollGalleryLayout(mList);
            Log.e("mList in else",""+mList.size());
            //    Log.e(mList.get(0).);
        }
       

    }
   
    public void horizontalScrollGalleryLayout (List<String> mList3) {
        Integer[] mThumbIds = {
                R.drawable.gallery_photo_1,R.drawable.gallery_photo_2,R.drawable.gallery_photo_3,
                R.drawable.gallery_photo_4,R.drawable.gallery_photo_5,R.drawable.gallery_photo_6,
                R.drawable.gallery_photo_1,R.drawable.gallery_photo_2,R.drawable.gallery_photo_3,
                R.drawable.gallery_photo_4,R.drawable.gallery_photo_2,
                R.drawable.gallery_photo_1,R.drawable.gallery_photo_2,R.drawable.gallery_photo_3,
                R.drawable.gallery_photo_4,R.drawable.gallery_photo_5,R.drawable.gallery_photo_6,
                R.drawable.gallery_photo_1,R.drawable.gallery_photo_2,R.drawable.gallery_photo_3,
                R.drawable.gallery_photo_4,R.drawable.gallery_photo_5,R.drawable.gallery_photo_6,
                R.drawable.gallery_photo_1,R.drawable.gallery_photo_2,R.drawable.gallery_photo_3,
                R.drawable.gallery_photo_4,R.drawable.gallery_photo_5,R.drawable.gallery_photo_6,
                /*  R.drawable.gallery_photo_1,R.drawable.gallery_photo_2,R.drawable.gallery_photo_3,
                  R.drawable.gallery_photo_4,R.drawable.gallery_photo_5,R.drawable.gallery_photo_6,
                  R.drawable.gallery_photo_1,R.drawable.gallery_photo_2,R.drawable.gallery_photo_3*/


        };
        Log.i("I got call","for creation of horizontalgallery");
        sv = new HorizontalScrollView(this);
        llh = new LinearLayout(this);
        llh.setOrientation(LinearLayout.HORIZONTAL);
        layoutParamsTV = new LinearLayout.LayoutParams(75,75);
        layoutParamsTV.setMargins(15, 30, 15, 15);

        layoutParamsLL = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutParamsLLD = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
        Log.e("in horizantal","scroll view 1");
        for(int k=0;k<mList3.size();k++)
        {  
            if(mList3.size()==total)
            {
                break;
            }
            llv = new LinearLayout(this);
           
            for (int i=0; i<3; i++) {
                llv.setOrientation(LinearLayout.VERTICAL);
                //button= new Button(this);
                //button=new Button(this);
                img1 = new ImageView(this);
                tx = new TextView(this);
                mCat = new Category();
                try {

                    img1.setBackgroundResource(mThumbIds[total]);
                    img1.setTag(mList3.get(total));
                    tx.setText(mList3.get(total));
                    tx.setTextColor(Color.WHITE);
                    //tx.setPadding(25, 0, 15, 0);
                    tx.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);

                    img1.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View view) {
                            // Perform action on click
                            //CharSequence cat = "Education";
                            CharSequence cat = (CharSequence) view.getTag();
                            Log.e("imgTag after category clicked",""+ cat);
                            CharSequence category = cat;
                            mCat=mAppMgr.getCategoryObjectFromId(category);
                            String isleaf = mCat.getIs_leaf();
                            String parent_id=mCat.getParent_id();
                            String cat_id=mCat.getCategory_id();

                            Log.e("isleaf",isleaf);
                            //Log.e("parent_id",parent_id);
                            if(isleaf.equals("false"))
                            {
                                Intent i=new Intent(CategoryMenu.this,ProfilesList.class);
                                //i.putExtra("subcat", category);
                                Log.d("false executed","Thanks");
                                i.putExtra("cat", category);
                                i.putExtra("view", Globals.CONST_SUBCATEGORY);
                                startActivity(i);
                            }
                            else
                            {
                                Intent i=new Intent(CategoryMenu.this,ProfilesList.class);
                                Log.d("true executed","Thanks");

                                i.putExtra("cat",cat_id);
                                i.putExtra("view", Globals.CONST_PROFILE);
                                startActivity(i);
                            }


                            //CharSequence category = cat;
                            //Log.e("category",""+category);
                            //i.putExtra("subcat", category);
                            //i.putExtra("view", Globals.CONST_PROFILE);

                            Log.e("am in","sub categories");



                        }
                    });


                    total++;

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                llv.addView(img1,layoutParamsTV);
                llv.addView(tx);
                if(mList3.size()==total)
                    break;
                //b1[k].setBackgroundResource(mThumbIds[k]);
            }

            //llv.addView(button, layoutParamsTV);

            llh.addView(llv, layoutParamsLL);
            llh.setBackgroundColor(Color.TRANSPARENT);
            llh.setHorizontalScrollBarEnabled(false);
        }

        sv.addView(llh, layoutParamsLLD);
        nsv.addView(sv);
        sv.setHorizontalScrollBarEnabled(false);
        nsv.setVerticalScrollBarEnabled(false);
        //setContentView(sv);
        setContentView(nsv);
       
    }


    /**
     *Progress bar  to show progress of fetching data from server
     */

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case INDETERMINATE: {
            mProgDlg = new ProgressDialog(this);
            mProgDlg.setTitle("Indeterminate");
            mProgDlg.setMessage("Please wait while loading...");
            mProgDlg.setIndeterminate(true);
            mProgDlg.setCancelable(true);
            return mProgDlg;
        }
        }
        return null;
    }






   
    public void onDestroy() {
        Log.i("CategoryMenu","onDestroy Called");
        super.onDestroy();
        try {
            stopService(new Intent(CategoryMenu.this, MessageAlertService.class));
        } catch (Throwable t) {
            Log.e("CategoryMenu", "stopService", t);
        }
    }
}

Database with Sqlite3 .EmployeeDB example

Step to create DBHelper class

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;




public class DatabaseHelper extends SQLiteOpenHelper {

    static final String dbName="demoDB";
    static final String employeeTable="Employees";
    static final String colID="EmployeeID";
    static final String colName="EmployeeName";
    static final String colAge="Age";
    static final String colDept="Dept";
   
    static final String deptTable="Dept";
    static final String colDeptID="DeptID";
    static final String colDeptName="DeptName";
   
    static final String viewEmps="ViewEmps";
   
   
   
    public DatabaseHelper(Context context) {
        super(context, dbName, null,33);
       
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
       
        db.execSQL("CREATE TABLE "+deptTable+" ("+colDeptID+ " INTEGER PRIMARY KEY , "+
                colDeptName+ " TEXT)");
       
        db.execSQL("CREATE TABLE "+employeeTable+" ("+colID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
                colName+" TEXT, "+colAge+" Integer, "+colDept+" INTEGER NOT NULL ,FOREIGN KEY ("+colDept+") REFERENCES "+deptTable+" ("+colDeptID+"));");
       
       
        db.execSQL("CREATE TRIGGER fk_empdept_deptid " +
                " BEFORE INSERT "+
                " ON "+employeeTable+
               
                " FOR EACH ROW BEGIN"+
                " SELECT CASE WHEN ((SELECT "+colDeptID+" FROM "+deptTable+" WHERE "+colDeptID+"=new."+colDept+" ) IS NULL)"+
                " THEN RAISE (ABORT,'Foreign Key Violation') END;"+
                "  END;");
       
        db.execSQL("CREATE VIEW "+viewEmps+
                " AS SELECT "+employeeTable+"."+colID+" AS _id,"+
                " "+employeeTable+"."+colName+","+
                " "+employeeTable+"."+colAge+","+
                " "+deptTable+"."+colDeptName+""+
                " FROM "+employeeTable+" JOIN "+deptTable+
                " ON "+employeeTable+"."+colDept+" ="+deptTable+"."+colDeptID
                );
        //Inserts pre-defined departments
        InsertDepts(db);
       
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
       
        db.execSQL("DROP TABLE IF EXISTS "+employeeTable);
        db.execSQL("DROP TABLE IF EXISTS "+deptTable);
       
        db.execSQL("DROP TRIGGER IF EXISTS dept_id_trigger");
        db.execSQL("DROP TRIGGER IF EXISTS dept_id_trigger22");
        db.execSQL("DROP TRIGGER IF EXISTS fk_empdept_deptid");
        db.execSQL("DROP VIEW IF EXISTS "+viewEmps);
        onCreate(db);
    }
   
     void AddEmployee(Employee emp)
    {
         
         
         SQLiteDatabase db= this.getWritableDatabase();
         
       
        ContentValues cv=new ContentValues();
       
        cv.put(colName, emp.getName());
        cv.put(colAge, emp.getAge());
        cv.put(colDept, emp.getDept());
        //cv.put(colDept,2);
       
        db.insert(employeeTable, colName, cv);
        db.close();
       
       
    }
     
     int getEmployeeCount()
     {
        SQLiteDatabase db=this.getWritableDatabase();
        Cursor cur= db.rawQuery("Select * from "+employeeTable, null);
        int x= cur.getCount();
        cur.close();
        return x;
     }
     
     Cursor getAllEmployees()
     {
         SQLiteDatabase db=this.getWritableDatabase();
         
         
         
         //Cursor cur= db.rawQuery("Select "+colID+" as _id , "+colName+", "+colAge+" from "+employeeTable, new String [] {});
         Cursor cur= db.rawQuery("SELECT * FROM "+viewEmps,null);
         return cur;
         
     }
     
     Cursor getAllDepts()
     {
         SQLiteDatabase db=this.getReadableDatabase();
         Cursor cur=db.rawQuery("SELECT "+colDeptID+" as _id, "+colDeptName+" from "+deptTable,new String [] {});
         
         return cur;
     }
     
     void InsertDepts(SQLiteDatabase db)
     {
         ContentValues cv=new ContentValues();
            cv.put(colDeptID, 1);
            cv.put(colDeptName, "Sales");
            db.insert(deptTable, colDeptID, cv);
            cv.put(colDeptID, 2);
            cv.put(colDeptName, "IT");
            db.insert(deptTable, colDeptID, cv);
            cv.put(colDeptID, 3);
            cv.put(colDeptName, "HR");
            db.insert(deptTable, colDeptID, cv);
            db.insert(deptTable, colDeptID, cv);
           
     }
     
     public String GetDept(int ID)
     {
         SQLiteDatabase db=this.getReadableDatabase();
         
         String[] params=new String[]{String.valueOf(ID)};
         Cursor c=db.rawQuery("SELECT "+colDeptName+" FROM"+ deptTable+" WHERE "+colDeptID+"=?",params);
         c.moveToFirst();
         int index= c.getColumnIndex(colDeptName);
         return c.getString(index);
     }
     
     public Cursor getEmpByDept(String Dept)
     {
         SQLiteDatabase db=this.getReadableDatabase();
         String [] columns=new String[]{"_id",colName,colAge,colDeptName};
         Cursor c=db.query(viewEmps, columns, colDeptName+"=?", new String[]{Dept}, null, null, null);
         return c;
     }
     
     public Cursor getEmpByID(String ID)
     {
         SQLiteDatabase db=this.getReadableDatabase();
         String [] columns=new String[]{"EmployeeID as _id",colName,colAge,colDept};
         Cursor c=db.query(employeeTable, columns, "_id=?", new String[]{ID}, null, null, null);
         return c;
     }
     
     public int GetDeptID(String Dept)
     {
         SQLiteDatabase db=this.getReadableDatabase();
         Cursor c=db.query(deptTable, new String[]{colDeptID+" as _id",colDeptName},colDeptName+"=?", new String[]{Dept}, null, null, null);
         //Cursor c=db.rawQuery("SELECT "+colDeptID+" as _id FROM "+deptTable+" WHERE "+colDeptName+"=?", new String []{Dept});
         c.moveToFirst();
         return c.getInt(c.getColumnIndex("_id"));
         
         }
     
     public int UpdateEmp(Employee emp)
     {
         SQLiteDatabase db=this.getWritableDatabase();
         ContentValues cv=new ContentValues();
         cv.put(colName, emp.getName());
         cv.put(colAge, emp.getAge());
         cv.put(colDept, emp.getDept());
         return db.update(employeeTable, cv, colID+"=?", new String []{String.valueOf(emp.getID())});
         
     }
     
     public void DeleteEmp(Employee emp)
     {
         SQLiteDatabase db=this.getWritableDatabase();
         db.delete(employeeTable,colID+"=?", new String [] {String.valueOf(emp.getID())});
         db.close();
         
       
       
     }

}










Code for Employee.java
package mina.android.DatabaseDemo;

import android.content.Context;

public class Employee {
   
    int _id;
    String _name;
    int _age;
    int _dept;
   
    public Employee(String Name,int Age,int Dept)
    {
       
        this._name=Name;
        this._age=Age;
        this._dept=Dept;
    }
   
    public Employee(String Name,int Age)
    {
        this._name=Name;
        this._age=Age;
    }
   
    public int getID()
    {
        return this._id;
    }
    public void SetID(int ID)
    {
        this._id=ID;
    }
   
    public String getName()
    {
        return this._name;
    }
   
    public int getAge()
    {
        return this._age;
    }
   
    public void setName(String Name)
    {
        this._name=Name;
    }
    public void setAge(int Age)
    {
        this._age=Age;
    }
   
   
   
    public void setDept(int Dept)
    {
        this._dept=Dept;
    }
   
    public String getDeptName(Context con, int Dept)
    {
        return new DatabaseHelper(con).GetDept(Dept);
    }
    public int getDept()
    {
        return this._dept;
    }
}
Code for AddEmployee.java
 package mina.android.DatabaseDemo;

import android.app.Activity;
import android.app.Dialog;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Spannable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;

public class AddEmployee extends Activity {
    EditText txtName;
    EditText txtAge;
    TextView txtEmps;
    DatabaseHelper dbHelper;
    Spinner spinDept;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addemployee);
        txtName=(EditText)findViewById(R.id.txtName);
        txtAge=(EditText)findViewById(R.id.txtAge);
        txtEmps=(TextView)findViewById(R.id.txtEmps);
        spinDept=(Spinner)findViewById(R.id.spinDept);
    }
    
    @Override
    public void onStart()
    {
        try
        {
        super.onStart();
        dbHelper=new DatabaseHelper(this);
        txtEmps.setText(String.valueOf(dbHelper.getEmployeeCount()));
        
        Cursor c=dbHelper.getAllDepts();
        startManagingCursor(c);
        
        
        
        //SimpleCursorAdapter ca=new SimpleCursorAdapter(this,android.R.layout.simple_spinner_item, c, new String [] {DatabaseHelper.colDeptName}, new int []{android.R.id.text1});
        SimpleCursorAdapter ca=new SimpleCursorAdapter(this,R.layout.deptspinnerrow, c, new String [] {DatabaseHelper.colDeptName,"_id"}, new int []{R.id.txtDeptName});
        //ca.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinDept.setAdapter(ca);
        spinDept.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View selectedView,
                    int position, long id) {
                // TODO Auto-generated method stub
                
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
                
            }
        });
        
        
        //never close cursor
        }
        catch(Exception ex)
        {
            CatchError(ex.toString());
        }
    }
    
    public void btnAddEmp_Click(View view)
    {
        boolean ok=true;
        try
        {
            Spannable spn=txtAge.getText();
            String name=txtName.getText().toString();
            int age=Integer.valueOf(spn.toString());
            int deptID=Integer.valueOf((int)spinDept.getSelectedItemId());
            Employee emp=new Employee(name,age,deptID);
            
            dbHelper.AddEmployee(emp);
            
        }
        catch(Exception ex)
        {
            ok=false;
            CatchError(ex.toString());
        }
        finally
        {
            if(ok)
            {
                //NotifyEmpAdded();
                Alerts.ShowEmpAddedAlert(this);
                txtEmps.setText("Number of employees "+String.valueOf(dbHelper.getEmployeeCount()));
            }
        }
    }
    
    void CatchError(String Exception)
    {
        Dialog diag=new Dialog(this);
        diag.setTitle("Add new Employee");
        TextView txt=new TextView(this);
        txt.setText(Exception);
        diag.setContentView(txt);
        diag.show();
    }
    
    void NotifyEmpAdded()
    {
        Dialog diag=new Dialog(this);
        diag.setTitle("Add new Employee");
        TextView txt=new TextView(this);
        txt.setText("Employee Added Successfully");
        diag.setContentView(txt);
        diag.show();
        try {
            diag.wait(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            CatchError(e.toString());
        }
        diag.notify();
        diag.dismiss();
    }
    
}
Code for DatabaseDemo.java with tabhost:





package mina.android.DatabaseDemo;




import android.app.TabActivity;
import android.content.Intent;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;




import android.widget.GridView;

import android.widget.TabHost;
import android.widget.TextView;



public class DatabaseDemo extends TabActivity {
    DatabaseHelper dbHelper;
    GridView grid;
    TextView txtTest;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        SetupTabs();

    }
   
   
   
   
   
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        menu.add(1, 1, 1, "Add Employee");
        return true;
    }
   
   
   
   
   
   
   
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
        //Add employee
        case 1:
            Intent addIntent=new Intent(this,AddEmployee.class);
            startActivity(addIntent);
            break;
        }
        super.onOptionsItemSelected(item);
        return false;
    }
   
    void SetupTabs()
    {

        TabHost host=getTabHost();

        TabHost.TabSpec spec=host.newTabSpec("tag1");
        Intent in1=new Intent(this, AddEmployee.class);
        spec.setIndicator("Add Employee");
        spec.setContent(in1);
       
       
       
        TabHost.TabSpec spec2=host.newTabSpec("tag2");
        Intent in2=new Intent(this, GridList.class);
       
        spec2.setIndicator("Employees");
        spec2.setContent(in2);
       
        host.addTab(spec);
        host.addTab(spec2);
       
      
    }
   
}



code for EmployeesContentProvider.java which demonstrate content provider in android:


package mina.android.DatabaseDemo;

import java.sql.ResultSetMetaData;
import java.util.HashMap;
import java.util.List;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;

public class EmployeesContentProvider extends ContentProvider {

    public static final Uri CONTENT_URI=Uri.parse("content://employees");
    DatabaseHelper db;
    //authority and paths
    public static final String AUTHORITY="employees";
    public static final String ALLPATH="All";
    public static final String ITPATH="IT";
    public static final String HRPATH="HR";
    public static final String SALESPATH="Sales";
   
   
    //URiMatcher to match client URis
    public static final int ALLEMPLOYEES=1;
    public static final int SINGLEEMPLOYEE=2;
    public static final int IT=3;
    public static final int HR=4;
    public static final int SALES=5;
    static final UriMatcher matcher=new UriMatcher(UriMatcher.NO_MATCH);
    static{
        matcher.addURI(AUTHORITY,null,ALLEMPLOYEES);
        matcher.addURI(AUTHORITY, ITPATH, IT);
        matcher.addURI(AUTHORITY, HRPATH, HR);
        matcher.addURI(AUTHORITY, SALESPATH, SALES);
        //you can use '*' as a wild card for any text
        matcher.addURI(AUTHORITY, "#", SINGLEEMPLOYEE);
    }
   
    @Override
    public int delete(Uri uri, String where, String[] args) {
       
        int match=matcher.match(uri);
        //expecting the URi to be in the form of content://
        if(match==1)
        {
            SQLiteDatabase dataBase=db.getWritableDatabase();
            return dataBase.delete(db.employeeTable, where, args);
        }
        else
        return 0;
    }

    @Override
    public String getType(Uri uri) {
        int match=matcher.match(uri);
        // single employee
        if(match==2)
        {
            return "mina.android.Employee";
        }
        //collection of employees
        else
        {
           
            return "mina.android.Employees";
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        int match=matcher.match(uri);
        //not the Uri we're expecting
        long newID=0;
        if(match!=1)
            throw new IllegalArgumentException("Wrong URi "+uri.toString());
        if(values!=null)
        {
            newID=db.getWritableDatabase().insert(DatabaseHelper.employeeTable, DatabaseHelper.colName, values);
            return Uri.withAppendedPath(uri, String.valueOf(newID));
           
        }
        else
            return null;
    }

    @Override
    public boolean onCreate() {
        // TODO Auto-generated method stub
        db=new DatabaseHelper(this.getContext());
        if(db==null)
            return false;
        else
            return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder builder=new SQLiteQueryBuilder();
       
        builder.setTables(DatabaseHelper.viewEmps);
       
        String order=null;
        Cursor result=null;
        if(sortOrder!=null)
            order=sortOrder;
        int match=matcher.match(uri);
        switch(match)
        {
        case ALLEMPLOYEES:
           
            result=builder.query(db.getWritableDatabase(), projection, selection, selectionArgs, null, null, sortOrder);
            break;
        case SINGLEEMPLOYEE:
            //content://employees//id
            List<String>segments=uri.getPathSegments();
            String empID=segments.get(0);
            result=db.getEmpByID(empID);

            break;
        case IT:
            //content://employees//IT
            result=db.getEmpByDept("IT");
            result=builder.query(db.getReadableDatabase(), projection, db.colDeptName+"=?", new String[]{"IT"}, null, null, sortOrder);
            break;
        case HR:
            //content://employees//HR
            result=db.getEmpByDept("HR");
            result=builder.query(db.getReadableDatabase(), projection, db.colDeptName+"=?", new String[]{"HR"}, null, null, sortOrder);
            break;
        case SALES:
            //content://employees//Sales
            result=db.getEmpByDept("Sales");
            result=builder.query(db.getReadableDatabase(), projection, db.colDeptName+"=?", new String[]{"Sales"}, null, null, sortOrder);
           
            break;
       
        }
       
        return result;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {
        int match=matcher.match(uri);
        //not the Uri we're expecting
        int rows=0;
        //update single instance
        if(match==2)
        {
            if(values!=null)
            {
                List<String>segments=uri.getPathSegments();
                String empID=segments.get(0);
                rows=db.getWritableDatabase().update(DatabaseHelper.employeeTable, values,DatabaseHelper.colID+"=?", new String []{empID});
               
            }
           
        }
        //update all emps in a certain dept
        else if(match==3 ||match==4||match==5)
        {
            List<String>segments=uri.getPathSegments();
            String deptName=segments.get(0);
            int DeptID=db.GetDeptID(deptName);
            rows=db.getWritableDatabase().update(db.employeeTable, values,db.colDept+"=?", new String []{String.valueOf(DeptID)});
           
        }
            return rows;
    }

}


Code for GridList.java which shows list of employees :

package mina.android.DatabaseDemo;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.database.Cursor;
import android.database.sqlite.SQLiteCursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

public class GridList extends Activity {
    DatabaseHelper dbHelper;
    static public GridView grid;
    TextView txtTest;
    Spinner spinDept1;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        setContentView(R.layout.gridview);
        grid=(GridView)findViewById(R.id.grid);
        txtTest=(TextView)findViewById(R.id.txtTest);
        spinDept1=(Spinner)findViewById(R.id.spinDept1);
        
        Utilities.ManageDeptSpinner(this.getParent(),spinDept1);
        final DatabaseHelper db=new DatabaseHelper(this);
        try
        {
         
         spinDept1.setOnItemSelectedListener(new OnItemSelectedListener() {
             
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                // TODO Auto-generated method stub
                LoadGrid();
                //sca.notifyDataSetChanged();
               
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
               
            }
        });
       
        }
        catch(Exception ex)
        {
            txtTest.setText(ex.toString());
        }
        
        
       
        try
        {
        grid.setOnItemClickListener(new OnItemClickListener()
        {

            @Override
            public void onItemClick(AdapterView<?> parent, View v, int position,
                    long id) {
                // TODO Auto-generated method stub
                try
                {
           
                SQLiteCursor cr=(SQLiteCursor)parent.getItemAtPosition(position);
                String name=cr.getString(cr.getColumnIndex(DatabaseHelper.colName));
                int age=cr.getInt(cr.getColumnIndex(DatabaseHelper.colAge));
                String Dept=cr.getString(cr.getColumnIndex(DatabaseHelper.colDeptName));
                Employee emp=new Employee(name, age,db.GetDeptID(Dept));
                emp.SetID((int)id);
                AlertDialog diag= Alerts.ShowEditDialog(GridList.this,emp);
                diag.setOnDismissListener(new OnDismissListener() {
                   
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        // TODO Auto-generated method stub
                        txtTest.setText("dismissed");
                        //((SimpleCursorAdapter)grid.getAdapter()).notifyDataSetChanged();
                        LoadGrid();
                    }
                });
                diag.show();
                }
                catch(Exception ex)
                {
                    Alerts.CatchError(GridList.this, ex.toString());
                }
            }

           
        }
        );
        }
        catch(Exception ex)
        {
           
        }

    }
    
    @Override
    public void onStart()
    {
        super.onStart();
        //LoadGrid();
    }
    
    public void LoadGrid()
    {
        dbHelper=new DatabaseHelper(this);
        try
        {
            //Cursor c=dbHelper.getAllEmployees();
            View v=spinDept1.getSelectedView();
            TextView txt=(TextView)v.findViewById(R.id.txtDeptName);
            String Dept=String.valueOf(txt.getText());
            Cursor c=dbHelper.getEmpByDept(Dept);
            startManagingCursor(c);
           
            String [] from=new String []{DatabaseHelper.colName,DatabaseHelper.colAge,DatabaseHelper.colDeptName};
            int [] to=new int [] {R.id.colName,R.id.colAge,R.id.colDept};
            SimpleCursorAdapter sca=new SimpleCursorAdapter(this,R.layout.gridrow,c,from,to);
            grid.setAdapter(sca);
           
           
           
        }
        catch(Exception ex)
        {
            AlertDialog.Builder b=new AlertDialog.Builder(this);
            b.setMessage(ex.toString());
            b.show();
        }
    }
   
}


Code for Alert.java

package mina.android.DatabaseDemo;


import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Spinner;
import android.widget.TextView;

public class Alerts {
public static void ShowEmpAddedAlert(Context con)
{
    AlertDialog.Builder builder=new AlertDialog.Builder(con);
    builder.setTitle("Add new Employee");
    builder.setIcon(android.R.drawable.ic_dialog_info);
    DialogListner listner=new DialogListner();
    builder.setMessage("Employee Added successfully");
    builder.setPositiveButton("ok", listner);
   
    AlertDialog diag=builder.create();
    diag.show();
}

public static AlertDialog ShowEditDialog(final Context con,final Employee emp)
{
    AlertDialog.Builder b=new AlertDialog.Builder(con);
    b.setTitle("Employee Details");
    LayoutInflater li=LayoutInflater.from(con);
    View v=li.inflate(R.layout.editdialog, null);
   
    b.setIcon(android.R.drawable.ic_input_get);
   
    b.setView(v);
    final TextView txtName=(TextView)v.findViewById(R.id.txtDelName);
    final TextView txtAge=(TextView)v.findViewById(R.id.txtDelAge);
    final Spinner spin=(Spinner)v.findViewById(R.id.spinDiagDept);
    Utilities.ManageDeptSpinner(con, spin);
    for(int i=0;i<spin.getCount();i++)
    {
        long id=spin.getItemIdAtPosition(i);
        if(id==emp.getDept())
        {
            spin.setSelection(i, true);
            break;
        }
    }
   
   
    txtName.setText(emp.getName());
    txtAge.setText(String.valueOf(emp.getAge()));
   
    b.setPositiveButton("Modify", new OnClickListener() {
       
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            emp.setName(txtName.getText().toString());
            emp.setAge(Integer.valueOf(txtAge.getText().toString()));
            emp.setDept((int)spin.getItemIdAtPosition(spin.getSelectedItemPosition()));
           
            try
            {
            DatabaseHelper db=new DatabaseHelper(con);
            db.UpdateEmp(emp);
           
            }
            catch(Exception ex)
            {
                CatchError(con, ex.toString());
            }
        }
    });
   
    b.setNeutralButton("Delete", new OnClickListener() {
       
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            DatabaseHelper db=new DatabaseHelper(con);
            db.DeleteEmp(emp);
        }
    });
    b.setNegativeButton("Cancel", null);
   
    return b.create();
    //diag.show();
   
}

static public void CatchError(Context con, String Exception)
{
    Dialog diag=new Dialog(con);
    diag.setTitle("Error");
    TextView txt=new TextView(con);
    txt.setText(Exception);
    diag.setContentView(txt);
    diag.show();
}


}


Code for Utility.java which to load data from database to spinner:

package mina.android.DatabaseDemo;


import android.content.Context;
import android.database.Cursor;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;

public class Utilities {
static public void ManageDeptSpinner(Context context,Spinner view)
{
    DatabaseHelper dbHelper=new DatabaseHelper(context);
    Cursor c=dbHelper.getAllDepts();
    //context.startManagingCursor(c);
   
   
   
    //SimpleCursorAdapter ca=new SimpleCursorAdapter(this,android.R.layout.simple_spinner_item, c, new String [] {DatabaseHelper.colDeptName}, new int []{android.R.id.text1});
    SimpleCursorAdapter ca=new SimpleCursorAdapter(context,R.layout.deptspinnerrow, c, new String [] {DatabaseHelper.colDeptName,"_id"}, new int []{R.id.txtDeptName});
    view.setAdapter(ca);
   
}
}


Code main.xml for tabhost: 







<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@android:id/tabhost"
   
    >
    <TabWidget
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@android:id/tabs"
    />
    <FrameLayout
    android:id="@android:id/tabcontent"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:paddingTop="60px"
   
    >
</FrameLayout>
</TabHost>



Code for listview.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">
  <ListView android:id="@+id/listEmps"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="A semi-random button"
/>
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    android:id="@+id/txt"
    />
</LinearLayout>

Code for gridview.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/tab1"
   
    >
    <TableLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TableRow>
    <Spinner
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/spinDept1"
    android:layout_span="3"
    />
    </TableRow>
    <TableRow>
    <TextView android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:text="Employee Name"
    android:layout_weight="1"
  
   
   
    />
    <TextView android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:text="Employee Age"
    android:layout_weight="1"
 
   
    />
    <TextView android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:text="Department"
    android:layout_weight="1"
 
   
    />
   
    </TableRow>
    </TableLayout>
    <GridView
    android:id="@+id/grid"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:numColumns="1"
    android:stretchMode="columnWidth"
    />
    <TextView android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:text="Employee Age"
      android:id="@+id/txtTest"   
 
   
    />
    </LinearLayout>


Code for gridrow.xml

<?xml version="1.0" encoding="utf-8"?>
<TableLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <TableRow>
  <TextView
  android:layout_width="50px"
  android:layout_height="wrap_content"
  android:id="@+id/colName"
  android:padding="5px"
  android:layout_weight="1"
 
 
  />
  <TextView
  android:layout_width="50px"
  android:layout_height="wrap_content"
  android:id="@+id/colAge"
  android:padding="5px"
  android:layout_weight="1"
 
  />
 
  <TextView
  android:layout_width="50px"
  android:layout_height="wrap_content"
  android:id="@+id/colDept"
  android:padding="5px"
  android:layout_weight="1"
 
  />

  </TableRow>
</TableLayout>

Code for editdialog.xml


<?xml version="1.0" encoding="utf-8"?>
<TableLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:orientation="vertical"
  >
  <TableRow>
  <TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Name: "
  />
  <EditText
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:id="@+id/txtDelName"
  />
  </TableRow>
  <TableRow>
  <TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Age: "
  />
  <EditText
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:id="@+id/txtDelAge"
  />

  </TableRow>
  <TableRow>
   <Spinner
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:id="@+id/spinDiagDept"
  android:layout_span="2"
  />
  </TableRow>
  <TableRow>
 
  </TableRow>
</TableLayout>




Code for deptspinnerrow.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:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:id="@+id/txtDeptName"
  android:textColor="#000"
  />
  <TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:id="@+id/txtDeptID"
  android:textColor="#000"
  />
</LinearLayout>


Code for addemployee.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="wrap_content"
  android:orientation="vertical"
  >
  <TextView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="Employee Name"
  />
  <EditText
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:id="@+id/txtName"
  android:autoText="false"
  />
  <TextView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="Employee Age"
 
  />
  <EditText
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:id="@+id/txtAge"
  android:inputType="number"
  android:digits="0123456789"
  android:singleLine="true"
  />
  <TextView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="Employee Dept"
 
  />
  <Spinner
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:id="@+id/spinDept"
  />
  <Button
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:id="@+id/btnAdd"
  android:text="Add Employee"
  android:onClick="btnAddEmp_Click"
  />
  <TextView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="Number of employees "
  android:id="@+id/txtEmps"
  />
</LinearLayout>