First Android App | Step 9 | Speech Recognizer in Android

In this step, we are going to see how to integrate the Google's speech recognizer to capture voice and get the text conversion back to your activity.

In this case, the speech recognizer has been used on the Search tab as can be see below. There is a button next to searchView where we are integrating the speech recognizer.


Below is the YouTube video to explain how the integration was done.



Source Code

Changes in Search.java

1. Add setOnClickListener for audio button.

        buttonAudio.setOnClickListener(new OnClickListener() 
        {
            public void onClick(View v) 
            {
             Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                // Specify free form input
                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
                intent.putExtra(RecognizerIntent.EXTRA_PROMPT,"Please start speaking");
                intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.ENGLISH);
                startActivityForResult(intent, 2); 
            }
        });

2. Add code in onActivityResult to retrieve results and populate the searchView.

@Override  
    public void onActivityResult(int requestCode, int resultCode, Intent data)  
    {  
        //this requestCode is for handling the barcode activity.       
        if(requestCode==1)  
        {  
         String barcode=data.getStringExtra("BARCODE");
         if (barcode.equals("NULL"))
         {
          //that means barcode could not be identified or user pressed the back button
          //do nothing 
         }
         else
         {
          search.setQuery(barcode, true);
          search.setIconifiedByDefault(false);
         }
        }
        
        //this requestCode is for speechRecognizer. Only this part of the code needs to be added for
        //the implementation of voice to text functionality. 
 
        if (requestCode == 2) {
            ArrayList results;
            results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            //Toast.makeText(this, results.get(0), Toast.LENGTH_SHORT).show();
            
            //if the name has an ' then the SQL is failing. Hence replacing them. 
            String text = results.get(0).replace("'","");
            search.setQuery(text, true);
         search.setIconifiedByDefault(false);
        }
          
    }

First Android App | Step 10 | Implementing Button within Listview

In the search results, there is an option for the user to add to Cart. This has been implemented by using a Button or imageButton.

The complete view on how this can be implemented is available below.



Source Code

In Search.java, we have added a onClickListener for the button and a custom onClickListener to handle the click. 

inside getView of SearchResultsAdapter, we set up the custom listener

holder.addToCart.setOnClickListener(new MyPersonalClickListener("button_addtocart",tempProduct,context));

and then inside the SearchResultsAdapter class, add the following code to handle onClick

//this is a customized clicklistener
   public class MyPersonalClickListener implements OnClickListener
      {

       String button_name;
       Product prod_name;
       int tempQty;
       int tempValue;
       SQLiteDatabase sqLite;
       Context context;
       
       //constructor method
       public MyPersonalClickListener(String button_name, Product prod_name, Context context) 
       {
            this.prod_name = prod_name;
            this.button_name = button_name;
            this.context = context;
       }

       @Override
       public void onClick(View v)
       {
          
        // in this section, we are going to add items to cart
        //if the item is already there in cart, then increase the quantity by 1, else add the item to cart
        //if the quantity of the item has reached 10, then do nothing ---this is just a specific logic where
        //i did not want any item with quantity more than 10, but if you choose not to, then just comment out
        //the code. 
     sqLite=context.openOrCreateDatabase("basketbuddy", context.MODE_PRIVATE, null);
     
     Cursor cc = sqLite.rawQuery("SELECT PRODUCT_QTY, PRODUCT_VALUE FROM CART WHERE PRODUCT_CODE ="+Integer.parseInt(prod_name.getProductCode()), null);
     
     if (cc.getCount()== 0)
     {
           //product not already there in cart..add to cart
      sqLite.execSQL("INSERT INTO CART (PRODUCT_CODE, PRODUCT_NAME, PRODUCT_BARCODE, PRODUCT_GRAMMAGE"+
            ", PRODUCT_MRP, PRODUCT_BBPRICE, PRODUCT_DIVISION, PRODUCT_DEPARTMENT,PRODUCT_QTY,PRODUCT_VALUE) VALUES("+
           prod_name.getProductCode()+",'"+ prod_name.getProductName()+ "','" +
            prod_name.getProductBarcode()+"','"+ prod_name.getProductGrammage()+"',"+
           Integer.parseInt(prod_name.getProductMRP())+","+ Integer.parseInt(prod_name.getProductBBPrice())+","+
            Integer.parseInt(prod_name.getProductDivision())+","+Integer.parseInt(prod_name.getProductDepartment())+
            ",1,"+ Integer.parseInt(prod_name.getProductBBPrice())+")");
           
         Toast.makeText(context,"Item "+prod_name.getProductName()+" added to Cart", Toast.LENGTH_LONG).show();
     }
     else
     {
      
      //product already there in cart
      if(cc.moveToFirst())
     {
      do{
       tempQty=cc.getInt(0);
       tempValue = cc.getInt(1);
      }while(cc.moveToNext());
     }
      
      if (tempQty < 10)
      {
       sqLite.execSQL("UPDATE CART SET PRODUCT_QTY = "+ (tempQty+1)+",PRODUCT_VALUE = "+ 
     (Integer.parseInt(prod_name.getProductBBPrice())+tempValue)+" WHERE PRODUCT_CODE ="+
     prod_name.getProductCode());
       
       Toast.makeText(context,"Item "+prod_name.getProductName()+" added to Cart", Toast.LENGTH_LONG).show();
      }
     }

     sqLite.close();
              
       }

    }

First Android App | Step 11 | Shopping Cart | Delete within ListView and Refresh ListView

In this session, we will see how to create a Cart for our E-Commerce Application.

The user will be able to view items in his cart, change quantity, delete item and then proceed to checkout.

The final output will look like this.



The complete video of the tutorial is available in the following YouTube video.




Source Code is as follows:

fragment_mycart.xml

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

    <RelativeLayout 
   android:layout_width="fill_parent"
   android:layout_height="45dp" >
        
        <TextView
            android:id="@+id/item_text"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:text="Items"
            android:textColor="#474747"
            android:textSize="14dp"
            android:layout_marginTop="4dp"
            android:layout_marginLeft="10dp"/>
            
       <TextView
            android:id="@+id/item_count"
            android:layout_toRightOf="@+id/item_text"
            android:layout_alignParentTop="true"
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:text="(2)"
            android:textColor="#474747"
            android:textSize="14dp"
            android:layout_marginTop="4dp"
            android:layout_marginLeft="5dp"/>
        
       <TextView
            android:id="@+id/shipping_text"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/item_text"
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:text="Shipping:"
            android:textColor="#474747"
            android:textSize="14dp"
            android:layout_marginTop="2dp"
            android:layout_marginLeft="10dp"/>
       
       <TextView
            android:id="@+id/shipping_amount"
            android:layout_toRightOf="@+id/shipping_text"
            android:layout_alignTop="@+id/shipping_text"
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:text="Rs.50"
            android:textColor="#474747"
            android:textSize="14dp"
            android:layout_marginLeft="5dp"/>
       
             
        <TextView
            android:id="@+id/total_amount"
            android:layout_toLeftOf="@+id/checkout"
            android:layout_alignParentTop="true"
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:text="Rs. 5700"
            android:textColor="#000000"
            android:textSize="20dp"
            android:layout_marginTop="12dp"
            android:layout_marginRight="10dp"/>

        <Button
            android:id="@+id/checkout"
            android:layout_width="wrap_content"
            android:layout_height="25dp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_marginRight="4dp"
            android:layout_marginTop="4dp"
            android:background="#A2A2A2"
            android:padding="2dp"
            android:text="Checkout >>"
            android:textSize="16dp" />
         
           
      <TextView
            android:id="@+id/cart_empty"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:text="CART IS EMPTY"
            android:textColor="#474747"
            android:textSize="20dp"
            android:layout_marginTop="12dp"
            android:layout_marginLeft="50dp"/>    
         
         
         
    </RelativeLayout>
    
    
    
    <View
        android:id="@+id/view1"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="5dp"
        android:background="#BABABA" />
    
    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#FFFFFF"
        android:layout_margin="5dp">
        
    </ListView>
   
</LinearLayout>



