View

Saturday, 2 July 2011

How to use Autocomplete searchbox in Database?

Autocomplete means it show the complete text automatically.It have two types
1.Single line autocomplete
2.Multi line autocomplete
what letter we type in the searchbox,that letter of the complete words  to show.Here i use autocomplete searchbox ,The select item can pass into the textview
.I use DATABASE NAME as="itemsearchsqlite.db",TABLE NAME as="itemsearch" and DB COLUMN NAME as="item_name".
I use two java classes namely Home.java and SQLiteItemsearch.java
//SQLiteItemSearch.java//
------------------------
package com.autocomplete.sample;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class SQLiteItemSearch extends SQLiteOpenHelper
{
    private static final String DB_NAME = "itemsearchsqlite.db";
    private static final int DB_VERSION_NUMBER = 1;
    private static final String DB_TABLE_NAME = "itemsearch";
    private static final String DB_COLUMN_1_NAME = "item_name";

    private static final String DB_CREATE_SCRIPT = "create table " + DB_TABLE_NAME +
                            " (_id integer primary key autoincrement, item_name text not null);)";

    private SQLiteDatabase sqliteDBInstance = null;

    public SQLiteItemSearch(Context context)
    {
        super(context, DB_NAME, null, DB_VERSION_NUMBER);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        // TODO: Implement onUpgrade
    }

    @Override
    public void onCreate(SQLiteDatabase sqliteDBInstance)
    {
        Log.i("onCreate", "Creating the database...");
        sqliteDBInstance.execSQL(DB_CREATE_SCRIPT);
    }

    public void openDB() throws SQLException
    {
        Log.i("openDB", "Checking sqliteDBInstance...");
        if(this.sqliteDBInstance == null)
        {
            Log.i("openDB", "Creating sqliteDBInstance...");
            this.sqliteDBInstance = this.getWritableDatabase();
        }
    }

    public void closeDB()
    {
        if(this.sqliteDBInstance != null)
        {
            if(this.sqliteDBInstance.isOpen())
                this.sqliteDBInstance.close();
        }
    }

    public long insertitmSearch(String ItemBrandName)
    {
        ContentValues contentValues = new ContentValues();
        contentValues.put(DB_COLUMN_1_NAME, ItemBrandName);
        Log.i(this.toString() + " - insertitmSearch", "Inserting: " + ItemBrandName);
        return this.sqliteDBInstance.insert(DB_TABLE_NAME, null, contentValues);
    }

    public boolean removeitmSearch(String ItemBrandName)
    {
        int result = this.sqliteDBInstance.delete(DB_TABLE_NAME, "item_name='" + ItemBrandName + "'", null);

        if(result > 0)
            return true;
        else
            return false;
    }

    public long updateitmSearch(String oldItemBrandName, String newItemBrandName)
    {
        ContentValues contentValues = new ContentValues();
        contentValues.put(DB_COLUMN_1_NAME, newItemBrandName);
        return this.sqliteDBInstance.update(DB_TABLE_NAME, contentValues, "item_name='" + oldItemBrandName + "'", null);
    }

    public String[] getAllItemFilter()
    {
        Cursor cursor = this.sqliteDBInstance.query(DB_TABLE_NAME, new String[] {DB_COLUMN_1_NAME}, null, null, null, null, null);

        if(cursor.getCount() >0)
        {
            String[] str = new String[cursor.getCount()];
            int i = 0;

            while (cursor.moveToNext())
            {
                 str[i] = cursor.getString(cursor.getColumnIndex(DB_COLUMN_1_NAME));
                 i++;
             }
            return str;
        }
        else
        {
            return new String[] {};
        }
    }
}

Then again we have to insert a rows of dataitems inside of the Home.java class
public class Home extends Activity {
 private SQLiteItemSearch sqllitebb;
 TextView tv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_item);
       
        final AutoCompleteTextView actv=(AutoCompleteTextView)findViewById(R.id.autocompleteitem);
        sqllitebb=new SQLiteItemSearch(Home.this);
        sqllitebb.openDB();
     // Insert a few item list statically//
     
        sqllitebb.insertitmSearch("Color Monitor");
        sqllitebb.insertitmSearch("Compact Disk");
        sqllitebb.insertitmSearch("Computer");
       sqllitebb.insertitmSearch("Copy Righter");
       sqllitebb.insertitmSearch("Hard Disk");
       sqllitebb.insertitmSearch("HP Printer");
       sqllitebb.insertitmSearch("HP Laser Printer");
       sqllitebb.insertitmSearch("HP Injet Printer");
      //  sqllitebb.removeitmsearch("Computer");
       // sqllitebb.updateitmSearch("Computer","DELL");
     final  String[] deal = sqllitebb.getAllItemFilter();
      
       // Print out the values to the log
       for(int i = 0; i < deal.length; i++)
       {
           Log.i(this.toString(), deal[i]);
       }
       ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,deal);
       actv.setAdapter(adapter); 
       actv.setThreshold(1);
       actv.setOnItemClickListener(new OnItemClickListener() {
           public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            tv=(TextView)findViewById(R.id.selecteditem_tv);
            tv.setText(deal[arg2]);
            arg0.getItemAtPosition(arg2);
                Log.i("SELECTED TEXT WAS------->",  deal[arg2]);
           }
       });
    }
    public void onDestroy()
    {
        super.onDestroy();
        sqllitebb.close();
    }
}

Have to drag and drop the autocomplete control,the two textview controls.
[code=list_item.xml]

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="5dp" android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ITEM_SEARCH" />
    <AutoCompleteTextView android:id="@+id/autocompleteitem"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"/>
    <TextView android:text="TextView" android:id="@+id/selecteditem_tv" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
