Friday, February 3, 2012

Binded Services in Android to access Server

Create DatabaseHelper class and create table. and queries related to it.


DBHelper.java

public class DatabaseHelper extends SQLiteOpenHelper  {

    int mStatus;
    String TAG="DatabaseHelper";
    private static final int DB_VERSION = 15;
    private static final String DB_NAME = "CursorDemo";
public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

public void onCreate(SQLiteDatabase db) {

db.execSQL("CREATE TABLE paypal_secondary_receivers(sp_profile_id varchar NOT NULL,"+
                "paypal_merchant_id varchar ,"+
                "email_id varchar ,"+
                "profile_type INTEGER ,"+
                "secondary_receiver_percentage float ,"+
                "delay_time_days INTEGER ,"+
                "merchant_street_address varchar ,"+
                "merchant_city varchar ,"+
                "merchant_country varchar ,"+
        "merchant_postcode varchar )");
}

/**
     * GetMerchantAccount Details
     */

    public Merchant getMerchantAccount(String profileid){
        Merchant merchant=null;
        SQLiteDatabase database = this.getWritableDatabase();


        Cursor data= database.query("paypal_secondary_receivers", new String[] {"sp_profile_id", "paypal_merchant_id","email_id",

                "merchant_street_address",
                "merchant_city",
                "merchant_country",
        "merchant_postcode"},new String("sp_profile_id"+"=?"),new String[]{profileid.toString()}, null, null, null);

        if (data!= null)
        {   

            if (data.moveToFirst()){

                do{

                    String sp_profileid=data.getString(data.getColumnIndex("sp_profile_id"));
                    String paypal_merchant_id=data.getString(data.getColumnIndex("paypal_merchant_id"));
                    String email_id=data.getString(data.getColumnIndex("email_id"));
                    //String profile_type=data.getString(data.getColumnIndex("profile_type"));
                    String merchant_street_address=data.getString(data.getColumnIndex("merchant_street_address"));
                    String merchant_city=data.getString(data.getColumnIndex("merchant_city"));
                    String merchant_country=data.getString(data.getColumnIndex("merchant_country"));
                    String merchant_postcode=data.getString(data.getColumnIndex("merchant_postcode"));
                    merchant=new Merchant();
                    merchant.sp_profile_id=sp_profileid;
                    merchant.email_id=email_id;
                    merchant.paypal_merchant_id=paypal_merchant_id;
                    merchant.merchant_street_address=merchant_street_address;
                    merchant.merchant_city=merchant_city;
                    merchant.merchant_country=merchant_country;
                    merchant.merchant_postcode=merchant_postcode;

                }while(data.moveToNext());

            }
            data.close();

            //database.close();
        }
        return merchant;
    }


ApplicationManager.java


String TAG="ApplicationManager";

    private DatabaseHelper mDBHelper;
    private NetworkManager mNWmgr;
    private Context mCtx;
    private static ApplicationManager mApplicationMgr;


    private ApplicationManager(Context context) {
        mCtx = context;
        mDBHelper =null;
        mNWmgr=null;

    }

    /**
     * getting Instance
     * @param context
     * @return DBAdapter
     */
    public static synchronized ApplicationManager getApplicationMgrInstance(Context context) {
        if (mApplicationMgr == null) {
            mApplicationMgr = new ApplicationManager(context);
        }
        return mApplicationMgr;
    }
/**
     *  method to get NetworkManager class instance
     *
     */

    public NetworkManager getNetworkManager()
    {
        if(mNWmgr==null)
        {
            mNWmgr=new NetworkManager(mCtx);
        }
        return mNWmgr;
    }
/**
     *  method to get DatabaseHelper class instance
     *
     */
    public DatabaseHelper getDbHelper()
    {
        if(mDBHelper==null)
        {
            mDBHelper=new DatabaseHelper(mCtx);
        }

        return mDBHelper;
    }

public Merchant getMerchantDetail(String key) {
        Log.d(TAG,"merchant detail called");
        if(mDBHelper==null)
        {
            mDBHelper=new DatabaseHelper(mCtx);
        }

        return mDBHelper.getMerchantAccount(key);
    }
}




BaseClass.java

/*which stores dilogs like session handling,checking network connection etc.


public class BaseClass extends Activity {

    private static String TAG="BaseClass";
    private Context mContext;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

    }
    void sessionTimeOut(Context ctx)
    {   
        mContext = ctx;
        AlertDialog.Builder dialog1 = new AlertDialog.Builder(mContext);
        dialog1.setTitle("ALERT");
        dialog1.setMessage("Session Timed OUT!Relogin");
        dialog1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog1, int id) {

                Intent i=new Intent(mContext,LoginInfo.class);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                mContext.startActivity(i);
                finish();
            }
        });
        dialog1.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {

                dialog.cancel();
            }
        });
        AlertDialog alert =dialog1.create();
        // Title for AlertDialog
        alert.setTitle("Session Expired");
        // Icon for AlertDialog
        alert.setIcon(R.drawable.icon);
        alert.show();
    }
    public void popIt(Context ctx, String title, String message ){
        mContext = ctx;
        AlertDialog.Builder dialog2 = new AlertDialog.Builder(mContext);
        dialog2.setTitle( title );
        dialog2.setMessage( message );
        dialog2.setPositiveButton("Ok", new OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                //do stuff onclick of YES
                }
        });
        AlertDialog alert =dialog2.create();
        // Title for AlertDialog
        alert.setTitle("");
        // Icon for AlertDialog
        alert.setIcon(R.drawable.icon);
        alert.show();
    }
    public void popError(Context ctx, String title, String message ){
        mContext = ctx;
        AlertDialog.Builder dialog3 = new AlertDialog.Builder(ctx);
        dialog3.setTitle( title );
        dialog3.setMessage( message );
        dialog3.setPositiveButton("Ok", new OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                //do stuff onclick of YES
            }
        });
        AlertDialog alert =dialog3.create();
        // Title for AlertDialog
        alert.setTitle(title);
        // Icon for AlertDialog
        alert.setIcon(R.drawable.icon);
        alert.show();

    }

    void showAlertNoConnection(Context ctx) {
        mContext = ctx;
        Log.i(TAG,"Entered base clas "+"no connection alert");
        AlertDialog.Builder dialog1 = new AlertDialog.Builder(mContext);
        dialog1.setTitle("ALERT");
        dialog1.setMessage("No Connection! Try Later");
        dialog1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog1, int id) {
                    finish();

            }
        });
        AlertDialog alert =dialog1.create();
        // Title for AlertDialog
        alert.setTitle("OUT OF CONNECTION");
        // Icon for AlertDialog
        alert.setIcon(R.drawable.icon);
        alert.show();

    }
}

merchant layout




merchnatac.xml


<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:background="@drawable/bk_gnd">
    <TextView android:id="@+id/pubprof_name" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:textSize="@dimen/menu_buttons_text_size"
        android:textColor="@color/menu_buttons" android:textStyle="bold"
        android:text="Merchant Account" android:gravity="center" />
    <TextView android:layout_width="fill_parent"
        android:layout_height="20dip" />
    <TableRow>
   
    <TextView android:text="Merchant id" android:id="@+id/emid"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:padding="5dip"
        android:textColor="@color/menu_buttons" />
        <EditText android:id="@+id/emidv" android:layout_width="150px"
                android:padding="3dip"
                android:background="@android:drawable/editbox_background"
                android:cursorVisible="true" android:typeface="normal"
                android:editable="true" />
                </TableRow>
                <TableRow>
        <TextView android:text="Email Id" android:id="@+id/editmail"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:padding="5dip"
        android:textColor="@color/menu_buttons" />
        <EditText android:id="@+id/editemail" android:layout_width="150px"
                 android:padding="3dip"
                android:background="@android:drawable/editbox_background"
                android:cursorVisible="true" android:typeface="normal"
                android:editable="true" />
                </TableRow>
                <TableRow>
        <TextView android:text="City" android:id="@+id/emcity"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:textColor="@color/menu_buttons"
        android:padding="5dip" />
        <EditText android:id="@+id/emcityv" android:layout_width="150px"
            android:padding="3dip"
                android:background="@android:drawable/editbox_background"
                android:cursorVisible="true" android:typeface="normal"
                android:editable="true" />
                </TableRow>
                <TableRow>
        <TextView android:text="Country" android:id="@+id/emcnt"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:padding="5dip"
        android:textColor="@color/menu_buttons" />
        <EditText android:id="@+id/emcntv" android:layout_width="150px"
                 android:padding="3dip"
                android:background="@android:drawable/editbox_background"
                android:cursorVisible="true" android:typeface="normal"
                android:editable="true" />
                </TableRow>
                <TableRow>
        <TextView android:text=" Street Address" android:id="@+id/estadd"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:padding="5dip"
        android:textColor="@color/menu_buttons" />
        <EditText android:id="@+id/estreet" android:layout_width="150px"
                 android:padding="3dip"
                android:background="@android:drawable/editbox_background"
                android:cursorVisible="true" android:typeface="normal"
                android:editable="true" />
                </TableRow>
                <TableRow>
        <TextView android:text="Postal Code" android:id="@+id/epc"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:padding="5dip"
        android:textColor="@color/menu_buttons"/>
        <EditText android:id="@+id/epostcode" android:layout_width="150px"
                 android:padding="3dip"
                android:background="@android:drawable/editbox_background"
                android:cursorVisible="true" android:typeface="normal"
                android:editable="true" />
                </TableRow>
                       
               
    <Button android:id="@+id/mdone" android:text="Done"
        android:textSize="@dimen/menu_buttons_text_size" android:textColor="@color/menu_buttons"
        android:textStyle="bold" android:gravity="center"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:layout_below="@id/upload_image" android:background="@drawable/button_menu" />
    <Button android:id="@+id/refresh1" android:text="Refresh"
        android:textSize="@dimen/menu_buttons_text_size" android:textColor="@color/menu_buttons"
        android:textStyle="bold" android:layout_gravity="center"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"

         android:background="@drawable/button_menu" />
</TableLayout>
</ScrollView>


MyMerchantAccount.java
//which displayes merchant details


/**
 * Class Name :MyMerchantAccount
 *
 * Parent Class :BaseClass
 *
 * Interfaces: None
 *
 * Description:This class displays Merchant Details like Paypal account details
 *
 */