listone_custom.xml

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

    <ImageButton
        android:id="@+id/delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:background="#FFFFFF"
        android:scaleX="1"
        android:scaleY="1"
        android:src="@android:drawable/ic_delete" />

    <TextView
        android:id="@+id/product_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="10dp"
        android:layout_toLeftOf="@+id/delete"
        android:text="Kelloggs Corn Flakes Honey and Almond 400gm"
        android:textSize="20dp" />

    <TextView
        android:id="@+id/product_mrp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/product_name"
        android:layout_below="@+id/product_name"
        android:layout_marginTop="15dp"
        android:text="MRP: "
        android:textSize="14dp" 
        android:textColor="#757575"/>

    <TextView
        android:id="@+id/product_mrpvalue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/product_mrp"
        android:layout_marginLeft="0dp"
        android:layout_toRightOf="@+id/product_mrp"
        android:text="Rs.20000"
        android:textSize="14dp" 
        android:textColor="#757575"/>

    <TextView
        android:id="@+id/product_bb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/product_name"
        android:layout_below="@+id/product_mrp"
        android:layout_marginTop="5dp"
        android:text="BB:  "
        android:textSize="14dp" 
        android:textColor="#757575"/>

    <TextView
        android:id="@+id/product_bbvalue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/product_mrpvalue"
        android:layout_below="@+id/product_mrpvalue"
        android:layout_marginLeft="0dp"
        android:layout_marginTop="5dp"
        android:text="Rs.15000"
        android:textSize="14dp" 
        android:textColor="#757575"/>

    <View
        android:id="@+id/view1"
        android:layout_width="1dp"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/product_savings"
        android:layout_below="@+id/product_name"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:layout_toRightOf="@+id/product_mrpvalue"
        android:background="#E6E6E6" />
 
    <TextView
        android:id="@+id/qty_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/view1"
        android:layout_below="@+id/product_name"
        android:layout_marginLeft="25dp"
        android:layout_marginTop="10dp"
        android:text="Qty"
        android:textSize="14dp" 
        android:textColor="#757575"/>
    
    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="50dp"
        android:layout_height="40dp"
        android:layout_below="@+id/qty_text"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="0dp"
        android:layout_toRightOf="@+id/view1"/>
    
    <View
        android:id="@+id/view2"
        android:layout_width="1dp"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/product_savings"
        android:layout_below="@+id/product_name"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:layout_toRightOf="@+id/spinner1"
        android:background="#E6E6E6" />
    
    
    <TextView
        android:id="@+id/product_value"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/product_name"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:layout_toRightOf="@+id/view2"
        android:text="Rs 5000"
        android:textColor="#191919"
        android:textSize="20dp" />
 
    <View
        android:id="@+id/view3"
        android:layout_width="wrap_content"
        android:layout_height="1dp"
        android:layout_alignRight="@+id/product_savingsvalue"
        android:layout_below="@+id/product_value"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="5dp"
        android:layout_toRightOf="@+id/view2"
        android:background="#E6E6E6" />
    
    <TextView
        android:id="@+id/product_savings"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/view3"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="5dp"
        android:layout_toRightOf="@+id/view2"
        android:text="Savings: "
        android:textColor="#5E5E5E"
        android:textSize="14dp" />
 
    <TextView
        android:id="@+id/product_savingsvalue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/view3"
        android:layout_marginLeft="0dp"
        android:layout_marginTop="5dp"
        android:layout_toRightOf="@+id/product_savings"
        android:text="Rs 12000 "
        android:textColor="#5E5E5E"
        android:textSize="14dp" />
        
<View
        android:id="@+id/view4"
        android:layout_width="match_parent"
        android:layout_height="10dp"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/view1"
        android:layout_marginTop="5dp"
        android:background="#E6E6E6" />

</RelativeLayout>

qty_spinner.item.xml

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

<TextView  
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:textSize="16dip"
    android:gravity="center"  
    android:textColor="#000000"         
    android:padding="0dp"
    />

MyCart.java

package com.zing.basket;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.zing.basket.util.Product;


@SuppressLint("ShowToast")
public class MyCart extends Fragment {
 
