android AutoCompleteTextView+ SQLite
搜索中需要记录用户的搜索历史,以方便用户在下次搜索时快捷搜索。
思路:
使用SQLite作为用户输入的记录,当用户查询时从数据库中取出数据作为AutoCompleteTextView的数据源。
具体代码:
1.在main.xml 或者 自己定义的xml文件中 增加 AutoCompleteTextView
<AutoCompleteTextView android:id="@+id/search_text" android:layout_width="0dip"
android:layout_height="wrap_content"android:layout_weight="1.0"
android:layout_marginTop="6dip"android:layout_marginBottom="6dip"
android:clickable="true"android:inputType="none"
android:textSize="18sp"android:textstyle="normal"
android:textColor="@android:color/primary_text_light"
android:textColorHint="@color/search_hint" />2.数据库操作,这里可以写你自己具体的数据库操作,下面是我的代码
public class Complete_Db {
public static SQLiteDatabase db;
publicstaticStringfilepath;
publicstaticvoidCreateDB(StringdbName,Contextcontext){
filepath=context.getFilesDir().toString()+"/"+dbName;
db=SQLiteDatabase.openOrCreateDatabase(filepath,null);
}
publicstaticbooleanInsert(Stringname){
booleanresult=false;
try{
System.out.println("dbstate:"+db.isOpen());
if(!db.isOpen())
db.openOrCreateDatabase(filepath,null);
ContentValuesvalue=newContentValues();
value.put("name",name);
db.insertOrThrow("input",null,value);
//db.execSQL("insertintoinputvalues(null,?)",newString[]{name});
}catch(SQLExceptione){
e.printStackTrace();
db.execSQL("createtableinput(idintegerprimarykeyautoincrement,namevarchar(100))");
ContentValuesvalue=newContentValues();
value.put("name",name);
db.insertOrThrow("input",null,value);
//db.execSQL("insertintoinputvalues(null,?)",newString[]{name});
}
finally{
Log.i("insertintodb",name);
}
returnresult;
}
publicstaticCursorQuery(Stringquery){
if(query!=null){
try{
if(!db.isOpen())
db.openOrCreateDatabase(filepath,null);
Stringselection="namelike\'"+query+"%\'";
returndb.query("input",newString[]{"name"},selection,null,null,null,null);
}
catch(SQLExceptione)
{
db.execSQL("createtableinput(idintegerprimarykeyautoincrement,namevarchar(100))");
Stringselection="namelike\'"+query+"%\'";
returndb.query("input",newString[]{"name"},selection,null,null,null,null);
}
}
else
returnnull;
}
publicstaticvoidClose(){
if(db!=null&&db.isOpen())
db.close();
}
publicstaticvoidClear(){
//清空搜索数据库
try{
if(!db.isOpen())
db.openOrCreateDatabase(filepath,null);
db.execSQL("delete*frominput");
}catch(SQLExceptione){
e.printStackTrace();
}
}
}3.在Activity 中调用
AutoCompleteTextView searchText = (AutoCompleteTextView)findViewById(R.id.search_text);
Complete_Db.CreateDB("search.db", SearchActivity.this);
List<String>search_hint=newArrayList<String>();
System.out.println("querystring:"+searchText.getText().toString().trim());
Cursorcursor=Complete_Db.Query(searchText.getText().toString().trim());
cursor.moveToFirst();
while(cursor.isAfterLast()==false){
Log.i("queryresult",cursor.getString(0));
search_hint.add(cursor.getString(0));
cursor.moveToNext();
}
search_hint.add("清除历史");//用于清除历史记录
Stringhints[]=newString[search_hint.size()];
search_hint.toArray(hints);
ArrayAdapter<String>adapter=newArrayAdapter<String>(
SogouSearchActivity.this,R.layout.auto_complete_list,hints);
for(inti=0;i<hints.length;i++){
System.out.println("dbstring:"+hints[i]);
}searchText.setAdapter(adapter);
cursor.close();
searchText.setThreshold(1);
searchText.setOnItemClickListener(new OnItemClickListener() {public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
longarg3){
//TODOAuto-generatedmethodstub
if(searchText.getText().toString().equals("清除历史")){
Log.i("touchclear","history");
Complete_Db.Clear();
searchText.setText(null);
}
}
});另外需要增加一个事件,用于监听当输入改变时从数据库中取数据:
searchText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
//TODOAuto-generatedmethodstub
List<String>search_hint=newArrayList<String>();
System.out.println("querystring:"+searchText.getText().toString().trim());
Cursorcursor=Complete_Db.Query(searchText.getText().toString().trim());
cursor.moveToFirst();
while(cursor.isAfterLast()==false){
Log.i("queryresult",cursor.getString(0));
search_hint.add(cursor.getString(0));
cursor.moveToNext();
}
search_hint.add("清除历史");
Stringhints[]=newString[search_hint.size()];
search_hint.toArray(hints);
ArrayAdapter<String>adapter=newArrayAdapter<String>(
SogouSearchActivity.this,R.layout.auto_complete_list,hints);
for(inti=0;i<hints.length;i++){
System.out.println("dbstring:"+hints[i]);
}
searchText.setAdapter(adapter);
}public void beforeTextChanged(CharSequence s, int start, int count,
intafter){
//TODOAuto-generatedmethodstub
}
publicvoidonTextChanged(CharSequences,intstart,intbefore,
intcount){
Log.i("text",s.toString());
//TODOAuto-generatedmethodstub
}
});@Override
publicvoidonDestroy(){
super.onDestroy();
Complete_Db.Close();
}