public class MyMerchantAccount extends BaseClass {

    private static final String TAG="MyMerchantAccount";
    private EditText mMerchantId,mCity,mCountry,mEmail,mStreet,mPostal;
    private String mMerchantId1,mCity1,mCountry1,mEmail1,mStreet1,mPostal1;
    Button mDone,mRefresh;
    public static String mProfile_id;
    TextView mTxt;
    private ProgressDialog mProgDlg;
    boolean mIsBound;
    Merchant mMyMerchantAccount;
    private static ApplicationManager mAppMgr;
    private DatabaseHelper mDBHelper;
    private static final int INDETERMINATE = 0;
    private Context mContext;
    BaseClass mBaseClass = new BaseClass();

    final Messenger mMessenger = new Messenger(new IncomingHandler());
    Messenger mService = null;

    class IncomingHandler extends Handler {

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

        @Override
        public void handleMessage(Message msg) {

            Log.e(TAG,"UIAct "+"handleMessage for mymerchant");

            switch (msg.what) {

            case NetworkService.MSG_RETRIEVED_MERCHANT_ACCOUNT_DETAILS:
                String key = (String) msg.obj;
                Bundle b9 =msg.getData();
                String status=b9.getString("status");
                Log.i(TAG,"My Key handle msg of mymerchant status : "+status);


                if(status.equals("200")){
                    Log.i(TAG,"My Key handle msg of mymerchant key : "+key);
                    mMyMerchantAccount=mAppMgr.getMerchantDetail(key);
                    //doUnbindService();
                    //mProgDlg.dismiss();
                    mMerchantId1=mMyMerchantAccount.paypal_merchant_id;
                    mCity1=mMyMerchantAccount.merchant_city;
                    mCountry1=mMyMerchantAccount.merchant_country;
                    mEmail1=mMyMerchantAccount.email_id;
                    mStreet1=mMyMerchantAccount.merchant_street_address;
                    mPostal1=mMyMerchantAccount.merchant_postcode;
                    mMerchantId.setText(mMerchantId1);
                    mCity.setText(mCity1);
                    mCountry.setText(mCountry1);
                    mEmail.setText(mEmail1);
                    mStreet.setText(mStreet1);
                    mPostal.setText(mPostal1);
                    mProgDlg.dismiss();
                    doUnbindService();
                }

                else if(status.equals("408"))
                {

                    mBaseClass.sessionTimeOut(mContext);
               
                }

                else{
                    mProgDlg.dismiss();
                    setContentView(R.layout.nodata);
                    mTxt=(TextView) findViewById(R.id.nodata);
                    mTxt.setText("No Data Under this Profile!");
                    //doUnbindService();
                }

                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);
            Log.e(TAG,"binding to "+"service in ServiceConnection ");

            try {

                Message msg = Message.obtain(null, NetworkService.MSG_REGISTER_CLIENT);
                msg.replyTo = mMessenger;
                mService.send(msg);

                msg = Message.obtain(null, NetworkService.MSG_GET_MERCHANT_ACCOUNT);

                Bundle b1=new Bundle();
                b1.putString("profileid",mProfile_id);
                msg.setData(b1);
                Log.d(TAG,"connecting "+"for merchantaccountdetail");
                msg.replyTo = mMessenger;
                mService.send(msg);
            }


            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(TAG,"UIAct "+"onServiceDisconnected");
        }
    };

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mAppMgr = ApplicationManager.getApplicationMgrInstance(this.getApplicationContext());
        setContentView(R.layout.merchantac);
        mMerchantId=(EditText) findViewById(R.id.emidv);
        mCity=(EditText) findViewById(R.id.emcityv);
        mCountry=(EditText) findViewById(R.id.emcntv);
        mEmail=(EditText) findViewById(R.id.editemail);
        mStreet=(EditText) findViewById(R.id.estreet);
        mPostal=(EditText) findViewById(R.id.epostcode);
        mDone=(Button) findViewById(R.id.mdone);
        mRefresh=(Button) findViewById(R.id.refresh1);
        mContext=this;

        Intent ip = getIntent();

        mProfile_id=(String) ip.getCharSequenceExtra("profileid");
        Log.d(TAG,"profile id is : "+mProfile_id);
        mMyMerchantAccount=mAppMgr.getMerchantDetail(mProfile_id);

        if(mMyMerchantAccount==null)
        {

            if (NetworkUtilService.getInstance(this).isOnline(this)) {

                Log.e(TAG,"binding to "+"service for merchant account details");
                doBindService();
                //    bindService(new Intent(this, NetworkService.class), mConnection, Context.BIND_AUTO_CREATE);
                showDialog(INDETERMINATE);

            } else { 

                ShowAlertNoConnection();

            }

        }
        else
        {
            mMerchantId1=mMyMerchantAccount.paypal_merchant_id;
            mCity1=mMyMerchantAccount.merchant_city;
            mCountry1=mMyMerchantAccount.merchant_country;
            mEmail1=mMyMerchantAccount.email_id;
            mStreet1=mMyMerchantAccount.merchant_street_address;
            mPostal1=mMyMerchantAccount.merchant_postcode;
            mMerchantId.setText(mMerchantId1);
            mCity.setText(mCity1);
            mCountry.setText(mCountry1);
            mEmail.setText(mEmail1);
            mStreet.setText(mStreet1);
            mPostal.setText(mPostal1);
           

        }

        if(EditAccount.mCurrentview==Globals.EDIT_ACCOUNT)

        {
            doBindService();
            showDialog(INDETERMINATE);
            mDone.setVisibility(View.VISIBLE);
            mRefresh.setVisibility(View.GONE);

        }

        else
        {

            mDone.setVisibility(View.GONE);

        }

        mDone.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {

                EditAccount.mCurrentview=Globals.EDIT_ACCOUNT;
                Intent ip = getIntent();
                String profileid1=(String) ip.getCharSequenceExtra("profileid");
                Log.e(TAG,"profileid1 : "+profileid1);
                mMyMerchantAccount.paypal_merchant_id=mMerchantId.getText().toString();
                mMyMerchantAccount.merchant_city=mCity.getText().toString();
                mMyMerchantAccount.merchant_country=mCountry.getText().toString();
                mMyMerchantAccount.email_id=mEmail.getText().toString();
                mMyMerchantAccount.merchant_street_address=mStreet.getText().toString();
                Log.e(TAG,"mMyMerchantAccount.email_id in DONE button "+mMyMerchantAccount.email_id);
                mMyMerchantAccount.merchant_postcode=mPostal.getText().toString();
                Intent resultIntent=new Intent(MyMerchantAccount.this,EditAccount.class);

                Bundle b=new Bundle();
                b.putParcelable("merchantdetails",mMyMerchantAccount);
                resultIntent.putExtra("mdetails",b);
                setResult(RESULT_OK, resultIntent);
                finish();

            }

        });

        mRefresh.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                Boolean connected = networkInfo != null    && networkInfo.isAvailable() && networkInfo.isConnected();
                Log.d(TAG,"connection "+connected);

                if (connected)
                {
                    Log.e(TAG,"button 1 clicked");
                    Log.e(TAG,"binding to "+"service for transactiondetails in refresh");
                    doBindService();
                    //bindService(new Intent(MyTransactions.this, NetworkService.class), mConnection, Context.BIND_AUTO_CREATE);
                    showDialog(INDETERMINATE);
                    //doUnbindService();
                }

                else
                {

                    ShowAlertNoConnection();
                }

            }

        });
    }

    protected void ShowAlertNoConnection() {
        AlertDialog.Builder dialog1 = new AlertDialog.Builder(MyMerchantAccount.this);
        dialog1.setTitle("ALERT");
        dialog1.setMessage("No Connection! Try Later");
        dialog1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog1, int id) {

                MyMerchantAccount.this.finish();
                //dialog1.cancel();
            }
        });
        AlertDialog alert =dialog1.create();
        // Title for AlertDialog
        alert.setTitle("OUT OF CONNECTION");
        // Icon for AlertDialog
        alert.setIcon(R.drawable.icon);
        alert.show();

    }
    void doBindService() {
        // Establish a connection with the service.  We use an explicit
        // class name because there is no reason to be able to let other
        // applications replace our component.
        bindService(new Intent(MyMerchantAccount.this,
                NetworkService.class), mConnection, Context.BIND_AUTO_CREATE);
        mIsBound = true;

    }

    void doUnbindService() {
        if (mIsBound) {
            // If we have received the service, and hence registered with
            // it, then now is the time to unregister.
            if (mService != null) {

                try {
                    Message msg = Message.obtain(null,
                            NetworkService.MSG_UNREGISTER_CLIENT);
                    msg.replyTo = mMessenger;
                    mService.send(msg);
                } catch (RemoteException e) {
                    // There is nothing special we need to do if the service
                    // has crashed.
                }
            }

            // Detach our existing connection.
            unbindService(mConnection);
            mIsBound = false;

        }
    }

    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;
    }

    @Override
    public void onDestroy() {
        Log.i(TAG,"onDestroy Called");
        super.onDestroy();
        try {
            unbindService(mConnection);
        } catch (Throwable t) {

        }
    }

}