 ArrayList<Product&lgt; cart_list = new ArrayList<Product&lgt;();
 SQLiteDatabase sqLite;
 int count=0;
 int totalCartItemCount =0;
 int totalCartValue = 0;
 View myFragmentView;
 final String[] qtyValues = {"1","2","3","4","5","6","7","8","9","10"};
 
 
 @Override
 public void onCreate(Bundle savedInstanceState)
 {
  super.onCreate(savedInstanceState);
 }
 
 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
 Bundle savedInstanceState) {
   myFragmentView = inflater.inflate(R.layout.fragment_mycart, container, false);
   
   getCartData();
   totalCartItemCount = cart_list.size();
   totalCartValue =0;
   for (int temp1=0; temp1 < cart_list.size(); temp1++)
   {
    totalCartValue = totalCartValue + Integer.parseInt(cart_list.get(temp1).getProductValue());
   }
   HomeScreen activity = (HomeScreen) getActivity();
   
   Typeface type= Typeface.createFromAsset(activity.getAssets(),"fonts/book.TTF");
   
   TextView itemText = (TextView) myFragmentView.findViewById(R.id.item_text);
   TextView itemCount = (TextView) myFragmentView.findViewById(R.id.item_count);
   TextView shippingText = (TextView) myFragmentView.findViewById(R.id.shipping_text);
   TextView shippingAmount = (TextView) myFragmentView.findViewById(R.id.shipping_amount);
   TextView totalAmount = (TextView) myFragmentView.findViewById(R.id.total_amount);
   Button checkout = (Button) myFragmentView.findViewById(R.id.checkout);
   ListView lv1=(ListView) myFragmentView.findViewById(R.id.listView1);
   TextView cartEmpty = (TextView) myFragmentView.findViewById(R.id.cart_empty);
   
   if (totalCartItemCount == 0)
   {
    itemText.setVisibility(myFragmentView.INVISIBLE);
    itemCount.setVisibility(myFragmentView.INVISIBLE);
    shippingText.setVisibility(myFragmentView.INVISIBLE);
    shippingAmount.setVisibility(myFragmentView.INVISIBLE);
    totalAmount.setVisibility(myFragmentView.INVISIBLE);
    checkout.setVisibility(myFragmentView.INVISIBLE);
    lv1.setVisibility(myFragmentView.INVISIBLE);
    cartEmpty.setVisibility(myFragmentView.VISIBLE);
   }
   
   else
   {
    itemText.setVisibility(myFragmentView.VISIBLE);
    itemCount.setVisibility(myFragmentView.VISIBLE);
    shippingText.setVisibility(myFragmentView.VISIBLE);
    shippingAmount.setVisibility(myFragmentView.VISIBLE);
    totalAmount.setVisibility(myFragmentView.VISIBLE);
    checkout.setVisibility(myFragmentView.VISIBLE);
    lv1.setVisibility(myFragmentView.VISIBLE);
    cartEmpty.setVisibility(myFragmentView.INVISIBLE);
    
   }
   
   
   itemCount.setText("("+ totalCartItemCount + ")");
   if (totalCartValue &lgt; 500)
   {
    shippingAmount.setText("Free");
    totalAmount.setText("Rs "+ totalCartValue);
   }
   else
   {
    shippingAmount.setText("Rs 50");
    totalAmount.setText("Rs "+ (totalCartValue+50));
   }
   
   
   itemText.setTypeface(type);
   itemCount.setTypeface(type);
   shippingText.setTypeface(type);
   shippingAmount.setTypeface(type);
   totalAmount.setTypeface(type);
   checkout.setTypeface(type);
   
   
   lv1.setAdapter(new custom_list_one(this.getActivity(),cart_list));
   
   return myFragmentView;
  }
 
 class custom_list_one extends BaseAdapter
 {
   private LayoutInflater layoutInflater;
   ViewHolder holder;
   private ArrayList<Product&lgt; cartList=new ArrayList<Product&lgt;();
   int cartCounter;
   Typeface type;
   Context context;
   
  public custom_list_one(Context context, ArrayList<Product&lgt; cart_list) {
   layoutInflater = LayoutInflater.from(context);
    this.cartList=cart_list;
    this.cartCounter= cartList.size();
    this.context = context;
    type= Typeface.createFromAsset(context.getAssets(),"fonts/book.TTF");
  }

  @Override
  public int getCount() {

   return cartCounter;
  }

  @Override
  public Object getItem(int arg0) {

   return cartList.get(arg0);
  }

  @Override
  public long getItemId(int arg0) {

   return arg0;
  }

  @Override
  public View getView(final int position, View convertView, ViewGroup parent) 
  {
   Product tempProduct = cart_list.get(position);

   
    if (convertView == null) 
       {
        convertView = layoutInflater.inflate(R.layout.listone_custom, null);
           holder = new ViewHolder();
           holder.name = (TextView) convertView.findViewById(R.id.product_name);
           holder.product_mrp = (TextView) convertView.findViewById(R.id.product_mrp);
           holder.product_mrpvalue = (TextView) convertView.findViewById(R.id.product_mrpvalue);
           holder.qty = (Spinner) convertView.findViewById(R.id.spinner1);
           holder.cancel = (ImageButton) convertView.findViewById(R.id.delete);
           holder.product_value = (TextView) convertView.findViewById(R.id.product_value);
           holder.qty_text =(TextView) convertView.findViewById(R.id.qty_text);
           holder.product_bb = (TextView) convertView.findViewById(R.id.product_bb);
           holder.product_bbvalue = (TextView) convertView.findViewById(R.id.product_bbvalue);
           holder.product_savings = (TextView) convertView.findViewById(R.id.product_savings);
           holder.product_savingsvalue = (TextView) convertView.findViewById(R.id.product_savingsvalue);
           
           convertView.setTag(holder);
       } 
       else 
       {
              holder = (ViewHolder) convertView.getTag();
       }
   
       
    holder.name.setText(tempProduct.getProductName());
    holder.name.setTypeface(type);
    
    holder.product_mrp.setTypeface(type);
    
    
    holder.product_mrpvalue.setText("Rs "+tempProduct.getProductMRP());
    holder.product_mrpvalue.setTypeface(type);
    
    
    ArrayAdapter<String&lgt; aa=new ArrayAdapter<String&lgt;(context,R.layout.qty_spinner_item,qtyValues);
    aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    
    holder.qty.setAdapter(aa);
   
    holder.qty.setSelection(Integer.parseInt(tempProduct.getProductQty())-1);
    
    holder.product_bb.setTypeface(type);
    
    holder.product_bbvalue.setText("Rs "+tempProduct.getProductBBPrice());
    holder.product_bbvalue.setTypeface(type);
    
    holder.product_savings.setTypeface(type);
    
    holder.product_savingsvalue.setText("Rs "+(Integer.parseInt(tempProduct.getProductMRP())-Integer.parseInt(tempProduct.getProductBBPrice()))*Integer.parseInt(tempProduct.getProductQty())+"");
    holder.product_savingsvalue.setTypeface(type);
    
    holder.qty_text.setTypeface(type);
    
    holder.product_value.setText("Rs "+Integer.parseInt(tempProduct.getProductBBPrice())*Integer.parseInt(tempProduct.getProductQty())+"");
    holder.product_value.setTypeface(type);
    

    
    holder.cancel.setOnClickListener(new MyPersonalClickListener("button_delete",tempProduct)); 
          
    holder.qty.setOnItemSelectedListener(new OnItemSelectedListener(){
    
    @Override
    public void onItemSelected(AdapterView<?&lgt; parent, View view,int selectionIndex, long id) 
    {
      //if user has changed the quantity, then save it in the DB. refresh cart_list
     
      if ((parent.getSelectedItemPosition()+1) != Integer.parseInt(cart_list.get(position).getProductQty()))
      {
       
       sqLite=context.openOrCreateDatabase("basketbuddy", context.MODE_PRIVATE, null);
       sqLite.execSQL("UPDATE CART SET PRODUCT_QTY ='"+ (parent.getSelectedItemPosition()+1)+"' WHERE PRODUCT_CODE ='"+cart_list.get(position).getProductCode()+"'");
       sqLite.execSQL("UPDATE CART SET PRODUCT_VALUE='" + (parent.getSelectedItemPosition()+1) * Integer.parseInt(cart_list.get(position).getProductBBPrice())  +"' WHERE PRODUCT_CODE ='"+cart_list.get(position).getProductCode()+"'");
       sqLite.close();
       getCartData();
       
       notifyDataSetChanged();
       
       //refresh data outside the listview - Cart Total, Total Items, Shipping Cost etc
       View parentView = (View) view.getParent().getParent().getParent().getParent();
       
       TextView txtTotalAmount = (TextView) parentView.findViewById(R.id.total_amount);
       TextView txtTotalItems = (TextView) parentView.findViewById(R.id.item_count);
       TextView txtShippingAmt = (TextView) parentView.findViewById(R.id.shipping_amount);
       
       totalCartItemCount = cart_list.size();
       totalCartValue =0;
       
       for (int temp1=0; temp1 < cart_list.size(); temp1++)
       {
        totalCartValue = totalCartValue + Integer.parseInt(cart_list.get(temp1).getProductValue());
       }
       
       txtTotalItems.setText("("+ totalCartItemCount + ")");
       
         if (totalCartValue &lgt; 500)
         {
          txtShippingAmt.setText("Free");
          txtTotalAmount.setText("Rs "+ totalCartValue);
         }
         else
         {
          txtShippingAmt.setText("Rs 50");
          txtTotalAmount.setText("Rs "+ (totalCartValue+50));
         }
      }
    }

    @Override
    public void onNothingSelected(AdapterView<?&lgt; arg0) 
    {

    }
    });
    
       return convertView;
  }
   class ViewHolder 
   {         
          TextView name;
          TextView product_mrp;
          TextView product_mrpvalue;
          TextView product_bb;
          TextView product_bbvalue;
          TextView qty_text;
          TextView product_savings;
          TextView product_savingsvalue;
          TextView product_value;
          ImageButton cancel;
          Spinner qty;
          
   }
   
 }
 
 public class MyPersonalClickListener implements OnClickListener
    {

      String button_name;
      Product prod_name;
      int tempQty;
      int tempValue;
      
      public MyPersonalClickListener(String button_name, Product prod_name) 
      {
           this.prod_name = prod_name;
           this.button_name = button_name;
      }

      @Override
      public void onClick(View v)
      {
  
       if (button_name == "button_delete")
          {
        sqLite=getActivity().openOrCreateDatabase("basketbuddy", getActivity().MODE_PRIVATE, null);
        sqLite.execSQL("DELETE FROM CART WHERE PRODUCT_CODE ="+Integer.parseInt(prod_name.getProductCode()));
          sqLite.close();
          Toast.makeText(getActivity(),"Item "+prod_name.getProductName()+" deleted from Cart", Toast.LENGTH_LONG).show();
          
          getCartData();
          
          View lView = (View) v.getParent().getParent();
          
          ((ListView) lView).setAdapter(new custom_list_one(getActivity(),cart_list));
       
          
          TextView txtTotalAmount = (TextView) myFragmentView.findViewById(R.id.total_amount);
          TextView txtTotalItems = (TextView) myFragmentView.findViewById(R.id.item_count);
          TextView txtShippingAmt = (TextView) myFragmentView.findViewById(R.id.shipping_amount);   
          TextView itemText = (TextView) myFragmentView.findViewById(R.id.item_text);
          TextView shippingText = (TextView) myFragmentView.findViewById(R.id.shipping_text);
          Button checkout = (Button) myFragmentView.findViewById(R.id.checkout);
          ListView lv1=(ListView) myFragmentView.findViewById(R.id.listView1);
          TextView cartEmpty = (TextView) myFragmentView.findViewById(R.id.cart_empty);
          
          totalCartItemCount = cart_list.size();
     totalCartValue =0;
     for (int temp1=0; temp1 < cart_list.size(); temp1++)
     {
      totalCartValue = totalCartValue + Integer.parseInt(cart_list.get(temp1).getProductValue());
     }
    
     txtTotalItems.setText("("+ totalCartItemCount + ")");
    
     if (totalCartValue &lgt; 500)
     {
      txtShippingAmt.setText("Free");
      txtTotalAmount.setText("Rs "+ totalCartValue);
     }
     else
     {
      txtShippingAmt.setText("Rs 50");
      txtTotalAmount.setText("Rs "+ (totalCartValue+50));
     }
     
     
     if (totalCartItemCount == 0)
     {
      itemText.setVisibility(myFragmentView.INVISIBLE);
      txtTotalItems.setVisibility(myFragmentView.INVISIBLE);
      shippingText.setVisibility(myFragmentView.INVISIBLE);
      txtShippingAmt.setVisibility(myFragmentView.INVISIBLE);
      txtTotalAmount.setVisibility(myFragmentView.INVISIBLE);
      checkout.setVisibility(myFragmentView.INVISIBLE);
      lv1.setVisibility(myFragmentView.INVISIBLE);
      cartEmpty.setVisibility(myFragmentView.VISIBLE);
     }
     
     else
     {
      itemText.setVisibility(myFragmentView.VISIBLE);
      txtTotalItems.setVisibility(myFragmentView.VISIBLE);
      shippingText.setVisibility(myFragmentView.VISIBLE);
      txtShippingAmt.setVisibility(myFragmentView.VISIBLE);
      txtTotalAmount.setVisibility(myFragmentView.VISIBLE);
      checkout.setVisibility(myFragmentView.VISIBLE);
      lv1.setVisibility(myFragmentView.VISIBLE);
      cartEmpty.setVisibility(myFragmentView.INVISIBLE);
      
     } 

          }
       
      }

   }
 
 public void getCartData() {
  

  HomeScreen activity = (HomeScreen) getActivity();
  Product tempCartItem = new Product();
  
  cart_list.clear();
  sqLite=activity.openOrCreateDatabase("basketbuddy", activity.MODE_PRIVATE, null);
  Cursor c=sqLite.rawQuery("SELECT  * FROM CART",null);
  count=0;
  if(c.moveToFirst())
  {
   do{
    
    tempCartItem = new Product();
    tempCartItem.setProductCode(c.getString(c.getColumnIndex("PRODUCT_CODE")));
    tempCartItem.setProductName(c.getString(c.getColumnIndex("PRODUCT_NAME")));
    tempCartItem.setProductBarcode(c.getString(c.getColumnIndex("PRODUCT_BARCODE")));
    tempCartItem.setProductGrammage(c.getString(c.getColumnIndex("PRODUCT_GRAMMAGE")));
    tempCartItem.setProductDivision(c.getString(c.getColumnIndex("PRODUCT_DIVISION")));
    tempCartItem.setProductDepartment(c.getString(c.getColumnIndex("PRODUCT_DEPARTMENT")));
    tempCartItem.setProductBBPrice(c.getString(c.getColumnIndex("PRODUCT_BBPRICE")));
    tempCartItem.setProductMRP(c.getString(c.getColumnIndex("PRODUCT_MRP")));
    tempCartItem.setProductQty(c.getString(c.getColumnIndex("PRODUCT_QTY")));
    tempCartItem.setProductValue(c.getString(c.getColumnIndex("PRODUCT_VALUE")));
    cart_list.add(tempCartItem);
    count++;
   }while(c.moveToNext());
   
  }
  sqLite.close();
  
 }
}

