Thursday, February 2, 2012

implementing search in Android without SearchManger and contentprovider

create table in your DBHelper class with following table.

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

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


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

searchAct.xml


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

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


searchAct.java

package com.inception.smui;

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

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

import com.ServiceMessenger.R;

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

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

public class SearchAct extends Activity {

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

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

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

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

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

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

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

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

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

    };


    TextWatcher watcher = new TextWatcher()
    {

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

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


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

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

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

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

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


        }

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

        }

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

        }

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

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

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

        }

    };

    public ArrayList<Category> prepareCatlogPath()
    {

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

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


        }

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

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

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

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

        return catString;
    }
}


searchrow.xml 

here am showing the search result.


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

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


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

package com.inception.smui;

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

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

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


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

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

        return mCategory.size();
    }

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

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

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

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

        }

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

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

        return convertView;
    }

}

No comments:

Post a Comment