NetworkService.java

public class NetworkService extends Service {
    private static boolean mIsRunning = false;


    private static ApplicationManager mAppMgr;
    RegistrationRes mRes1;
    NetworkManager mNtwMngr;
    ArrayList<Phnos > mPhnolist;
    String TAG="NetworkService";
// Target we publish for clients to send messages to IncomingHandler.
    final Messenger mMessenger = new Messenger(new IncomingHandler());

    //constants
    public static final int MSG_REGISTER_CLIENT = 1;
    public static final int MSG_UNREGISTER_CLIENT = 2;
public static final int MSG_GET_MERCHANT_ACCOUNT=117;
    public static final int MSG_RETRIEVED_MERCHANT_ACCOUNT_DETAILS=36;

private    String mProfileid;

    int mLogin;
    int mCatv=0;





    @Override
    public IBinder onBind(Intent intent) {
        mAppMgr = ApplicationManager.getApplicationMgrInstance(this.getApplicationContext());
        mNtwMngr=mAppMgr.getNetworkManager();
        Log.e(TAG, "OnBind is called for intent" + intent.describeContents());
        return mMessenger.getBinder();
    }

    /**
     * Class Name :IncomingHandler
     *
     * Parent Class :Handler
     *
     * Interfaces: None
     *
     * Description:Handler class for handling
     *
     *  incoming messages from client

     */

class IncomingHandler extends Handler {
        // Handler of incoming messages from clients.
        /**
         * Callback method to handle messages coming from client
         *
         */
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MSG_REGISTER_CLIENT:
                mClients.add(msg.replyTo);
                Log.e(TAG,"client "+"added");
                break;
            case MSG_UNREGISTER_CLIENT:
                mClients.remove(msg.replyTo);
                Log.e(TAG,"client "+"removed");
                break;
               case MSG_GET_MERCHANT_ACCOUNT:
                Bundle b11 = msg.getData();

                final String key11 = b11.getString("profileid");
                Log.e(TAG,"My Merchant Key handle msg"+key11);
                String status11=null;
                try {
                    status11 = mNtwMngr.getMyMerchantAccountDetailsFromServer(key11);
                } catch (Exception e2) {
                    // TODO Auto-generated catch block
                    e2.printStackTrace();
                }

                sendMessageToClient11(MSG_RETRIEVED_MERCHANT_ACCOUNT_DETAILS,key11,status11);


                break;

default:
                super.handleMessage(msg);
            }
        }
  



}

private void sendMessageToClient11(int intvaluetosend,String key,String status ) {
        for (int i=mClients.size()-1; i>=0; i--) {
            try {
                // Send data as an Integer
                Message msg = Message.obtain(null,MSG_RETRIEVED_MERCHANT_ACCOUNT_DETAILS,key);
                Log.e(TAG,"servermsg in sending msg to client for mysps"+key);
                Bundle b5=new Bundle();
                b5.putString("status",status);
                Log.e(TAG,"status "+status);
                msg.setData(b5);
                mClients.get(i).send(msg);


            } catch (RemoteException e) {
                // The client is dead. Remove it from the list; we are going through the list from back to front so this is safe to do inside the loop.
                mClients.remove(i);
            }
        }
    }


NetworkManager.java


public class NetworkManager {

public NetworkManager(Context context) {

        mCtx = context;

        mAppMgr = ApplicationManager.getApplicationMgrInstance(mCtx);

    }

String getMyMerchantAccountDetailsFromServer(final String key) throws Exception {
        mDBHelper =mAppMgr.getDbHelper();
        String MyMerchantAcctDetail=CustomHttpClient.executeHttpGet(Configure.SM_SERVER_URL_PREFIX+"merchantDetails?profile_id="+key+"&client_type=mc&catalog_version_id=0");
        String status=JSONSMParser.parseStatus(MyMerchantAcctDetail);
        Log.d(TAG,MyMerchantAcctDetail);
        if(status.equals("200")){
            mMyMerchantAcctDetail=JSONSMParser.parseMyMerchantAcctDetail(MyMerchantAcctDetail);
            createMyMerchantAcctDetail(mDBHelper,key);
            Log.e(TAG,"mysubscriberdetails");
            return status;
        }
        else if(status.equals("408"))
        {
            return status;
        }
        else
            return status;

    }

private void createMyMerchantAcctDetail(DatabaseHelper mDBHelper,String key) {
        // TODO Auto-generated method stub
        SQLiteDatabase database = mDBHelper.getWritableDatabase();

        ContentValues acctdetail= new ContentValues();
        String pay_merchant_id=mMyMerchantAcctDetail.paypal_merchant_id;
        Log.d(TAG,"paymerchatid "+ pay_merchant_id);
        String merchant_city=mMyMerchantAcctDetail.merchant_city;
        String merchat_country=mMyMerchantAcctDetail.merchant_country;
        String email_id=mMyMerchantAcctDetail.email_id;
        String merchant_postcode=mMyMerchantAcctDetail.merchant_postcode;
        String merchant_street_address=mMyMerchantAcctDetail.merchant_street_address;
        Log.d(TAG,"merchant_street_address : "+ merchant_street_address);
        acctdetail.put("sp_profile_id", key);
        acctdetail.put("paypal_merchant_id", pay_merchant_id);
        acctdetail.put("email_id", email_id);
        acctdetail.put("merchant_city", merchant_city);
        acctdetail.put("merchant_country", merchat_country);
        acctdetail.put("merchant_street_address", merchant_street_address);
        acctdetail.put("merchant_postcode", merchant_postcode);


        database.insert("paypal_secondary_receivers",null,acctdetail);

    }

//follwoing method to post the data to server example

/**
     * change password
     */
    public String getchangepassword(final String key_existingpass, final String key_newpass,final String key_newrepass,final String profileid) throws Exception {
        Log.e(TAG,"expass "+key_existingpass);
        Log.e(TAG,"newpass "+key_newpass);
        Log.e(TAG,"newrepass "+key_newrepass);
        Log.e(TAG,"id "+profileid);
        String mRes=null;
        ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();

        postParameters.add(new BasicNameValuePair("existing_password", key_existingpass));
        postParameters.add(new BasicNameValuePair("new_password", key_newpass ));
        postParameters.add(new BasicNameValuePair("confirm_password",key_newrepass));
        postParameters.add(new BasicNameValuePair("profileId",profileid));
        postParameters.add(new BasicNameValuePair("client_type", "mc"));

        mDBHelper =mAppMgr.getDbHelper();

        String response = CustomHttpClient.executeHttpPost2(Configure.SM_SERVER_URL_PREFIX+"changepass", postParameters);
        Log.i(TAG,response);
        String status=JSONSMParser.parseStatus(response);
        if(status.equals("200")){
            return status;
        }
        else
            return status;

    }


 JSONSMParser.java

public class JSONSMParser{


/**
     *  method to parse login status coming from server
     *
     */
    public static String parseStatus(String jsonString) {
        String login_statuscode=null;
        String status_msg=null;

        try {
            JSONObject jObject = new JSONObject(jsonString);

            login_statuscode=jObject.getString("status_code");
            status_msg=jObject.getString("status_msg");

            Log.d(TAG,"login status "+jObject.getString("status_code"));
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
        return login_statuscode;
    }

public static Merchant parseMyMerchantAcctDetail(String myMerchantAcctDetail) {
        /*{"merchantAccountBean":["ssell_1316531348_biz@inceptionitsystems.com",
              "Hyderabad","India","naresh.mogili@gmail.com","5000082",
              "Banjara Hils"]}*/
        Merchant m = new Merchant();

        try {


            JSONObject jObject = new JSONObject(myMerchantAcctDetail);
            JSONArray menuitemArray1 = jObject.getJSONArray("merchantAccountBean");

            for(int i=0;i<menuitemArray1.length();i++){

                m.paypal_merchant_id=menuitemArray1.getString(i);
                Log.e(TAG,"paypal merchant id "+m.paypal_merchant_id);
                m.email_id=menuitemArray1.getString(++i);
                m.merchant_street_address=menuitemArray1.getString(++i);
                m.merchant_city=menuitemArray1.getString(++i);
                m.merchant_country=menuitemArray1.getString(++i);

                m.merchant_postcode=menuitemArray1.getString(++i);


            }

        }
        catch (JSONException e) {
            e.printStackTrace();
        }
        return m;






    }

}


CustomHttpClient.java

package com.inception.network;

/**
 * Class Name : CustomHttpClient
 *
 * Parent Class :
 *
 * Interfaces: None
 *
 * Description: Handles Http get and post.
 *
 */
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import java.net.HttpURLConnection;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;

import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;


import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.util.Log;

public class CustomHttpClient {
    /** The time it takes for our client to timeout */
    public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds

    /** Single instance of our HttpClient */
    private static HttpClient mHttpClient;
    private static HttpContext mHttpContext;
    private static Bitmap bitmap;

    public static Cookie mSessionCookie;

    static String TAG="CustomHttpClient";

    /**
     * Get our single instance of our HttpClient object.
     *
     * @return an HttpClient object with connection parameters set
     */
    public static HttpClient getHttpClient() {
        if (mHttpClient == null) {
            mHttpClient = new DefaultHttpClient();
            final HttpParams params = mHttpClient.getParams();

            HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
            HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
            ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
        }
        return mHttpClient;
    }
   
    private static HttpContext getHttpContext(){
        if(mHttpContext==null){
            mHttpContext=new BasicHttpContext();
        }
        return mHttpContext;
    }
   
    private static String connect(String url){


        HttpClient client = getHttpClient();

        HttpGet httpget = new HttpGet(url);

        httpget.getAllHeaders();
        HeaderElementIterator it1 = new BasicHeaderElementIterator(
                httpget.headerIterator());
        System.out.println(httpget.getURI());

        while (it1.hasNext()) {
            HeaderElement elem = it1.nextElement();
            System.out.println("session name"+elem.getName() + " = " + elem.getValue());
            NameValuePair[] params = elem.getParameters();
            for (int i = 0; i < params.length; i++) {
                System.out.println(" " + params[i]);
            }
        }
        // Execute the request
        HttpResponse response;

        // return string
        String returnString = null;

        try {

            // Open the webpage.
            response =client.execute(httpget);

            //        if(response.getStatusLine().getStatusCode() == 200){
            if(true) {
                // Connection was established. Get the content.

                HttpEntity entity = response.getEntity();
                //SetCookie c=new Cookie();
                //SetCookie.setValue(mSessionId);
                response.getAllHeaders();
                Log.e("headers",""+response.getAllHeaders());
                HeaderElementIterator it = new BasicHeaderElementIterator(
                        response.headerIterator());
                while (it.hasNext()) {
                    HeaderElement elem = it.nextElement();
                    System.out.println(elem.getName() + " = " + elem.getValue());
                    NameValuePair[] params = elem.getParameters();
                    for (int i = 0; i < params.length; i++) {
                        System.out.println(" " + params[i]);
                    }
                }
                // If the response does not enclose an entity, there is no need
                // to worry about connection release

                if (entity != null) {
                    // A Simple JSON Response Read
                    InputStream instream = entity.getContent();

                    // Load the requested page converted to a string into a JSONObject.
                    //    JSONObject myAwway = new JSONObject(convertStreamToString(instream));
                    returnString = convertStreamToString(instream);
                    //    Log.e(TAG,"instream  : "+convertStreamToString(instream));
                    //        Log.e(TAG,"myawway  : "+ myAwway);

                    // Get the query value'
                    //String query = myAwway.getString("query");
                    //    JSONObject menuObject =myAwway.getJSONObject("photos");
                    // Make array of the suggestions
                    //        JSONArray suggestions =menuObject.getJSONArray("photo");

                    // Build the return string.
                    //                    returnString = "Found: " + suggestions.length() ;
                    //                for (int i = 0; i < suggestions.length(); i++) {
                    //                    returnString += "\n\t" +(suggestions.getJSONObject(i).getString("id").toString());
                    //                }
                    //    returnString = "Found";
                    // Cose the stream.
                    instream.close();

                }
            }
            else {
                // code here for a response othet than 200.  A response 200 means the webpage was ok
                // Other codes include 404 - not found, 301 - redirect etc...
                // Display the response line.
                returnString = "Unable to load page - " + response.getStatusLine();
            }
            return returnString ; 
        }
        catch (IOException  ex) {
            // thrown by line 80 - getContent();
            // Connection was not established
            returnString = "Connection failed; " + ex.getMessage();
        }
        //        catch (JSONException ex){
        // JSON errors
        //            returnString = "JSON failed; " + ex.getMessage();
        //        }
        return returnString;
    }

    private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {

                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Log.e("sb string   : ",""+ sb.toString());
        return sb.toString();
    }
    /**
     * Performs an HTTP Post request to the specified url with the
     * specified parameters.
     *
     * @param url The web address to post the request to
     * @param postParameters The parameters to send via the request
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            // Create a local instance of cookie store
            CookieStore cookieStore = new BasicCookieStore();
            // Create local HTTP context
            HttpContext localContext=getHttpContext();
            // Bind custom cookie store to the local context
            localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

            HttpPost request = new HttpPost(url);

            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
            Log.e( "postParameters",""+ postParameters);
            Log.e("formEntity",""+formEntity);

            /*    MultipartEntity entity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.JPEG, 100, bos);
            byte[] data = bos.toByteArray();
            entity.addPart("returnformat", new StringBody("json"));
            entity.addPart("uploaded", new ByteArrayBody(data,
                    "myImage.jpg"));*/
            request.setEntity(formEntity);
            HttpResponse response = client.execute(request,localContext);
            //HttpResponse response = client.execute(request);
            Log.e("headers",""+response.headerIterator());
            //String mSessionId=null;
            //  Log.e("mSessionId",""+mSessionId);
            HeaderElementIterator it = new BasicHeaderElementIterator(
                    response.headerIterator());
            while (it.hasNext()) {
                HeaderElement elem = it.nextElement();
                System.out.println(elem.getName() + " = " + elem.getValue());
                if(elem.getName().equals("JSESSIONID")){
                    NetworkManager.mSessionId=elem.getValue();
                }
                NameValuePair[] params = elem.getParameters();
                for (int i = 0; i < params.length; i++) {
                    System.out.println(" " + params[i]);
                }
            }


            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            List<Cookie> cookies = cookieStore.getCookies();
            Log.e("CustomHttpClient","Cookies size= " + cookies.size());
            for (int i = 0; i < cookies.size(); i++) {
                Cookie cookie = cookies.get(i);
                Log.e("CustomHttpClient","Local cookie: " + cookie);
                mSessionCookie = cookie;
                Log.e("CustomHttpClient",""+cookie.getValue());
            }

            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static String executeHttpPost2(String url, ArrayList<NameValuePair> postParameters) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            // Create a local instance of cookie store
            //CookieStore cookieStore = new BasicCookieStore();
            // Create local HTTP context
            HttpContext localContext=getHttpContext();
            // Bind custom cookie store to the local context
            //localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

            HttpPost request = new HttpPost(url);

            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
            Log.e( "postParameters",""+ postParameters);
            Log.e("formEntity",""+formEntity);

            /*    MultipartEntity entity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.JPEG, 100, bos);
            byte[] data = bos.toByteArray();
            entity.addPart("returnformat", new StringBody("json"));
            entity.addPart("uploaded", new ByteArrayBody(data,
                    "myImage.jpg"));*/
            request.setEntity(formEntity);
            HttpResponse response = client.execute(request,localContext);
            //HttpResponse response = client.execute(request);
            Log.e("headers",""+response.headerIterator());
            //String mSessionId=null;
            //  Log.e("mSessionId",""+mSessionId);
            HeaderElementIterator it = new BasicHeaderElementIterator(
                    response.headerIterator());
            while (it.hasNext()) {
                HeaderElement elem = it.nextElement();
                System.out.println(elem.getName() + " = " + elem.getValue());
                if(elem.getName().equals("JSESSIONID")){
                    NetworkManager.mSessionId=elem.getValue();
                }
                NameValuePair[] params = elem.getParameters();
                for (int i = 0; i < params.length; i++) {
                    System.out.println(" " + params[i]);
                }
            }


            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            /* List<Cookie> cookies = cookieStore.getCookies();
            Log.e("CustomHttpClient","Cookies size= " + cookies.size());
            for (int i = 0; i < cookies.size(); i++) {
                Cookie cookie = cookies.get(i);
                Log.e("CustomHttpClient","Local cookie: " + cookie);
                mSessionCookie = cookie;
                Log.e("CustomHttpClient",""+cookie.getValue());
            }*/

            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static String executeHttpPost1(String url,ArrayList<NameValuePair> postParameters ) throws Exception {
        HttpPost post = new HttpPost(url);

        Bitmap bitmap; 
        String Result_STR=null;
        HttpClient client = getHttpClient();
        HttpContext localContext=getHttpContext();
        HttpEntity resmarkMessagesReadFrom =null;
        MultipartEntity reqmarkMessagesReadFrom = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        try {
            Log.e(TAG+"postParameters.size()",""+postParameters.size());
            for(int i=0;i<postParameters.size();i++){
                Log.e(TAG+"parameters",""+postParameters.get(i).getName()+""+postParameters.get(i).getValue());

                if(postParameters.get(i).getName().equals("spProfilePic")){
                    bitmap = BitmapFactory.decodeFile(postParameters.get(i).getValue()); 

                    // you can change the format of you image compressed for what do you want; 
                    //now it is set up to 640 x 480; 

                    Bitmap bmpCompressed = Bitmap.createScaledBitmap(bitmap, 640, 480, true); 
                    ByteArrayOutputStream bos = new ByteArrayOutputStream(); 

                    // CompressFormat set up to JPG, you can change to PNG or whatever you want; 

                    bmpCompressed.compress(CompressFormat.JPEG, 100, bos); 
                    byte[] data = bos.toByteArray();
                    Log.e(TAG,"data"+data);     
                    reqmarkMessagesReadFrom.addPart(postParameters.get(i).getName(), new ByteArrayBody(data, "temp.jpg")); 
                    Log.e(TAG,"bitmap"+bitmap);     

                }
                else
                    reqmarkMessagesReadFrom.addPart(postParameters.get(i).getName(), new StringBody(postParameters.get(i).getValue()));


            }
            post.setEntity(reqmarkMessagesReadFrom);
            Log.e(TAG,"after for loop"+post.getEntity());
            HttpResponse response = client.execute(post,localContext);
            Log.e("headers",""+response.getAllHeaders());
            resmarkMessagesReadFrom = response.getEntity();
            if (resmarkMessagesReadFrom != null) {
                Result_STR=EntityUtils.toString(resmarkMessagesReadFrom);
                // mMSGBox.setText(Result_STR);
            }
        }
        catch(Exception e){
            Log.e(TAG,e.toString());
        }
        finally {

        }

        return Result_STR;
    }