First Android App | Step 12 | Upload Data to Server from Android App

In this post, we are going to discuss the working of how to upload data from Android App to the server.

The example is that of uploading order information to server from an E-Commerce Shopping Application on android.

The screen looks like this.



The complete demo is available in this video.



Source Code


Checkout.java.

Note: Currently, UserId for user has been hardcoded to 1.

package com.zing.basket;


import java.util.ArrayList;

import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.zing.basket.util.Product;

public class Checkout extends Activity {

 ArrayList cart_list = new ArrayList();
 SQLiteDatabase sqLite;
 int count;
 String address ="";
 String productList="";
 String userId="1";
 String orderNo="";
 String numberOfItems;
 @Override
 public void onCreate(Bundle savedInstanceState)
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_checkout);
  
  getCartData();
  
  Typeface type= Typeface.createFromAsset(getAssets(),"fonts/book.TTF");
  
  TextView addressHeader = (TextView) findViewById(R.id.header);
  addressHeader.setTypeface(type);
  
  TextView paymentHeader = (TextView) findViewById(R.id.header1);
  paymentHeader.setTypeface(type);
  
  final EditText name = (EditText) findViewById(R.id.name);
  name.setTypeface(type);
  
  final EditText address1 = (EditText) findViewById(R.id.address1);
  address1.setTypeface(type);
  
  final EditText address2 = (EditText) findViewById(R.id.address2);
  address2.setTypeface(type);
  
  final EditText city = (EditText) findViewById(R.id.city);
  city.setTypeface(type);
  
  final EditText state = (EditText) findViewById(R.id.state);
  state.setTypeface(type);
  
  final EditText pin = (EditText) findViewById(R.id.pin);
  pin.setTypeface(type);
  
  final EditText phone = (EditText) findViewById(R.id.phone);
  phone.setTypeface(type);
  
  Button submit = (Button) findViewById(R.id.submit);
  submit.setTypeface(type);
  
  submit.setOnClickListener(new OnClickListener()
  {
  
   @Override
   public void onClick(View arg0) {
    
    int i=0;
    String prod;
    
    //do validations
    
    //if all validations are ok, then proceed. 
    // construct the address
    address = address.concat(":name:");
    address = address.concat(name.getText().toString());
    address = address.concat(":address1:");
    address = address.concat(address1.getText().toString());
    address = address.concat(":address2:");
    address = address.concat(address2.getText().toString());
    address = address.concat(":city:");
    address = address.concat(city.getText().toString());
    address = address.concat(":state:");
    address = address.concat(state.getText().toString());
    address = address.concat(":pin:");
    address = address.concat(pin.getText().toString());
    address = address.concat(":phone:");
    address = address.concat(phone.getText().toString());
    address = address.replace(" ", "%20");
    //Log.d("arindam",address);
    
    //construct the order summary
    numberOfItems = String.valueOf(cart_list.size());
    //Log.d("arindam",numberOfItems);
    // construct the product details
    
    for (i=0;i {
 JSONParser jParser;
 String url = new String();
 ProgressDialog pd;
 String response = new String();
 SQLiteDatabase sqLite;
 String result;
 
 @Override
 protected void onPreExecute() {
  super.onPreExecute();

  url = "http://lawgo.in/lawgo/order?userid="
    + userId + "&address=" + address + "&itemcount="+numberOfItems +"&orderlist=" + productList;
  //Log.d("arindam","url"+ url);
  
  jParser = new JSONParser();
  pd = new ProgressDialog(Checkout.this);
  pd.setMessage("Please Wait");
  pd.setCancelable(false);
  pd.show();
 }

 @Override
 protected String doInBackground(Void... arg0) {
  try {
  JSONObject json = jParser.getJSONFromUrl(url);
  
   response = json.getString("Status");
   Log.i("arindam",response);
   
   if (response.equalsIgnoreCase("Success")) {
     
     
     orderNo = json.getString("OrderNo");
     Log.i("arindam",orderNo);
     deleteCartData();
     addOrderData();
     result = "success";
    }
  } catch (Exception e) 
  {
   result = "connection error";
  }
  return result;

 }

 @Override
 protected void onPostExecute(String result) {
  if (result.equalsIgnoreCase("success")) 
  {
   Toast.makeText(Checkout.this,"Order No "+orderNo+"successfully created.", Toast.LENGTH_LONG).show();
   pd.dismiss();
   Intent intent = new Intent(getApplicationContext(),HomeScreen.class);
   startActivity(intent);
   finish();
   
  } else {
   pd.dismiss();
   Toast.makeText(getApplicationContext(),
     "Network not aviliable, please try later.", Toast.LENGTH_LONG).show();
   finish();
  }

 }
}
 
}


Refresh PageViewer Fragment everytime user selects Fragment

All of us have faced this challenge where data of one Fragment got changed from another Fragment but since PageViewer instantiates adjacent Fragments even before Fragment is selected, the changed data does not reflect.

Let us take an example. I have a PageViewer with 3 fragments - One is Search, Second is Cart and 3rd is QuickOrder.


By Default, Search is displayed when this activity starts. Since, Cart is next to Search, it is automatically queued up and instantiated. Now, from Search Fragment, if I add an item to cart, since Cart is already instantiated, even when I select Cart, it does not show the newly added item.

When I select Cart, it automatically instantiates QuickOrder Fragment. Now, no matter what I do, since Cart has been already been instantiated, the new data never shows, even if I move between tabs.

I am sure many of you would have faced this problem. So read a lot and saw suggestions from users at StackOverFlow. This is the working solution that I have.

Solution:

Add a hash map to keep the tags of all the Fragments which have been instantiated. This way, from my FragmentActivity, I can check when the Fragment is the current fragment, in which case I call the onResume() method within the Fragment to refresh the content that I want to refresh.


The video should explain it all.




Source Code:

Inside FragmentPageAdapter which is my FragmentPagerAdapter

I define a hash map to store the Tags of the Fragments

mFragmentTags = new HashMap<Integer,String>();

Then we override the instantiateItem method to save the tag of the Fragment in the hashmap along with the position.
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Object obj = super.instantiateItem(container, position);
        if (obj instanceof Fragment) {
            // record the fragment tag here.
            Fragment f = (Fragment) obj;
            String tag = f.getTag();
            mFragmentTags.put(position, tag);
        }
        return obj;
    }

Also, we create a method which will return tag of a previously created Fragment based on the position
public Fragment getFragment(int position) {
        String tag = mFragmentTags.get(position);
        if (tag == null)
            return null;
        return mFragmentManager.findFragmentByTag(tag);
}

Inside HomeScreen.java which is my FragmentActivity, inside method on onPageSelected
Fragment fragment = ((FragmentPageAdapter)viewpager.getAdapter()).getFragment(arg0);
				
	if (arg0 ==1 && fragment != null)
	{
		fragment.onResume();
	}

In myCart.java

@Override
public void onResume()
{
	//do the data changes. In this case, I am refreshing the arrayList cart_list and then calling the listview to refresh. 
        getCartData();
        lv1.setAdapter(new custom_list_one(this.getActivity(),cart_list));
}

First Android App | Step 13 | View Pager and Navigation Drawer with Expandable List View

In this session, we are going to discuss how we can implement a Navigation Drawer with View Pager. The Navigation Drawer is going to have an expandable list view.

The final output is going to look like this.


The video on how to implement this is provided below




Source Code:

activity_home_screen.xml - This is the xml for the home screen which had originally implemented the viewpager.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:orientation="vertical" 
     android:background="#ffffff" />   
 
    
    <ExpandableListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#FFFFFF"/>
    
</android.support.v4.widget.DrawerLayout>

Code for Category.java, which is a custom object to store the names of all Categories

package com.zing.basket.util;


public class Category{
 
 private String cat_name;
 private int cat_code;
 
 public void setCatName (String cat_name)
 {
     this.cat_name = cat_name;
 }
 
 public String getCatName()
 {
     return cat_name;
 }

 public void setCatCode (int cat_code)
 {
     this.cat_code = cat_code;
 }
 
 public int getCatCode()
 {
     return cat_code;
 }
 
}



Code or SubCategory.java which is a custom object to store the names of all SubCategories

package com.zing.basket.util;


public class SubCategory{
 
 private String subcat_name;
 private String subcat_code;
 
 public void setSubCatName (String subcat_name)
 {
     this.subcat_name = subcat_name;
 }
 
 public String getSubCatName()
 {
     return subcat_name;
 }

 public void setSubCatCode (String subcat_code)
 {
     this.subcat_code = subcat_code;
 }
 
 public String getSubCatCode()
 {
     return subcat_code;
 }
 
}




Code for expandablelistcategory.xml which is the xml for the group view of expandable list view

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 
 <TextView
  android:id="@+id/cat_desc_1"
  android:textColor="#000000"
  android:layout_height="wrap_content"
  android:layout_width="match_parent"
  android:layout_gravity="left|center_vertical"
  android:layout_alignParentLeft="true"
  android:textSize="18dp" 
  android:layout_marginLeft="30dp"
  android:layout_marginTop="10dp"
  android:layout_marginBottom="5dip"
  android:text="Product Description"/> 
 
 <View
        android:id="@+id/view1"
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_below="@+id/cat_desc_1"
        android:background="#E6E6E6" />
 
</RelativeLayout>



Code for expandablelistviewsubcat.xml which is the xml for the child view of expandable list view

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    
    
    <View
        android:id="@+id/view1"
        android:layout_width="14dp"
        android:layout_height="40dp"
        android:layout_alignParentLeft="true"
        android:background="#E6E6E6" />
    
    <TextView
        android:id="@+id/subcat_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="15dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="10dp"
        android:text="Sub Category Name"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textSize="14dp" />
        
</RelativeLayout>



Code for HomeScreen.java which is the base fragment activity housing the viewpager and navigation drawer.

package com.zing.basket;

import java.util.ArrayList;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.TextView;

import com.zing.basket.util.Category;
import com.zing.basket.util.SubCategory;

public class HomeScreen extends FragmentActivity implements ActionBar.TabListener 
{
 
ActionBar bar;
ViewPager viewpager;
FragmentPageAdapter ft;
Fragment mSearchFragment;
Fragment mCartFragment;
Fragment mQuickOrderFragment;

Search search;
MyCart mycart;
QuickOrder quickorder;

// here we define the widgets required for implementing the drawer layout. 
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private ExpandableListView mCategoryList;

// these are the arraylists for the categories and sub categories
private ArrayList<Category> category_name = new ArrayList<Category>();
private ArrayList<ArrayList<SubCategory>> subcategory_name = new ArrayList<ArrayList<SubCategory>>();
private ArrayList<Integer> subCatCount = new ArrayList<Integer>();

int previousGroup;

 @Override
 protected void onCreate(Bundle savedInstanceState) 
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_home_screen);

  //populate the arraylists
  this.getCatData();  
  
  viewpager = (ViewPager) findViewById(R.id.pager);
        
        ft = new FragmentPageAdapter(getSupportFragmentManager(),this.getApplicationContext());
        viewpager.setAdapter(ft);
        
  final ActionBar bar = getActionBar();
        bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
        
        bar.addTab(bar.newTab().setText("Search").setTabListener(this));
        bar.addTab(bar.newTab().setText("Cart").setTabListener(this));
        bar.addTab(bar.newTab().setText("Quick Order").setTabListener(this));
        
        viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
   
   @Override
   public void onPageSelected(int arg0) {
    // TODO Auto-generated method stub
    bar.setSelectedNavigationItem(arg0);
    
    Fragment fragment = ((FragmentPageAdapter)viewpager.getAdapter()).getFragment(arg0);
    
    if (arg0 ==1 && fragment != null)
    {
     fragment.onResume(); 
    }
    
   }
   
   @Override
   public void onPageScrolled(int arg0, float arg1, int arg2) {
    // TODO Auto-generated method stub
    
   }
   
   @Override
   public void onPageScrollStateChanged(int arg0) {
    // TODO Auto-generated method stub
    
   }
  });
        
        //new code for drawer layout
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mCategoryList = (ExpandableListView) findViewById(R.id.left_drawer);
        
        //set up the adapter for the expandablelistview to display the categories. 
        
        mCategoryList.setAdapter(new expandableListViewAdapter(HomeScreen.this,category_name,subcategory_name, subCatCount));
        
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        
        // enable ActionBar application icon to be used to open or close the drawer layout
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);
    
        //defining the behavior when any group is clicked in expandable listview
        mCategoryList.setOnGroupClickListener(new OnGroupClickListener()
  {
   @Override
   public boolean onGroupClick(ExpandableListView parent, View view,
     int groupPosition, long id) {
    
    
          if (parent.isGroupExpanded(groupPosition)) 
          {
              parent.collapseGroup(groupPosition);
          } else 
          {
              if (groupPosition != previousGroup)
              {
               parent.collapseGroup(previousGroup);
              }
              previousGroup = groupPosition;
              parent.expandGroup(groupPosition);
          }
          
          parent.smoothScrollToPosition(groupPosition);
    return true;
   }
   
  });
  
      //defining the behavior when any child is clicked in expandable listview 
  mCategoryList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
   
   @Override
   public boolean onChildClick(ExpandableListView parent, View v,
     int groupPosition, int childPosition, long id) {
    
    //calling CatWiseSearchResults with parameters of subcat code. 
    //CatWiseSearchResults will fetch items based on subcatcode. 
    
       Intent intent=new Intent(HomeScreen.this,CatWiseSearchResults.class);
       
       ArrayList<SubCategory> tempList = new ArrayList<SubCategory>();
                tempList =  subcategory_name.get(groupPosition);
                
       intent.putExtra("subcategory", tempList.get(childPosition).getSubCatCode());
       startActivity(intent);
    mDrawerLayout.closeDrawer(mCategoryList);
    
       return true;
   }
  });
        
        // ActionBarDrawerToggle ties together the the proper interactions
        // between the sliding drawer and the action bar app icon
  
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, 
                R.string.drawer_open, R.string.drawer_close ){
         
                    @Override
                    public void onDrawerClosed(View view) {
                        
                        invalidateOptionsMenu();
                               
                    }

                    @Override
                    public void onDrawerOpened(View drawerView) {
                        
                        invalidateOptionsMenu();
                        
                    }

                };
                
        mDrawerLayout.setDrawerListener(mDrawerToggle);
                
 }
 
 
 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.start_screen, menu);
        return true;
    }
 
 
 @Override
 public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {
  // TODO Auto-generated method stub
  
 }

 @Override
 public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
  // TODO Auto-generated method stub
  viewpager.setCurrentItem(tab.getPosition());
 }

 @Override
 public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
  // TODO Auto-generated method stub
  
 }
 
 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
     // The action bar home/up action should open or close the drawer.
     // ActionBarDrawerToggle will take care of this.
     if (mDrawerToggle.onOptionsItemSelected(item)) {
         return true;
     }
     // Handle action buttons
     return true;
 }
 
 @Override
 protected void onPostCreate(Bundle savedInstanceState) {
     super.onPostCreate(savedInstanceState);
     // Sync the toggle state after onRestoreInstanceState has occurred.
     mDrawerToggle.syncState();
 }
 
 public class expandableListViewAdapter extends BaseExpandableListAdapter 
 {
   
  private LayoutInflater layoutInflater;
  private ArrayList<Category> categoryName=new ArrayList<Category>();
  ArrayList<ArrayList<SubCategory>> subCategoryName = new ArrayList<ArrayList<SubCategory>>();
        ArrayList<Integer> subCategoryCount = new ArrayList<Integer>();
  int count;
  Typeface type;
        
        SubCategory singleChild = new SubCategory();
        
        public expandableListViewAdapter(Context context, ArrayList<Category> categoryName, ArrayList<ArrayList<SubCategory>> subCategoryName, ArrayList<Integer> subCategoryCount) 
        {
 
      layoutInflater = LayoutInflater.from(context);
      this.categoryName= categoryName;
      this.subCategoryName = subCategoryName;
      this.subCategoryCount = subCategoryCount;
      this.count= categoryName.size();
      
      type= Typeface.createFromAsset(context.getAssets(),"fonts/book.TTF");
      
     }
        
        @Override
        public void onGroupCollapsed(int groupPosition) 
        {
         super.onGroupCollapsed(groupPosition);
        }
        
        @Override
        public void onGroupExpanded(int groupPosition) 
        {
         super.onGroupExpanded(groupPosition);
        }
        
        @Override
        public int getGroupCount() 
        {
        
            return categoryName.size();
        }
 
        @Override
        public int getChildrenCount(int i) 
        {
                 
         return (subCategoryCount.get(i));
         
        }
 
        @Override
        public Object getGroup(int i) 
        {
            return categoryName.get(i).getCatName();
        }
 
        @Override
        public SubCategory getChild(int i, int i1) 
        {
         
         ArrayList<SubCategory> tempList = new ArrayList<SubCategory>();
            tempList =  subCategoryName.get(i);
            return tempList.get(i1);
         
        }
 
        @Override
        public long getGroupId(int i) {
            return i;
        }
 
        @Override
        public long getChildId(int i, int i1) {
            return i1;
        }
 
        @Override
        public boolean hasStableIds() {
            return true;
        }
 
        @Override
        public View getGroupView(int i, boolean isExpanded, View view, ViewGroup viewGroup) 
        {
            
         if (view == null)
         {
          view = layoutInflater.inflate(R.layout.expandablelistcategory, viewGroup, false);
         }
         
         TextView textView = (TextView) view.findViewById(R.id.cat_desc_1);
            textView.setText(getGroup(i).toString());
            textView.setTypeface(type);
            
            return view;
            
        }
        
               
        @Override
        public View getChildView(int i, int i1, boolean isExpanded, View view, ViewGroup viewGroup) 
        { 
         if (view == null)
         {
         view = layoutInflater.inflate(R.layout.expandablelistviewsubcat, viewGroup, false);
         
         }
         
         singleChild = getChild(i,i1);
         
         TextView childSubCategoryName = (TextView) view.findViewById(R.id.subcat_name);
         childSubCategoryName.setTypeface(type);
         
         childSubCategoryName.setText(singleChild.getSubCatName());
         
            return view;
            
        }
 
        @Override
        public boolean isChildSelectable(int i, int i1) 
        {
            return true;
        }
        
        @Override
        public boolean areAllItemsEnabled()
        {
            return true;
        }
                      
    }
 
 public void getCatData()
 {
  category_name.clear();
  Category categoryDetails = new Category();
  
  categoryDetails.setCatCode(10);
  categoryDetails.setCatName("Grocery & Staples");
  
  category_name.add(categoryDetails);
  
  categoryDetails = new Category();
  categoryDetails.setCatCode(20);
  categoryDetails.setCatName("Biscuits, Snacks and Namkeens");
  category_name.add(categoryDetails);
  
  categoryDetails = new Category();
  categoryDetails.setCatCode(30);
  categoryDetails.setCatName("Beverages");
  category_name.add(categoryDetails);
  
  categoryDetails = new Category();
  categoryDetails.setCatCode(40);
  categoryDetails.setCatName("Packed Food and Condiments");
  category_name.add(categoryDetails);
  
  categoryDetails = new Category();
  categoryDetails.setCatCode(50);
  categoryDetails.setCatName("Personal Care");
  category_name.add(categoryDetails);
  
  categoryDetails = new Category();
  categoryDetails.setCatCode(60);
  categoryDetails.setCatName("Baby & Kids");
  category_name.add(categoryDetails);
  
  categoryDetails = new Category();
  categoryDetails.setCatCode(70);
  categoryDetails.setCatName("Household Cleaning");
  category_name.add(categoryDetails);
  
  categoryDetails = new Category();
  categoryDetails.setCatCode(80);
  categoryDetails.setCatName("Metal, Plastics and Microwaveware");
  category_name.add(categoryDetails);
  
  //----Populate Sub Category Codes
  subcategory_name.clear();
     
  ArrayList<SubCategory> subCategoryMatches = new ArrayList<SubCategory>();
     
  SubCategory subCategoryMatch = new SubCategory();
     
  subCategoryMatch.setSubCatName("Dal & Pulses");
  subCategoryMatch.setSubCatCode("1001");
  subCategoryMatches.add(subCategoryMatch);
     
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Oil & Ghee");
  subCategoryMatch.setSubCatCode("1002");
  subCategoryMatches.add(subCategoryMatch);
      
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Flour");
  subCategoryMatch.setSubCatCode("1003");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Spices, Seasoning, Cooking Pastes");
  subCategoryMatch.setSubCatCode("1004");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Rice & Soya Products");
  subCategoryMatch.setSubCatCode("1005");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Sugar & Salt");
  subCategoryMatch.setSubCatCode("1006");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Organic");
  subCategoryMatch.setSubCatCode("1007");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Dry Fruits & Nuts");
  subCategoryMatch.setSubCatCode("1008");
  subCategoryMatches.add(subCategoryMatch);
  
  subcategory_name.add(subCategoryMatches);
     subCatCount.add(subCategoryMatches.size());
     //---
     
     subCategoryMatches = new ArrayList<SubCategory>();
     
  subCategoryMatch = new SubCategory();
     
  subCategoryMatch.setSubCatName("Biscuits");
  subCategoryMatch.setSubCatCode("2001");
  subCategoryMatches.add(subCategoryMatch);
     
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Chips");
  subCategoryMatch.setSubCatCode("2002");
  subCategoryMatches.add(subCategoryMatch);
      
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Namkeen");
  subCategoryMatch.setSubCatCode("2003");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Cookies, Cakes & Rusk");
  subCategoryMatch.setSubCatCode("2004");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Popcorn");
  subCategoryMatch.setSubCatCode("2005");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Diet Snacks");
  subCategoryMatch.setSubCatCode("2006");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Confectionery");
  subCategoryMatch.setSubCatCode("2007");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Sweets");
  subCategoryMatch.setSubCatCode("2008");
  subCategoryMatches.add(subCategoryMatch);
  
  subcategory_name.add(subCategoryMatches);
     subCatCount.add(subCategoryMatches.size());
     
     //---
     
     subCategoryMatches = new ArrayList<SubCategory>();
     
  subCategoryMatch = new SubCategory();
     
  subCategoryMatch.setSubCatName("Juices");
  subCategoryMatch.setSubCatCode("3001");
  subCategoryMatches.add(subCategoryMatch);
     
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Soft Drinks");
  subCategoryMatch.setSubCatCode("3002");
  subCategoryMatches.add(subCategoryMatch);
      
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Milk Mixes");
  subCategoryMatch.setSubCatCode("3003");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Fruit Drinks");
  subCategoryMatch.setSubCatCode("3004");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Tea & Coffee");
  subCategoryMatch.setSubCatCode("3005");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Flavoured Drinks");
  subCategoryMatch.setSubCatCode("3006");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Energy Drinks");
  subCategoryMatch.setSubCatCode("3007");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Water");
  subCategoryMatch.setSubCatCode("3008");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Milk Drinks");
  subCategoryMatch.setSubCatCode("3009");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Powder Drinks");
  subCategoryMatch.setSubCatCode("3010");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Syrups / Squash");
  subCategoryMatch.setSubCatCode("3011");
  subCategoryMatches.add(subCategoryMatch);
  
  
  subcategory_name.add(subCategoryMatches);
     subCatCount.add(subCategoryMatches.size());
     
     //---
     
     subCategoryMatches = new ArrayList<SubCategory>();
     
  subCategoryMatch = new SubCategory();
     
  subCategoryMatch.setSubCatName("Breakfast & Cereals");
  subCategoryMatch.setSubCatCode("4001");
  subCategoryMatches.add(subCategoryMatch);
     
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Ketchup & Sauce");
  subCategoryMatch.setSubCatCode("4002");
  subCategoryMatches.add(subCategoryMatch);
      
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Spreads & Dressing");
  subCategoryMatch.setSubCatCode("4003");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Ready To Eat, Ready to Cook");
  subCategoryMatch.setSubCatCode("4004");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Noodles & Soup");
  subCategoryMatch.setSubCatCode("4005");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Pasta");
  subCategoryMatch.setSubCatCode("4006");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Breads");
  subCategoryMatch.setSubCatCode("4007");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Pickles, Olives and Papad");
  subCategoryMatch.setSubCatCode("4008");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Baking and Dessert Ingredients");
  subCategoryMatch.setSubCatCode("4009");
  subCategoryMatches.add(subCategoryMatch);
  
  subcategory_name.add(subCategoryMatches);
     subCatCount.add(subCategoryMatches.size());
     
     //---
     
     subCategoryMatches = new ArrayList<SubCategory>();
     
  subCategoryMatch = new SubCategory();
     
  subCategoryMatch.setSubCatName("Soaps & Handwash");
  subCategoryMatch.setSubCatCode("5001");
  subCategoryMatches.add(subCategoryMatch);
     
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Body Care");
  subCategoryMatch.setSubCatCode("5002");
  subCategoryMatches.add(subCategoryMatch);
      
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Hair Care");
  subCategoryMatch.setSubCatCode("5003");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Mens Grooming");
  subCategoryMatch.setSubCatCode("5004");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Oral Care");
  subCategoryMatch.setSubCatCode("5005");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Talk & Deodorant");
  subCategoryMatch.setSubCatCode("5006");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Facial Care");
  subCategoryMatch.setSubCatCode("5007");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Feminine Hygiene");
  subCategoryMatch.setSubCatCode("5008");
  subCategoryMatches.add(subCategoryMatch);
   
  subcategory_name.add(subCategoryMatches);
     subCatCount.add(subCategoryMatches.size());
     
     //---baby and kids
     
     subCategoryMatches = new ArrayList<SubCategory>();
     
  subCategoryMatch = new SubCategory();
     
  subCategoryMatch.setSubCatName("Baby Food");
  subCategoryMatch.setSubCatCode("6001");
  subCategoryMatches.add(subCategoryMatch);
     
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Baby Care");
  subCategoryMatch.setSubCatCode("6002");
  subCategoryMatches.add(subCategoryMatch);
      
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Diapers");
  subCategoryMatch.setSubCatCode("6003");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Kids");
  subCategoryMatch.setSubCatCode("6004");
  subCategoryMatches.add(subCategoryMatch);
   
  subcategory_name.add(subCategoryMatches);
     subCatCount.add(subCategoryMatches.size());
     
     //--- cleaning
     
     subCategoryMatches = new ArrayList<SubCategory>();
     
  subCategoryMatch = new SubCategory();
     
  subCategoryMatch.setSubCatName("Fabric");
  subCategoryMatch.setSubCatCode("7001");
  subCategoryMatches.add(subCategoryMatch);
     
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Utensil");
  subCategoryMatch.setSubCatCode("7002");
  subCategoryMatches.add(subCategoryMatch);
      
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Household");
  subCategoryMatch.setSubCatCode("7003");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Toilet");
  subCategoryMatch.setSubCatCode("7004");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Shoes");
  subCategoryMatch.setSubCatCode("7005");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Tissue Rolls");
  subCategoryMatch.setSubCatCode("7006");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Brooms & Brushes");
  subCategoryMatch.setSubCatCode("7007");
  subCategoryMatches.add(subCategoryMatch);
  
  subcategory_name.add(subCategoryMatches);
     subCatCount.add(subCategoryMatches.size());
     
     //---household goods
     
     subCategoryMatches = new ArrayList<SubCategory>();
     
  subCategoryMatch = new SubCategory();
     
  subCategoryMatch.setSubCatName("Freshners");
  subCategoryMatch.setSubCatCode("8001");
  subCategoryMatches.add(subCategoryMatch);
     
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Repellents");
  subCategoryMatch.setSubCatCode("8002");
  subCategoryMatches.add(subCategoryMatch);
      
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Pooja Needs");
  subCategoryMatch.setSubCatCode("8003");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Bulbs and CFLs");
  subCategoryMatch.setSubCatCode("8004");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("OTC Medicines");
  subCategoryMatch.setSubCatCode("8005");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Batteries");
  subCategoryMatch.setSubCatCode("8006");
  subCategoryMatches.add(subCategoryMatch);
  
  subCategoryMatch = new SubCategory();
  subCategoryMatch.setSubCatName("Disposibles & Napkins");
  subCategoryMatch.setSubCatCode("8007");
  subCategoryMatches.add(subCategoryMatch);
   
     subcategory_name.add(subCategoryMatches);
     subCatCount.add(subCategoryMatches.size());
     
 }
}



