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>




2 comments:

  1. Hi in HomeScreen.java at line number 40-42 and 35 getting errors ,
    Search search;
    MyCart mycart;
    QuickOrder quickorder;
    and getting errors at FragmentPageAdapter can't be resolve to a type, can you plz give me the solutions for these issues:

    ReplyDelete
  2. I think that is because you have to include the Object classes Category and SubCategory. Now you can get the entire source code here. http://semycolon.blogspot.in/2015/03/source-code-e-commerce-app.html

    ReplyDelete