    /**
     * Performs an HTTP GET request to the specified url.
     *
     * @param url The web address to post the request to
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpGet(String url) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpGet request = new HttpGet();
            HttpContext localContext=getHttpContext();
            request.setURI(new URI(url));
            HttpResponse response = client.execute(request,localContext);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            Log.e("headers",""+response.headerIterator());
            //String mSessionId=null;
            //  Log.e("mSessionId",""+mSessionId);
            HeaderElementIterator it = new BasicHeaderElementIterator(
                    response.headerIterator());
            while (it.hasNext()) {
                HeaderElement elem = it.nextElement();
                System.out.println(elem.getName() + " = " + elem.getValue());
                if(elem.getName().equals("JSESSIONID")){
                    NetworkManager.mSessionId=elem.getValue();
                }
                NameValuePair[] params = elem.getParameters();
                for (int i = 0; i < params.length; i++) {
                    System.out.println(" " + params[i]);
                }
            }

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

for abouve Customhttp class use commons-io-2.0.1.jar & httpmime-4.1-beta1.jar

Thursday, February 2, 2012

implementing search in Android without SearchManger and contentprovider

create table in your DBHelper class with following table.

private static final int DB_VERSION = 15;
    private static final String DB_NAME = "CursorDemo";

    public static final String TABLE_CATLOGS = "catalog2";
    public static final String CAT_ID = "_id";
    public static final String CAT_NAME = "category_name";
    public static final String PARENT_ID = "parent_id";
    public static final String IS_LEAF = "is_leaf";
    public static final String CAT_VERSION = "catalog_version";
    public static final String CAT_URL = "category_url";
    public static final String CAT_IMG = "category_img";


    private static final String CREATE_TABLE_CATLOG = "create table "
        + TABLE_CATLOGS + " (" + CAT_ID
        + " VARCHAR primary key , " + CAT_NAME
        + " text not null, " + PARENT_ID + " VARCHAR, " + IS_LEAF
        + " integer, " + CAT_VERSION + " integer, "+ CAT_URL
        + " varchar, "+ CAT_IMG + " blob);";

searchAct.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
>
<LinearLayout android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:orientation="horizontal"
               android:layout_margin="5dip">
             
              <EditText
               android:id="@+id/searchtext"
               android:layout_width="fill_parent"
               android:layout_height="wrap_content"/>
              
             <!--  <Button android:id ="@+id/srchbtn"
              android:layout_width="wrap_content"
              android:layout_height="50dip"
              android:textStyle="bold"
              android:textSize="20sp"
              android:text="Search"/>  -->
             
</LinearLayout>

    <ListView android:id="@+id/searchlist"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              >
    </ListView>
    <ListView android:id="@+id/searchlist1"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:layout_weight="1">
    </ListView>
       
</LinearLayout>


searchAct.java

package com.inception.smui;

/**
 * Class Name :SearchAct
 * 
 * Parent Class :Activity
 * 
 * Interfaces: None
 * 
 * Description:It will search Catalogs and SubCatalogs
 */

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

import com.ServiceMessenger.R;

import com.inception.dataparser.Category;
import com.inception.dataprovider.DatabaseHelper;
import com.inception.sm.ApplicationManager;
import com.inception.sm.MyAppContext;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class SearchAct extends Activity {

    private static String TAG="SearchAct";
    private static ApplicationManager mAppMgr;
    private DatabaseHelper mDBHelper;
    private Context mContext;
    private Cursor mCursor;
    private SimpleCursorAdapter mAdapter;
    private SQLiteDatabase mDb;
    private Activity mActivity;

    //widgets
    private ListView mListView1;
    private ListView mListView2;
    private EditText mEditText; 

    private String[] mCol={DatabaseHelper.CAT_NAME};
    private int[] to={R.id.text1};
    private boolean mInit = false;
    private ArrayList<Category> mCatPathList = new ArrayList<Category>();
    private ArrayList<Category> mList1 = new ArrayList<Category>();
    private ArrayList<Category> mCatList = new ArrayList<Category>();
    private ArrayList<Category> mResults;
    private SearchableAdapter adapter = null; 
    Category c=null;
    MyAppContext mAppctx;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.searchact);

        mListView1 = (ListView)findViewById(R.id.searchlist);
        mListView2 = (ListView)findViewById(R.id.searchlist1);
        mEditText = (EditText)findViewById(R.id.searchtext);
        mEditText.addTextChangedListener(watcher);
        mContext = this;
        mDBHelper = new DatabaseHelper(mContext);
        mAppMgr = ApplicationManager.getApplicationMgrInstance(this.getApplicationContext());
        mAppctx = (MyAppContext)getApplicationContext();
        mActivity = this;
        mListView1.setOnItemClickListener(listItemClickListener1);
        mListView2.setOnItemClickListener(listItemClickListener2);
        mDb = mDBHelper.getReadableDatabase();
       
        /*
         * cursor to get Total number of Catalog present. 
         */
       
        mCursor = mDb.query("catalog2", new String[] {DatabaseHelper.CAT_ID,DatabaseHelper.CAT_NAME},null ,null,null,null,null,null);
        int count = mCursor.getCount();
        Log.d(TAG,"cursor size "+ count);
        mResults = new ArrayList<Category>();
        if (mCursor != null)
        {

            if (mCursor.moveToFirst())
            {
                do
                {
                    String catId = mCursor.getString(mCursor.getColumnIndex(DatabaseHelper.CAT_ID));
                    String catagoryName = mCursor.getString(mCursor.getColumnIndex(DatabaseHelper.CAT_NAME));
                    c=new Category();
                    c.category_name=catagoryName;
                    Log.d(TAG,"catagoryName "+catagoryName);
                    c.category_id=catId;
                    mResults.add(c);
                } while (mCursor.moveToNext());
            }
            //mCursor.close();
        }
        mCursor.moveToFirst();
        mCatList = prepareCatlogList();
        Log.d(TAG,"Catloglist size "+mCatList.size());

        mAdapter = new SimpleCursorAdapter(mActivity,R.layout.searchrow, mCursor, mCol,to);
        mListView1.setAdapter(mAdapter);
        mInit = true;
        mDb.close();
    }

   
    AdapterView.OnItemClickListener listItemClickListener1 = new AdapterView.OnItemClickListener(){

        public void onItemClick(AdapterView<?> arg0, View v, int position,
                long id) {
            Log.d(TAG,"position "+position);
            c=new Category();
            String catid=mCatList.get(position).getCategory_id();
            Log.d(TAG,"cat_id "+catid);
            c=mAppMgr.getCategoryObjectFromId(catid);
            String isleaf = c.getIs_leaf();
            String cat_id=c.getCategory_id();
            Log.e(TAG,"isleaf:"+isleaf);
           
            if(isleaf.equals("false"))
            {
                Intent i=new Intent(mContext,SubCategoryMenu.class);
                Log.d(TAG,"false executed"+"Thanks");
                i.putExtra("cat", cat_id);
                startActivity(i);
            }
           
            else
            {
                Intent i=new Intent(mContext,ProfilesList.class);
                Log.d(TAG,"true executed"+"Thanks");
                mAppctx.setCatId(cat_id);
                startActivity(i);
            }
        }

    };