Code for CatWiseSearchResults.java which is a new activity for displaying the search results by sub category

package com.zing.basket;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.zing.basket.util.Product;


public class CatWiseSearchResults extends Activity 
{
   
  Typeface type;
  ListView searchResults;
  SQLiteDatabase sqLite;
  int count=0;
  String subCatCode;
  
  //This arraylist will have data as pulled from server. This will keep cumulating.
  ArrayList<Product> catWiseProductResults = new ArrayList<Product>();
  
  //Based on the subcatcode, only filtered products will be moved here from productResults
  ArrayList<Product> catWiseFilteredProductResults = new ArrayList<Product>();
  
  @Override
  public void onCreate(Bundle savedInstanceState)
  {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_catwisesearch);
   
   //ActionBar actionBar = getActionBar();
   //actionBar.hide();
   
   subCatCode = getIntent().getExtras().getString("subcategory");
   
   Log.d("basket","intent subcatcode-"+subCatCode);
   
   type= Typeface.createFromAsset(this.getAssets(),"fonts/book.TTF");
    
   searchResults = (ListView) findViewById(R.id.listview_search);
   
   myAsyncTask m= (myAsyncTask) new myAsyncTask().execute(subCatCode);
   
   //searchResults.setAdapter(new SearchResultsAdapter1(this,product_name));
   
  }
  
  class myAsyncTask extends AsyncTask<String, Void, String> 
  {
   JSONParser jParser;
   JSONArray productList;
   String url=new String();
   String textSearch;
   
  

   @Override
   protected void onPreExecute() {
    super.onPreExecute();
    productList=new JSONArray();
    jParser = new JSONParser();
   }

   @Override
   protected String doInBackground(String... sText) {
    
    url="http://lawgo.in/lawgo/productsbycat/user/1/searchcat/"+sText[0];
    getProductList(url);
    this.textSearch = sText[0];
    Log.d("basket","textSearch -"+textSearch);
    Log.d("basket",url);
    return "OK";
    
   }

   public void getProductList(String url)
   {
    
    Product tempProduct = new Product();
    String matchFound = "N";
    
    try {
     
     JSONObject json = jParser.getJSONFromUrl(url);
     
     productList = json.getJSONArray("ProductListByCat");
   
     Log.d("basket",""+productList.length()+"");
    
     for(int i=0;i<productList.length();i++)
     {
      tempProduct = new Product();
      
      JSONObject obj=productList.getJSONObject(i);
      
      tempProduct.setProductCode(obj.getString("ProductCode"));
      tempProduct.setProductName(obj.getString("ProductName"));
      tempProduct.setProductGrammage(obj.getString("ProductGrammage"));
      tempProduct.setProductBarcode(obj.getString("ProductBarcode"));
      tempProduct.setProductDivision(obj.getString("ProductCatCode"));
      tempProduct.setProductDepartment(obj.getString("ProductSubCode"));
      tempProduct.setProductMRP(obj.getString("ProductMRP"));
      tempProduct.setProductBBPrice(obj.getString("ProductBBPrice"));
      
      matchFound = "N";
      
      for (int j=0; j < catWiseProductResults.size();j++)
      {
       
       if (catWiseProductResults.get(j).getProductCode().equals(tempProduct.getProductCode()))
       {
        matchFound = "Y";
       
       }
      }
      
      if (matchFound == "N")
      {
       catWiseProductResults.add(tempProduct);
      }
      
     }
     
     //Log.d("basket",""+catWiseProductResults.size()+"");

    } catch (Exception e) {
     e.printStackTrace();
     //return ("Exception Caught");
    }
   }
   @Override
   protected void onPostExecute(String result) {

     super.onPostExecute(result);
     
     if(result.equalsIgnoreCase("Exception Caught"))
     {
      Toast.makeText(getApplicationContext(), "Unable to connect to server,please try later", Toast.LENGTH_LONG).show();
      Intent intent=new Intent(getApplicationContext(),HomeScreen.class);
      //pd.dismiss();
      intent.putExtra("userId", 1);
      startActivity(intent);
      finish();
     }
     else
     {
     
      filterProductArray(textSearch);
      //Log.d("basket","searchText ola-"+textSearch;
      //refresh view
      //Log.d("basket","size - "+catWiseFilteredProductResults.size());
      searchResults.setAdapter(new CatWiseSearchResultsAdapter(getApplicationContext(),catWiseFilteredProductResults));
      //pd.dismiss();
     }
   }

  }
  
  //this filters products from productResults and copies to filteredProductResults. 
  public void filterProductArray(String newText) 
  {
   //Log.d("basket","inside filterProductArray");
   String pName;
   
   catWiseFilteredProductResults.clear();
   for (int i = 0; i < catWiseProductResults.size(); i++)
   {
    //Log.d("basket","i="+i);
    //Log.d("basket","new text -dd"+newText);
    pName = catWiseProductResults.get(i).getProductDepartment();
    if ( pName.equals(newText))
    {
     catWiseFilteredProductResults.add(catWiseProductResults.get(i));
     //Log.d("basket","filtered-"+filteredProductResults.get(filteredProductResults.size()-1));
    }
   }
   
  }
}

