搜索中需要记录用户的搜索历史,以方便用户在下次搜索时快捷搜索。
思路:
使用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;
public static String filepath;
public static void CreateDB(String dbName,Context context){
filepath = context.getFilesDir().toString()+"/"+dbName;
db = SQLiteDatabase.openOrCreateDatabase(filepath, null);
}
public static boolean Insert(String name){
boolean result = false;
try{
System.out.println("db state:"+db.isOpen());
if(!db.isOpen())
db.openOrCreateDatabase(filepath, null);
ContentValues value = new ContentValues();
value.put("name", name);
db.insertOrThrow("input", null, value);
// db.execSQL("insert into input values(null,?)",new String[]{name});
}catch(SQLException e){
e.printStackTrace();
db.execSQL("create table input(id integer primary key autoincrement,name varchar(100))");
ContentValues value = new ContentValues();
value.put("name", name);
db.insertOrThrow("input", null, value);
// db.execSQL("insert into input values(null,?)",new String[]{name});
}
finally{
Log.i("insert into db",name);
}
return result;
}
public static Cursor Query(String query){
if(query != null){
try{
if(!db.isOpen())
db.openOrCreateDatabase(filepath, null);
String selection = "name like \'" + query +"%\'";
return db.query("input",new String[]{"name"}, selection, null, null, null, null);
}
catch(SQLException e)
{
db.execSQL("create table input(id integer primary key autoincrement,name varchar(100))");
String selection = "name like \'" + query +"%\'";
return db.query("input",new String[]{"name"}, selection, null, null, null, null);
}
}
else
return null;
}
public static void Close(){
if(db!=null && db.isOpen())
db.close();
}
public static void Clear(){
//清空搜索数据库
try{
if(!db.isOpen())
db.openOrCreateDatabase(filepath, null);
db.execSQL("delete * from input");
}catch(SQLException e){
e.printStackTrace();
}
}
}
3.在Activity 中调用
AutoCompleteTextView searchText = (AutoCompleteTextView)findViewById(R.id.search_text);
Complete_Db.CreateDB("search.db", SearchActivity.this);
List<String> search_hint = new ArrayList<String>();
System.out.println("query string :"+searchText.getText().toString().trim());
Cursor cursor = Complete_Db.Query(searchText.getText().toString().trim());
cursor.moveToFirst();
while(cursor.isAfterLast() == false){
Log.i("query result",cursor.getString(0));
search_hint.add(cursor.getString(0));
cursor.moveToNext();
}
search_hint.add("清除历史");//用于清除历史记录
String hints[] = new String[search_hint.size()];
search_hint.toArray(hints);
ArrayAdapter<String> adapter= new ArrayAdapter<String>(
SogouSearchActivity.this, R.layout.auto_complete_list,hints);
for(int i=0;i<hints.length;i++){
System.out.println("db string:"+hints[i]);
}
searchText.setAdapter(adapter);
cursor.close();
searchText.setThreshold(1);
searchText.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
if(searchText.getText().toString().equals("清除历史")){
Log.i("touch clear","history");
Complete_Db.Clear();
searchText.setText(null);
}
}
});
另外需要增加一个事件,用于监听当输入改变时从数据库中取数据:
searchText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
List<String> search_hint = new ArrayList<String>();
System.out.println("query string :"+searchText.getText().toString().trim());
Cursor cursor = Complete_Db.Query(searchText.getText().toString().trim());
cursor.moveToFirst();
while(cursor.isAfterLast() == false){
Log.i("query result",cursor.getString(0));
search_hint.add(cursor.getString(0));
cursor.moveToNext();
}
search_hint.add("清除历史");
String hints[] = new String[search_hint.size()];
search_hint.toArray(hints);
ArrayAdapter<String> adapter= new ArrayAdapter<String>(
SogouSearchActivity.this, R.layout.auto_complete_list,hints);
for(int i=0;i<hints.length;i++){
System.out.println("db string:"+hints[i]);
}
searchText.setAdapter(adapter);
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
Log.i("text",s.toString());
// TODO Auto-generated method stub
}
});
@Override
public void onDestroy(){
super.onDestroy();
Complete_Db.Close();
}