</LinearLayout>
   



If u want to check the database in sqlite,no problem Go to DDMS or
Go to Window->open Perspective-> select File explorer->go to data, then->select data->inside of the data all packages are availabel,here my application
package name is com.autocomplete.sample,after select our package there is two options are availabel 1.databases,2.lib.first have to select it or open it.open
databases inside of the databases our application database name itemsearchsqlite.db had held we have to pull a file from the device.u have to choose the db
in any location,for example i select desktop and pull it .Then u go to Android-SDK,inside of the SDK u have to open Tools,because the sqlite3 has present
inside of the tools.u click the sqlite3.open our db in desktop asusal click right side ,go to open with and select SQLITE3.At the begining we have to type
DOT or .tables,In sqlite it shows our correct and current table name at the final open our table like select * from itemsearch;
finished all the things.ITS show our records.
Note:If u not understand my hints means better u see my screen schots.






Go to Android SDK




Open DB in desktop




Download full source code

 


16 comments:

  1. Followers (28) follow balik gan..

    ReplyDelete
  2. excellent tutorial, but how suppose if I select the compact disk it will show the information about it. Do I need to make another database?

    ReplyDelete
    Replies
    1. Yes sure,we can use it...But calling a different table not a Daatabase

      Delete
  3. Hello,
    Thanks very much for this tutorial, it is indeed quite interesting and education. I copied the same code but was having errors as follows:

    10-08 00:58:02.621: E/AndroidRuntime(420): FATAL EXCEPTION: main
    10-08 00:58:02.621: E/AndroidRuntime(420): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.uchenna.testing/com.uchenna.testing.SQLiteItemSearch}: java.lang.InstantiationException: com.uchenna.testing.SQLiteItemSearch
    10-08 00:58:02.621: E/AndroidRuntime(420): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
    10-08 00:58:02.621: E/AndroidRuntime(420): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
    10-08 00:58:02.621: E/AndroidRuntime(420): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
    10-08 00:58:02.621: E/AndroidRuntime(420): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
    10-08 00:58:02.621: E/AndroidRuntime(420): at android.os.Handler.dispatchMessage(Handler.java:99)
    10-08 00:58:02.621: E/AndroidRuntime(420): at android.os.Looper.loop(Looper.java:123)
    10-08 00:58:02.621: E/AndroidRuntime(420): at android.app.ActivityThread.main(ActivityThread.java:4627)
    10-08 00:58:02.621: E/AndroidRuntime(420): at java.lang.reflect.Method.invokeNative(Native Method)
    10-08 00:58:02.621: E/AndroidRuntime(420): at java.lang.reflect.Method.invoke(Method.java:521)
    10-08 00:58:02.621: E/AndroidRuntime(420): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
    10-08 00:58:02.621: E/AndroidRuntime(420): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
    10-08 00:58:02.621: E/AndroidRuntime(420): at dalvik.system.NativeStart.main(Native Method)
    10-08 00:58:02.621: E/AndroidRuntime(420): Caused by: java.lang.InstantiationException: com.uchenna.testing.SQLiteItemSearch
    10-08 00:58:02.621: E/AndroidRuntime(420): at java.lang.Class.newInstanceImpl(Native Method)
    10-08 00:58:02.621: E/AndroidRuntime(420): at java.lang.Class.newInstance(Class.java:1429)
    10-08 00:58:02.621: E/AndroidRuntime(420): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
    10-08 00:58:02.621: E/AndroidRuntime(420): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
    10-08 00:58:02.621: E/AndroidRuntime(420): ... 11 more

    ReplyDelete
    Replies
    1. Its showing Unable to instantiate activity ComponentInfo,Better u check in Manifest.xml file..Did u copied my code ? or Pls take a download full source code

      Delete
    2. Thanks SaGa,
      Please can you tell me where to get the source code for this exercise so that I can download it.
      Thanks for your help.

      Delete
    3. http://saga-androidapplication.webgarden.com/

      Check this Site.The Project Name is Auto Complete.

      Delete
  4. Thank you very much, I really appreciate your help. I just noticed that the was on the manifest and corrected it immediately and now it is working.
    Please I want to ask how I could add more two tables (id number and country of origin). Actually, am creating a bus stop database that will have 3 tables: bus_stopTable, LongitudeTable and LatitudeTable. When user types the bus stop name, it will show the longitude and latitude of that bust stop. Going by your tutorial, I think it is possible but I have tried it but got 11 errors. Please assist me.

    Thanks once again.

    ReplyDelete
  5. I have been reading your posts regularly. I need to say that you are doing a fantastic job. Please keep up the great work.

    HP OfficeJet 4627 Printer suport

    ReplyDelete
  6. It's exciting that multiple of the bloggers your points supported to clarify a few points for me as entirely as giving... very particular helpful content.
    Java Training in Chennai | Best Android Training in Chennai | Android Training with placement in Chennai | Selenium Training Course in Velachery

    ReplyDelete
  7. Awesome Post! I like writing style, how you describing the topics throughout the post. I hope many web reader will keep reading your post at the end, Thanks for sharing your view.
    Android Training Institutes in Chennai|Android Training Institute in Chennai|iOS Training

    ReplyDelete
  8. Really its very useful information that you have shared and thanks for sharing the information with us.
    123 HP Officejet 4627

    ReplyDelete
  9. Greetings from Florida! I’m bored at work, so I decided to browse your site on my iPhone during lunch break.
    safety courses in chennai

    ReplyDelete