class CatWiseSearchResultsAdapter extends BaseAdapter
{
  private LayoutInflater layoutInflater;
  //private ArrayList listData=new ArrayList();
  private ArrayList<Product> productDetails=new ArrayList<Product>();
  int count;
  Typeface type;
  Context context;
  
 public CatWiseSearchResultsAdapter(Context context, ArrayList<Product> product_details) {
  // TODO Auto-generated constructor stub
  layoutInflater = LayoutInflater.from(context);
   //Toast.makeText(context, "Inside Custom List one", Toast.LENGTH_LONG).show();
   //this.listData=listData;
   this.productDetails=product_details;
   this.count= product_details.size();
   this.context = context;
   type= Typeface.createFromAsset(context.getAssets(),"fonts/book.TTF");
 }

 @Override
 public int getCount() {
  // TODO Auto-generated method stub
  return count;
 }

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

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

 @Override
 public View getView(int position, View convertView, ViewGroup parent) 
 {
  
   ViewHolder holder;
      
   if (convertView == null) 
      {
       convertView = layoutInflater.inflate(R.layout.listtwo_searchresults, null);
          holder = new ViewHolder();
          holder.product_name = (TextView) convertView.findViewById(R.id.product_name);
          holder.product_mrp = (TextView) convertView.findViewById(R.id.product_mrp);
          holder.product_mrpvalue = (TextView) convertView.findViewById(R.id.product_mrpvalue);
          holder.product_bb = (TextView) convertView.findViewById(R.id.product_bb);
          holder.product_bbvalue = (TextView) convertView.findViewById(R.id.product_bbvalue);
    //holder.product_savings = (TextView) convertView.findViewById(R.id.product_savings);
    //holder.product_savingsvalue = (TextView) convertView.findViewById(R.id.product_savingsvalue);
    //holder.qty = (TextView) convertView.findViewById(R.id.qty);
    //holder.product_value = (TextView) convertView.findViewById(R.id.product_value);
          holder.addToCart = (Button) convertView.findViewById(R.id.add_cart);
    convertView.setTag(holder);
      } 
   else 
      {
             holder = (ViewHolder) convertView.getTag();
      }
  
       
   holder.product_name.setText(productDetails.get(position).getProductName());
   holder.product_name.setTypeface(type);
   
   
   holder.product_mrp.setTypeface(type);
   
   holder.product_mrpvalue.setText(productDetails.get(position).getProductMRP());
   holder.product_mrpvalue.setTypeface(type);
   
   
   holder.product_bb.setTypeface(type);
   
   holder.product_bbvalue.setText(productDetails.get(position).getProductBBPrice());
   holder.product_bbvalue.setTypeface(type);
   
   holder.addToCart.setOnClickListener(new MyPersonalClickListener("button_addtocart",productDetails.get(position),context));
   //holder.product_savings.setTypeface(type);
   
   
   //holder.product_savingsvalue.setTypeface(type);
   
   
   //holder.qty.setTypeface(type);
   
   //holder.product_value.setTypeface(type);
   
      return convertView;
 }
 