    TextWatcher watcher = new TextWatcher()
    {

        public void afterTextChanged(Editable s) {
            mResults = new ArrayList<Category>();
            Log.d("MySearchableActivity","afterTextChanged text = "+s);

            System.gc();
            String word =  s.toString();
            Log.d("MySearchableActivity","keyEvent wordlength ="+word.length());
            Log.d("MySearchableActivity","keyEvent word="+word);


            mDb = mDBHelper.getReadableDatabase();
            if(mInit)
                mCursor.close();
            if(word.length()<1)
                mCursor = mDb.query("catalog2", new String[] {DatabaseHelper.CAT_ID,DatabaseHelper.CAT_NAME},null ,null,null,null,null,null);
            else
                mCursor = mDb.query("catalog2", new String[] {DatabaseHelper.CAT_ID,DatabaseHelper.CAT_NAME},"("+"category_name LIKE ?)" ,new String[] {"%"+word+"%"},null,null,null,null);
            Log.d("MySearchableActivity","cursor size "+ mCursor.getCount());
            if (mCursor != null)
            {

                if (mCursor.moveToFirst())
                {
                    do
                    {
                        String catId = mCursor.getString(mCursor.getColumnIndex(DatabaseHelper.CAT_ID));
                        String catagoryName = mCursor.getString(mCursor.getColumnIndex(DatabaseHelper.CAT_NAME));
                        c=new Category();
                        c.category_name=catagoryName;
                        Log.e(TAG,"catagoryName "+catagoryName);
                        c.category_id=catId;
                        mResults.add(c);

                    } while (mCursor.moveToNext());
               
                }
                //mCursor.close();
            }

            mCursor.moveToFirst();
            mCatPathList = prepareCatlogPath();
            Log.d(TAG,"mCatPathList size"+mCatPathList.size());

            adapter = new SearchableAdapter(mContext,mCatPathList);
            mListView2.setAdapter(adapter);
            mInit = true;
            mDb.close();


        }

        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            Log.d("MySearchableActivity","beforeTextChanged text = "+s);

        }

        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            Log.d("MySearchableActivity","onTextChanged text = "+s);

        }

    };
   
    AdapterView.OnItemClickListener listItemClickListener2 = new AdapterView.OnItemClickListener(){

        public void onItemClick(AdapterView<?> arg0, View v, int position,
                long id) {
            Log.d(TAG,"position "+v);
            c=new Category();
            String catid=mCatPathList.get(position).getCategory_id();
            Log.d(TAG,"cat_id "+catid);
            c=mAppMgr.getCategoryObjectFromId(catid);
            String isleaf = c.getIs_leaf();
            String cat_id=c.getCategory_id();
            Log.e(TAG,"isleaf:"+isleaf);

            if(isleaf.equals("false"))
           
            {
                Intent i=new Intent(mContext,SubCategoryMenu.class);
                Log.d(TAG,"false executed"+"Thanks");
                i.putExtra("cat", cat_id);
                startActivity(i);
            }
           
            else
           
            {
                Intent i=new Intent(mContext,ProfilesList.class);
                Log.d(TAG,"true executed"+"Thanks");
                mAppctx.setCatId(cat_id);
                startActivity(i);
            }

        }

    };

    public ArrayList<Category> prepareCatlogPath()
    {

        int i =0;
        Log.e(TAG,"am in"+"prepare string list");
        ArrayList<Category> List2=new ArrayList<Category>();

        for(;i< mResults.size();i++){
           
            String cat_id = mResults.get(i).category_id;
            Log.e(TAG,"cat_id:"+cat_id);
            String cat_name = mResults.get(i).category_name;
            Log.e(TAG,"catname:"+cat_name);
            String cat_path = mDBHelper.getCatalogPath(cat_id);
            Log.e(TAG,"catpath:"+cat_path);
            c=new Category();
            c.category_name=cat_name;
            Log.e(TAG,"catagoryName:"+cat_name);
            c.category_id=cat_id;
            c.cat_path=cat_path;
            List2.add(c);


        }

        Log.e(TAG,"mList2.size()"+mResults.size());
        return List2;
    }
   
    public ArrayList<Category> prepareCatlogList()
    {

        int i =0;
        Log.e(TAG,"am in"+"prepare Catlog string list");
        ArrayList<Category> catString=new ArrayList<Category>();

        for(;i< mResults.size();i++){

            String cat_id = mResults.get(i).category_id;
            Log.e(TAG,"cat_id:"+cat_id);
            String cat_name = mResults.get(i).category_name;
            Log.e(TAG,"catname:"+cat_name);
            c=new Category();
            c.category_name=cat_name;
            Log.e(TAG,"catagoryName:"+cat_name);
            c.category_id=cat_id;
           
            catString.add(c);
        }

        return catString;
    }
}


searchrow.xml 

here am showing the search result.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/vw1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView android:id="@+id/text1"
android:textSize="20sp"
android:textColor="#FF00008B"
android:background="#FFFFFFFF"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>

<TextView android:id="@+id/path"
android:textSize="15sp"
android:textColor="#FF00008B"
android:background="#FFFFFFFF"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>


this is SearchableAdapter.class which costomise my result 2nd listview which shows complete path of entered key

package com.inception.smui;

/**
 * Class Name :SearchableAdapter
 *
 * Parent Class :SearchAct
 *
 * Interfaces: None
 *
 * Description:It is used as Customised Adapter for showing resultList
 */
import java.util.ArrayList;

import com.ServiceMessenger.R;
import com.inception.dataparser.Category;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class SearchableAdapter extends BaseAdapter {
    private Context mContext;
    LayoutInflater layoutinflator;
    private ArrayList<Category> mCategory=null;


    public SearchableAdapter(Context con,ArrayList<Category> catalogPath) {
        // TODO Auto-generated constructor stub
        this.mContext=con;
        mCategory=catalogPath;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub

        return mCategory.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return mCategory.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        if (convertView == null) {

            LayoutInflater inflater = (LayoutInflater) mContext
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.searchrow, null);

        }

        TextView comment_name = (TextView) convertView.findViewById(R.id.text1);
        comment_name.setText( mCategory.get(position).category_name);

        TextView comment_desc = (TextView) convertView.findViewById(R.id.path);
        comment_desc.setText("path : " +mCategory.get(position).cat_path);

        return convertView;
    }

}

Wednesday, January 18, 2012

custom girdview on top and custom listview below which iterates itself.

package com.inception.smui;
/**
 * Class Name : ProfilesList
 *
 * Parent Class :Activity
 *
 * Interfaces: None
 *
 * Description:It will display the profiles related each and every sub-category
 */
import java.util.ArrayList;
import java.util.List;

import com.ServiceMessenger.R;
import com.inception.dataparser.Category;
import com.inception.dataparser.Service1;
import com.inception.dataparser.ServiceProvider;
import com.inception.dataparser.UserComments;
import com.inception.dataprovider.DatabaseHelper;
import com.inception.sm.ApplicationManager;
import com.inception.sm.Globals;
import com.inception.sm.MyAppContext;


import android.R.color;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
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.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Rect;
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.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

public class SubCategoryMenu extends BaseClass{
    String TAG="SubCategoryMenu";

    private DatabaseHelper mDBHelper;
    private static final int INDETERMINATE = 0;
    private ProgressDialog mProgDlg;
    private static ApplicationManager mAppMgr;
    TextView tv;

    private ArrayList<ServiceProvider> mProfileList = new ArrayList<ServiceProvider>();
    //private ArrayList<ServiceProvider> mProfileList = new ArrayList<ServiceProvider>();
    public ArrayList<String> mList = new ArrayList<String>();
    public ArrayList<String> mList1 = new ArrayList<String>();
    public ArrayList<String> mList2 = new ArrayList<String>();
    public List<String> mList3 = null;
    public List<String> mCatUrls=new ArrayList<String>();
    private List<Bitmap> mCatImg=new ArrayList<Bitmap>();
    private List<String> mProfileId = new ArrayList<String>();
    private ArrayList<String> mCatid = new ArrayList<String>();
    private ArrayList<Category> mSubCatList = new ArrayList<Category>();
    ArrayList<Service1> serviceList=null;
    ArrayList<String> mProfileIds=null;
    ArrayList<String> mProfileCities=null;
    ArrayList<String> mProfileCountries=null;
    ArrayList<String> mProfileRatings=null;
    ArrayList<String> mProfileDes=null;
    ArrayList<String> mProfileNames=null;
    ArrayList<String> mProfileOnlinestatus=null;
    ArrayList<String> mProfile_pic_url=null;
    ArrayList<UserComments> usercomments=null;
    ArrayList<Messenger> mClients = new ArrayList<Messenger>();
    private Context mContext;
    boolean mIsBound;
    private int mCurrentView;
    //widgets

    public ListView mListView;
    private Gallery mGallery;
    public Button mBtn1,mBtn2;
    private LayoutInflater mInflater;
    MyAppContext mAppctx;

