autocomplete textbox in android from sqlite database
In this Article, Today learn to autocomplete textbox in android from sqlite database follow the example. autocomplete textbox in android from SQLite database.
1.MainActivity.java:
package com.solar.sqliteautocomplete;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.widget.ArrayAdapter;
public class MainActivity extends Activity {
/*
* Change to type CustomAutoCompleteView instead of AutoCompleteTextView
* since we are extending to customize the view and disable filter
* The same with the XML view, type will be CustomAutoCompleteView
*/
CustomAutoCompleteView myAutoComplete;
// adapter for auto-complete
ArrayAdapter<String> myAdapter;
// for database operations
DatabaseHandler databaseH;
// just to add some initial value
String[] item = new String[] {"Please search..."};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
// instantiate database handler
databaseH = new DatabaseHandler(MainActivity.this);
// put sample data to database
insertSampleData();
// autocompletetextview is in activity_main.xml
myAutoComplete = (CustomAutoCompleteView) findViewById(R.id.myautocomplete);
// add the listener so it will tries to suggest while the user types
myAutoComplete.addTextChangedListener(new CustomAutoCompleteTextChangedListener(this));
// set our adapter
myAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, item);
myAutoComplete.setAdapter(myAdapter);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void insertSampleData(){
// CREATE
databaseH.create( new MyObject("January") );
databaseH.create( new MyObject("February") );
databaseH.create( new MyObject("March") );
databaseH.create( new MyObject("April") );
databaseH.create( new MyObject("May") );
databaseH.create( new MyObject("June") );
databaseH.create( new MyObject("July") );
databaseH.create( new MyObject("August") );
databaseH.create( new MyObject("September") );
databaseH.create( new MyObject("October") );
databaseH.create( new MyObject("November") );
databaseH.create( new MyObject("December") );
databaseH.create( new MyObject("New Caledonia") );
databaseH.create( new MyObject("New Zealand") );
databaseH.create( new MyObject("Papua New Guinea") );
databaseH.create( new MyObject("COFFEE-1K") );
databaseH.create( new MyObject("coffee raw") );
databaseH.create( new MyObject("authentic COFFEE") );
databaseH.create( new MyObject("k12-coffee") );
databaseH.create( new MyObject("view coffee") );
databaseH.create( new MyObject("Indian-coffee-two") );
}
// this function is used in CustomAutoCompleteTextChangedListener.java
public String[] getItemsFromDb(String searchTerm){
// add items on the array dynamically
List<MyObject> products = databaseH.read(searchTerm);
int rowCount = products.size();
String[] item = new String[rowCount];
int x = 0;
for (MyObject record : products) {
item[x] = record.objectName;
x++;
}
return item;
}
}
2.activity_main.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:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" />
<com.solar.sqliteautocomplete.CustomAutoCompleteView
android:id="@+id/myautocomplete"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:completionThreshold="1" >
</com.solar.sqliteautocomplete.CustomAutoCompleteView>
</LinearLayout>
3.CustomAutoCompleteTextChangedListener.java:
package com.solar.sqliteautocomplete;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.ArrayAdapter;
public class CustomAutoCompleteTextChangedListener implements TextWatcher{
public static final String TAG = "CustomAutoCompleteTextChangedListener.java";
Context context;
public CustomAutoCompleteTextChangedListener(Context context){
this.context = context;
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@SuppressLint("LongLogTag")
@Override
public void onTextChanged(CharSequence userInput, int start, int before, int count) {
// if you want to see in the logcat what the user types
Log.e(TAG, "User input: " + userInput);
MainActivity mainActivity = ((MainActivity) context);
// query the database based on the user input
mainActivity.item = mainActivity.getItemsFromDb(userInput.toString());
// update the adapater
mainActivity.myAdapter.notifyDataSetChanged();
mainActivity.myAdapter = new ArrayAdapter<String>(mainActivity, android.R.layout.simple_dropdown_item_1line, mainActivity.item);
mainActivity.myAutoComplete.setAdapter(mainActivity.myAdapter);
}
}
4.CustomAutoCompleteView.java:
package com.solar.sqliteautocomplete;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.AutoCompleteTextView;
public class CustomAutoCompleteView extends AutoCompleteTextView {
public CustomAutoCompleteView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public CustomAutoCompleteView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public CustomAutoCompleteView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
// this is how to disable AutoCompleteTextView filter
@Override
protected void performFiltering(final CharSequence text, final int keyCode) {
String filterText = "";
super.performFiltering(filterText, keyCode);
}
/*
* after a selection we have to capture the new value and append to the existing text
*/
@Override
protected void replaceText(final CharSequence text) {
super.replaceText(text);
}
}
5.DatabaseHandler.java:
package com.solar.sqliteautocomplete;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHandler extends SQLiteOpenHelper {
// for our logs
public static final String TAG = "DatabaseHandler.java";
// database version
private static final int DATABASE_VERSION = 4;
// database name
protected static final String DATABASE_NAME = "AutoCompleteDatabase";
// table details
public String tableName = "locations";
public String fieldObjectId = "id";
public String fieldObjectName = "name";
// constructor
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// creating table
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "";
sql += "CREATE TABLE " + tableName;
sql += " ( ";
sql += fieldObjectId + " INTEGER PRIMARY KEY AUTOINCREMENT, ";
sql += fieldObjectName + " TEXT ";
sql += " ) ";
db.execSQL(sql);
}
// When upgrading the database, it will drop the current table and recreate.
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "DROP TABLE IF EXISTS " + tableName;
db.execSQL(sql);
onCreate(db);
}
// create new record
// @param myObj contains details to be added as single row.
public boolean create(MyObject myObj) {
boolean createSuccessful = false;
if(!checkIfExists(myObj.objectName)){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(fieldObjectName, myObj.objectName);
createSuccessful = db.insert(tableName, null, values) > 0;
db.close();
if(createSuccessful){
Log.e(TAG, myObj.objectName + " created.");
}
}
return createSuccessful;
}
// check if a record exists so it won't insert the next time you run this code
public boolean checkIfExists(String objectName){
boolean recordExists = false;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT " + fieldObjectId + " FROM " + tableName + " WHERE " + fieldObjectName + " = '" + objectName + "'", null);
if(cursor!=null) {
if(cursor.getCount()>0) {
recordExists = true;
}
}
cursor.close();
db.close();
return recordExists;
}
// Read records related to the search term
public List<MyObject> read(String searchTerm) {
List<MyObject> recordsList = new ArrayList<MyObject>();
// select query
String sql = "";
sql += "SELECT * FROM " + tableName;
sql += " WHERE " + fieldObjectName + " LIKE '%" + searchTerm + "%'";
sql += " ORDER BY " + fieldObjectId + " DESC";
sql += " LIMIT 0,5";
SQLiteDatabase db = this.getWritableDatabase();
// execute the query
Cursor cursor = db.rawQuery(sql, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
// int productId = Integer.parseInt(cursor.getString(cursor.getColumnIndex(fieldProductId)));
String objectName = cursor.getString(cursor.getColumnIndex(fieldObjectName));
MyObject myObject = new MyObject(objectName);
// add to list
recordsList.add(myObject);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return the list of records
return recordsList;
}
}
6.MyObject.java:
package com.solar.sqliteautocomplete;
public class MyObject {
public String objectName;
// constructor for adding sample data
public MyObject(String objectName){
this.objectName = objectName;
}
}
7.AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.solar.sqliteautocomplete">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.SqliteAutocomplete">
<activity android:name=".MainActivity"></activity>
<activity android:name=".spinner.MainActivity1">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
No comments:
Post a Comment