  static class ViewHolder 
  {         
         TextView product_name;
         TextView product_mrp;
         TextView product_mrpvalue;
         TextView product_bb;
         TextView product_bbvalue;
         TextView product_savings;
         TextView product_savingsvalue;
         TextView qty;
         TextView product_value;
         Button addToCart;
                
  }
  
  public class MyPersonalClickListener implements OnClickListener
     {

      String button_name;
      Product prod_name;
      int tempQty;
      int tempValue;
      SQLiteDatabase sqLite;
      Context context;
      
      public MyPersonalClickListener(String button_name, Product prod_name, Context context) 
      {
           this.prod_name = prod_name;
           this.button_name = button_name;
           this.context = context;
      }

      @Override
      public void onClick(View v)
      {
          Log.d("basket","OnClick - "+button_name+"-"+prod_name);
       if (button_name == "button_addtocart")
          {
        sqLite=context.openOrCreateDatabase("basketbuddy", context.MODE_PRIVATE, null);
        
        //check if item is already in cart
        Cursor cc = sqLite.rawQuery("SELECT PRODUCT_QTY, PRODUCT_VALUE FROM CART WHERE PRODUCT_CODE ="+Integer.parseInt(prod_name.getProductCode()), null);
        
        if (cc.getCount()== 0)
        {
         Log.d("basket","entry not found in cart -"+prod_name.getProductName());
         //if not found then insert, else update qty and product value. If qty > 10, dont update
              sqLite.execSQL("INSERT INTO CART (PRODUCT_CODE, PRODUCT_NAME, PRODUCT_BARCODE, PRODUCT_GRAMMAGE"+
               ", PRODUCT_MRP, PRODUCT_BBPRICE, PRODUCT_DIVISION, PRODUCT_DEPARTMENT,PRODUCT_QTY,PRODUCT_VALUE) VALUES("+
              prod_name.getProductCode()+",'"+ prod_name.getProductName()+ "','" +
               prod_name.getProductBarcode()+"','"+ prod_name.getProductGrammage()+"',"+
              Integer.parseInt(prod_name.getProductMRP())+","+ Integer.parseInt(prod_name.getProductBBPrice())+","+
               Integer.parseInt(prod_name.getProductDivision())+","+Integer.parseInt(prod_name.getProductDepartment())+
               ",1,"+ Integer.parseInt(prod_name.getProductBBPrice())+")");
            Toast.makeText(context,"Item "+prod_name.getProductName()+" added to Cart", Toast.LENGTH_LONG).show();
        }
        else
        {
         
         Log.d("basket","entry found in cart -"+prod_name.getProductName());
         if(cc.moveToFirst())
        {
         do{
          tempQty=cc.getInt(0);
          tempValue = cc.getInt(1);
         }while(cc.moveToNext());
        }
         
         if (tempQty < 10)
         {
          sqLite.execSQL("UPDATE CART SET PRODUCT_QTY = "+ (tempQty+1)+",PRODUCT_VALUE = "+ 
        (Integer.parseInt(prod_name.getProductBBPrice())+tempValue)+" WHERE PRODUCT_CODE ="+
        prod_name.getProductCode());
          Toast.makeText(context,"Item "+prod_name.getProductName()+" added to Cart", Toast.LENGTH_LONG).show();
         }
        }

        sqLite.close();
          }
       
      }

     }
}