    public static String mCategory_id;
    public static String mSubcat;
    private static CharSequence pid;
    //public static String mCat;
    public static int mView;
    public static CharSequence cat;
    private Category mCat = new Category();
    BaseClass b = new BaseClass();

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

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mDBHelper = new DatabaseHelper(this);
        mAppMgr = ApplicationManager.getApplicationMgrInstance(this.getApplicationContext());
        setContentView(R.layout.profile);
        mListView=(ListView)findViewById(R.id.lv_user1);
        mGallery = (Gallery) findViewById(R.id.gallery_catlog);
        mList3= new ArrayList<String>();
        mList3=mAppMgr.getCategories();
        mCatUrls=mAppMgr.getCategoriesUrls();
        Log.e(TAG,mCatUrls.get(0));
        mCatImg=mAppMgr.getCategoryImgs();
        mContext=this;
        mBtn1=(Button)findViewById(R.id.button_MyAcct1);
        mBtn2=(Button)findViewById(R.id.button_MySP1);
        /**
         *Button click listener for MyAccpunt button
         */
        mBtn1.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                Log.e(TAG,"button My Account clicked");
                if(CategoryMenu.mStatus){
                    Log.e("am in","login status true" );
                    MyAccount.mCurrentView1=Globals.SENT_FROM_SPLIST;
                    Intent i=new Intent(SubCategoryMenu.this,MyAccount.class);
                    startActivity(i);
                }
                else
                {
                    LoginInfo.mCurrentView1=Globals.LOGIN_IN_MYACCOUNT;
                    Intent i=new Intent(SubCategoryMenu.this,LoginInfo.class);
                    startActivity(i);

                }
            }

        });


        /**
         *Button click listener for MySPs button
         */
        mBtn2.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                Log.e(TAG,"button 1 clicked");
                if(CategoryMenu.mStatus){
                    Log.e("am in","login status true" );
                    Intent i=new Intent(mContext,MyAccount.class);
                    startActivity(i);
                }
                else
                {
                    LoginInfo.mCurrentView1=Globals.LOGIN_IN_MYACCOUNT;
                    Intent i=new Intent(mContext,LoginInfo.class);
                    startActivity(i);

                }
            }

        });
       
        mAppctx = (MyAppContext)getApplicationContext();
        mGallery.setAdapter(new ImageAdapter(mContext));
        //mGallery.setFadingEdgeLength(20); 
        Intent ip = getIntent();
        //int view= ip.getIntExtra("view", Globals.CONST_SUBCATEGORY);

        cat=(String) ip.getCharSequenceExtra("cat");
        Log.d("cat",""+cat);
        int view=(int) ip.getIntExtra("view", 0);
        Log.d("view",""+view);

        //if(view  == Globals.CONST_SUBCATEGORY)
        //{
        //mList = null;
        cat = ip.getCharSequenceExtra("cat");
        Log.d("subcatarory",""+cat);

        mCurrentView = Globals.CONST_SUBCATEGORY;

        mSubCatList=mAppMgr.getSubCategories(cat);
        /*if(mSubCatList.size()==0)
            {
                finish();
                //mCurrentView = Globals.CONST_PROFILE;
            }
            else{*/
        System.out.println(mSubCatList);

        Log.d("u r in ",cat.toString());
        mList2 = prepareStringList1();
        Log.d("mList2",""+mList2.size());

        mListView.setAdapter(new ArrayAdapter<String>(this,R.layout.list_item3,R.id.subCatlog_text,mList2));
        //}

        //}








        //mSubcat = (String) ip.getCharSequenceExtra("subcat");
        //Log.e(TAG,mSubcat);
        //mList1= null;
        /*    SQLiteDatabase database = mDBHelper.getWritableDatabase();

        Cursor data = database.query("catalog2", new String[] {"category_id"},new String("category_name"+"=?"),new String[]{mSubcat.toString()}, null, null, null);
        if (data != null)
        {
            Log.d("database",database.toString());
            if (data.moveToFirst()){
                mCategory_id= data.getString(data.getColumnIndex("category_id"));


            }
        }*/

        /**
         *List item click listener for profiles
         */

        mListView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                Log.d("SM","position "+position);
                mCat = new Category();
                if(mCurrentView == Globals.CONST_SUBCATEGORY){



                    CharSequence category = mList2.get(position);
                    CharSequence catSelectId = mCatid.get(position);

                    Log.e("subcategory clicked",""+ catSelectId);

                    mCat=mAppMgr.getCategoryObjectFromId(catSelectId);
                    String isleaf = mCat.getIs_leaf();
                    String cat_id=mCat.getCategory_id();
                    String cat_name=mCat.getCategory_name();
                    //String parent_id=mCat.getParent_id();

                    Log.e("isleaf",isleaf);
                    if(isleaf.equals("false"))
                    {
                        Log.d("false executed","Thanks");
                        mSubCatList=mAppMgr.getSubCategories(cat_id);
                        System.out.println(mSubCatList);
                        mCurrentView = Globals.CONST_SUBCATEGORY;
                        mList2 = prepareStringList1();
                        mListView.setAdapter(new ArrayAdapter<String>(mContext,R.layout.list_item3,R.id.subCatlog_text,mList2));

                    }
                    else
                    {
                        Intent i=new Intent(SubCategoryMenu.this,ProfilesList.class);
                        Log.d("true executed","Thanks");
                        mAppctx.setCatId(cat_id);
                        mAppctx.setCatName(cat_name);
                        //i.putExtra("cat",cat_id);
                        //i.putExtra("view", Globals.CONST_PROFILE);
                        startActivity(i);

                    }
                    //Log.e("am in","sub categories");
                    //startActivity(i);


                }




            }
        });

        /**
         *Gallery item click listener for categories
         */

        mGallery.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                mCat = new Category();
                //v.setFocusable(true);
                //tv.setText("");
                CharSequence cat = mList3.get(position);
                Log.e("category clicked",""+ cat);
                CharSequence category = cat;
                mCat=mAppMgr.getCategoryObjectFromName(category);
                String isleaf = mCat.getIs_leaf();
                String parent_id=mCat.getParent_id();
                String cat_id=mCat.getCategory_id();
                Log.e("cat_id",cat_id);

                Log.e("isleaf",isleaf);
                //Log.e("parent_id",parent_id);
                if(isleaf.equals("false"))
                {
                    callsubcatlog(cat_id);
                }
                else
                {
                    Intent i=new Intent(mContext,ProfilesList.class);
                    Log.d("true executed","Thanks");

                    //i.putExtra("cat",cat_id);
                    mAppctx.setCatId(cat_id);

                    startActivity(i);

                }


            }
           
        });
       
       
    }



    public ArrayList<String> prepareStringList1()
    {

        int i =0;
        Log.e("am in","prepare string list");
        //    Log.e(TAG+"mList1.size()",""+mList1.size());
        mCatid=new ArrayList<String>();
        ArrayList<String> List2=new ArrayList<String>();
        //misleaf=new ArrayList<String>();
        for(;i< mSubCatList.size();i++){
            String profileStr = mSubCatList.get(i).category_id;
            String profileStr1 = mSubCatList.get(i).category_name;
            //String isleaf=mList1.get(i).is_leaf;

            Log.e("profileStr1",profileStr);
            mCatid.add(profileStr);

            List2.add(profileStr1);

            //misleaf.add(isleaf);



        }
        Log.e("TAG+mList1.size()",""+mSubCatList.size());


        return List2;
    }



    void callsubcatlog(String cat_id)
    {
        mSubCatList=mAppMgr.getSubCategories(cat_id);
        if(mSubCatList.size()==0)
        {
            finish();
            mCurrentView = Globals.CONST_PROFILE;
        }
        else{
            System.out.println(mSubCatList);

            Log.d("u r in ",cat.toString());
            mList2 = prepareStringList1();
            Log.d("mList2",""+mList2.size());

            mListView.setAdapter(new ArrayAdapter<String>(this,R.layout.list_item3,R.id.subCatlog_text,mList2));
        }
    }

    /**
     * To set image in profile list
     */
    class IconicAdapter extends ArrayAdapter {
        IconicAdapter() {
            super(SubCategoryMenu.this, R.layout.list_item,R.id.text,mProfileNames);
        }

        public View getView(int position, View convertView,
                ViewGroup parent) {
            LayoutInflater inflater=getLayoutInflater();
            View row=inflater.inflate(R.layout.list_item, parent,    false);


            ImageView icon=(ImageView)row.findViewById(R.id.icon);
            TextView label=(TextView)row.findViewById(R.id.text);
            label.setText(mProfileNames.get(position)+","+mProfileCountries.get(position));

            /*    if (mList1.get(0).startsWith("abc")) {
                Log.e("am in","abc profile");
                icon.setImageResource(R.drawable.icon);
            }
            if (mList1.get(0).startsWith("xyz")) {
                icon.setImageResource(R.drawable.d1);
                Log.e("am in","xyz profile");
            }*/

            return(row);
        }
    }
    /**
     * To papulate images , data in catalog gallery
     */

    public class ImageAdapter extends BaseAdapter {
        int mGalleryItemBackground;
        private Context mContext;
        ViewHolder holder;

        public ImageAdapter(Context c) {
            mContext = c;
            mInflater = LayoutInflater.from(c);

            TypedArray a = obtainStyledAttributes(R.styleable.Theme);
            mGalleryItemBackground = a.getResourceId(
                    R.styleable.Theme_android_galleryItemBackground, 0);
            a.recycle();
        }

        public int getCount() {
            Log.i(TAG+"i am taking images from local DB","");
            //mCatImg=mAppMgr.getCategoryImgs();
            return mCatUrls.size();
            //return mCatImg.size();
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        /**
         * To papulate each view of gallery with textview and imageview
         */

        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.list_item_icon_text, null);
               
               
                //convertView.setLayoutParams(new Gallery.LayoutParams(100, 150));
                // Creates a ViewHolder and store references to the two children views
                // we want to bind data to.
                holder = new ViewHolder();
                holder.text = (TextView) convertView.findViewById(R.id.text);
                holder.icon = (ImageView) convertView.findViewById(R.id.icon);
                convertView.setTag(holder);
               
               
            } else {
                // Get the ViewHolder back to get fast access to the TextView
                // and the ImageView.
                holder = (ViewHolder) convertView.getTag();
            }

            // Bind the data efficiently with the holder.
            holder.text.setText(mList3.get(position));
            holder.icon.setImageBitmap(mCatImg.get(position));

            holder.icon.setBackgroundResource(mGalleryItemBackground);
            return convertView;


        }
       


    }
    /**
     * To Hold TextView and ImageView
     */

    static class ViewHolder {
        TextView text;
        ImageView icon;
    }


}