Changes in AndroidManifest.xml

        <activity
            android:name="com.zing.basket.CatWiseSearchResults"
            android:label="@string/search"
             android:screenOrientation="portrait"
            android:launchMode="singleTask" >
        </activity>




Android NumberPicker - Scaling does not work

For my E Commerce application that I have been working on, I wanted to use the NumberPicker as it is quite a neat widget. I had to implement in my Shopping Cart where a ListView will be display the items that I have added in the Cart. Within each row of the ListView I had to add a NumberPicker so that the users can change the quantity of the product in the Cart.

So I added the NumberPicker to my layout using the following code.

<NumberPicker

android:id="@+id/numberPicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" />






By default, the size of the NumberPicker is quite big and is completely unusable within a ListView row. So I used the scaling parameters to reduce the size of the NumberPicker.

        android:scaleX=".5"
        android:scaleY=".5"


This would scale the size to 50%. However, this is where the problem starts. As you can see, the scaling happens and the size of the widget becomes smaller. But the padding appears around the widget (as can be seen from the blue rectangle). The problem is, there is no way for us to remove this padding. That is why, even though the widget scales, but it is useless for all practical purposes. Imagine having a ListView whose every row has a width as shown below. 




I did a lots of research, but failed. Hence had to revert back to good old 2 buttons and a text box in between. Or if your quantity options are not very big, I would recommend you can even use a Spinner to select the quantity.