list_item_icon_text.xml layout for custom gallery


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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView android:id="@+id/icon" android:layout_width="100dip"
        android:layout_height="100dip" />

    <TextView android:id="@+id/text" android:layout_width="100dip"

        android:layout_height="wrap_content" />

</LinearLayout>

profile.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:background="@drawable/bk_gnd">
    <TextView android:id="@+id/empty" android:layout_width="fill_parent"
        android:layout_height="15dip" />
    <TextView android:id="@+id/catlogs_gallery_text" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="Categories"
        android:textColor="@color/menu_buttons" android:textSize="20sp"
        android:gravity="center" android:layout_below="@id/empty" />
    <TextView android:id="@+id/empty1" android:layout_width="fill_parent"
        android:layout_height="15dip" android:layout_below="@id/catlogs_gallery_text" />
    <Button android:id="@+id/button_MyAcct1" android:text="MyAccount"
        android:textSize="@dimen/menu_buttons_text_size" android:textColor="@color/menu_buttons"
        android:textStyle="bold" android:gravity="center"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" android:background="@drawable/button_menu" />

    <Button android:id="@+id/button_MySP1" android:text="MySPs"
        android:textSize="@dimen/menu_buttons_text_size" android:textColor="@color/menu_buttons"
        android:textStyle="bold" android:gravity="center"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"

        android:layout_alignParentRight="true" android:background="@drawable/button_menu" />
    <Gallery android:id="@+id/gallery_catlog" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:layout_below="@id/catlogs_gallery_text" />
    <TextView android:id="@+id/empty2" android:layout_width="fill_parent"
        android:layout_height="15dip" android:layout_below="@id/gallery_catlog" />
    <TextView android:id="@+id/txt_subCat" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="Sub Categories"
        android:textColor="@color/menu_buttons" android:textSize="20sp"
        android:gravity="center" android:layout_below="@id/empty2" />
    <TextView android:id="@+id/txt_selectsubCat" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="Select any category to get subcategories"
        android:textColor="@color/menu_buttons" android:layout_below="@id/txt_subCat" />
    <ListView android:textSize="150sp" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:id="@+id/lv_user1"
        android:layout_below="@id/txt_selectsubCat" />

</RelativeLayout>

list_item3.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="wrap_content" android:layout_height="wrap_content">

   
    <TextView android:id="@+id/subCatlog_text" android:layout_width="fill_parent"
        android:layout_height="fill_parent" android:layout_toRightOf="@id/icon"
        android:padding="5dp" android:textSize="@dimen/menu_buttons_text_size"
        android:textColor="@color/menu_buttons" android:textStyle="bold"


        android:layout_margin="5dp" />

    <ImageView android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_centerVertical="true"
        android:id="@+id/iv_forward" android:src="@drawable/arrow1"

        android:layout_alignParentRight="true" android:layout_marginRight="10dip">
    </ImageView>
</RelativeLayout>

horizontal gallery view which contains image and texts like profile



//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.LayoutParams layoutParamsTXT;
    private LinearLayout.LayoutParams layoutParamsIMG;
    private LinearLayout.LayoutParams layoutParamsHOLDER;
    private LinearLayout llHoder;
    private LinearLayout llFrame;
    private LinearLayout lltxts;
    private LinearLayout llv;
    static int  total;

    //widgets
    ImageView img1;
    TextView txt_Name;
    TextView txt_Charge;
    TextView txt_CatName;
    Button b1;

    public ListView mListView;
    MyAppContext mAppctx;



Call the following method to create gallery and load views


public void horizontalScrollGalleryLayout (List<String> mList3,List<String> mList4,List<String> mList5,List<Service1> mList6) {
        Integer[] mThumbIds = {
                R.drawable.ds

        };
        total=0;
        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(150,190);
        layoutParamsTV.setMargins(3, 30, 3, 30);
       
        layoutParamsIMG = new LinearLayout.LayoutParams(60,150);
        layoutParamsIMG.setMargins(3, 3, 3, 3);
        layoutParamsIMG.height=60;
        layoutParamsIMG.width= 60;
        layoutParamsTXT = new LinearLayout.LayoutParams(75,150);
        layoutParamsTXT.setMargins(3, 3, 3, 3);

        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);
           
            //llv.setBackgroundColor(R.drawable.border);
            for (int i=0; i<2; i++) {
                llv.setOrientation(LinearLayout.VERTICAL);
               

                llFrame = new LinearLayout(this);
                //llFrame.setPadding(1,1,1,1);
                //llFrame.setBackgroundColor(0xFFB0C4DE );
                llFrame.setBackgroundResource(R.drawable.layout_border);
               
                lltxts=new LinearLayout(this);
                lltxts.setOrientation(LinearLayout.VERTICAL);
                llFrame.setOrientation(LinearLayout.HORIZONTAL);   
                //button=new Button(this);
                img1 = new ImageView(this);
                txt_Name = new TextView(this);
                txt_CatName = new TextView(this);
                txt_Charge=new TextView(this);
                mCat = new Category();
                try {

                    img1.setImageResource(mThumbIds[0]);
                   
                    //img1.setTag(mList4.get(total));
                    img1.setTag(total);
                    if(!mProfile_pic_url.get(total).equals("null")&&!(mProfile_pic_url.get(total).startsWith(".."))&&(mProfile_pic_url.get(total)!=null)&&!(mProfile_pic_url.get(total).equals("")))
                    new DownloadImageAsyncTask(mProfileIds.get(total),mAppMgr,img1,"profile_img").execute(mProfile_pic_url.get(total));
                       
                    txt_Name.setText("Name : "+mList3.get(total));
                    txt_Name.setTextColor(Color.WHITE);
                    txt_CatName.setText("Category : "+mAppctx.getCatName());
                    txt_CatName.setTextColor(Color.WHITE);
                    txt_Charge.setText("Charge : "+mList6.get(total).service_charge);
                    txt_Charge.setTextColor(Color.WHITE);




                    //tx.setPadding(25, 0, 15, 0);
                    //txt_Name.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);

                    img1.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View view) {
                            // Perform action on click
                            //CharSequence cat = "Education";
                            Log.e("TAG","I entered const profile");
                            Integer id = (Integer) view.getTag();
                            Log.e("imgTag after clicked",""+ id);
                            pid=mProfileIds.get(id);
                            //pid=(CharSequence) img1.getTag();
                            Log.i("profileid",""+pid);
                            ArrayList<UserComments> personal_usercomments=new ArrayList<UserComments>();
                            //UserComments u=new UserComments();
                            //CharSequence pid = mList2.get(position);
                            for(int i=0;i<usercomments.size();i++)
                            {
                                UserComments u=new UserComments();
                                Log.i("size is",""+usercomments.size());
                                if(usercomments.get(i).sp_profileid.equals(pid))
                                {
                                    //UserComments u=new UserComments();
                                    u.name=usercomments.get(i).name;
                                    u.userComments=usercomments.get(i).userComments;
                                    personal_usercomments.add(u);
                                }

                            }
                            Log.e("pid is ",""+ pid);
                            ProfileInfo.mCurView=Globals.SENT_FROM_SPLIST;
                            Intent i1=new Intent(ProfilesList.this,ProfileInfo.class);
                            i1.putExtra("profileid", pid);
                            i1.putExtra("rating",mProfileRatings.get(id));
                            i1.putExtra("profilename",mProfileNames.get(id));
                            i1.putExtra("service_charge",serviceList.get(id).service_charge);
                            i1.putExtra("service_id", serviceList.get(id).service_id);
                            i1.putExtra("profiledes",mProfileDes.get(id));
                            i1.putParcelableArrayListExtra("comments", personal_usercomments);
                            i1.putExtra("country", mProfileCountries.get(id));
                            i1.putExtra("city", mProfileCities.get(id));

                            i1.putExtra("pic_url",mProfile_pic_url.get(id));
                            Log.e(TAG,"pic_url"+mProfile_pic_url.get(id));
                            startActivity(i1);

                        }
                    });
                    //if(total==13)
                    //break;
                    //new DownloadImageAsyncTask(mProfileIds.get(total),mAppMgr,img1,"profile_img").execute(Configure.SM_SERVER_URL_PREFIX+(mProfile_pic_url.get(total)));
                    total++;

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                lltxts.addView(txt_Name);
                lltxts.addView(txt_CatName);
                lltxts.addView(txt_Charge);
                llFrame.addView(img1,layoutParamsIMG);
                llFrame.addView(lltxts,layoutParamsTXT);
               
                llv.addView(llFrame,layoutParamsTV);
                //llv.addView(txt_Name);
                //llv.addView(txt_CatName);
                //llv.addView(txt_Charge);
                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);

    }

put layoutborder.xml in drawable forlder which puts border.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <stroke android:width="5dp" android:height="5dp"
                android:color="#FFC0C0C0" />
            <solid android:color="#000000" />
            <padding android:left="1dp" android:top="1dp" android:right="1dp"
                android:bottom="1dp" />

            <corners android:radius="1dp" android:bottomRightRadius="5dp"
                android:bottomLeftRadius="5dp" android:topLeftRadius="5dp"
                android:topRightRadius="5dp" />
        </shape>
    </item>

</layer-list>