package it.person.search;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import it.person.search.adapter.SearchAdapter;
import it.person.search.bean.SearchData;
public class MainActivity extends Activity {
private EditText mEditText;//搜索栏
private ListView mListView;//显示模糊查找返回的数据
private Context mContext;
private String[] mItems = {"五花肉", "天涯海角", "小葱拌豆腐"};
private String[] mNumbers = {"1234556676", "2342352345", "3243545666"};
private List<SearchData> mData;//模糊查找的时候返回的数据
private SearchAdapter mSearchAdapter;//ListView的适配
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
initView();
}
//初始化View
private void initView() {
mEditText = (EditText) findViewById(R.id.et_search);
mListView = (ListView) findViewById(R.id.lv);
//给EditText添加搜索栏控件文本变化监听器
mEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
search();//文本输入发生变化时开始进行模糊查找
}
});
createSearch();
}
//创建数据库,并给数据库添加数据
private void createSearch() {
//打开或创建search.db数据库
SQLiteDatabase db = openOrCreateDatabase("search.db", Context.MODE_PRIVATE, null);
//在数据库中创建mydata表,如果该表存在,则先删除后再创建,该表有三个字段,一个是id,一个是姓名(name),一个是编号(number)
db.execSQL("DROP TABLE IF EXISTS mydata");
db.execSQL("CREATE TABLE mydata (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, number VARCHAR)");
//给数据库插入数据
int len = mItems.length;
for (int i = 0; i < len; i++) {
ContentValues cv = new ContentValues();
cv.put("name", mItems[i]);
cv.put("number", mNumbers[i]);
db.insert("mydata", null, cv);
}
}
//搜索栏文本变化时开始进行模糊查找
private void search() {
String temp = mEditText.getText().toString().trim();
mData = new ArrayList<>();
if (!temp.equals("")) {
SQLiteDatabase db_search = openOrCreateDatabase("search.db", Context.MODE_PRIVATE, null);
Cursor csearch = db_search.rawQuery("SELECT * FROM mydata WHERE name LIKE '%" + temp + "%'", null);
while (csearch.moveToNext()) {
String name = csearch.getString(csearch.getColumnIndex("name"));
String number = csearch.getString(csearch.getColumnIndex("number"));
SearchData data = new SearchData();
data.setName(name);
data.setNumber(number);
mData.add(data);
}
db_search.close();
csearch.close();
}
if (mSearchAdapter == null) {
mSearchAdapter = new SearchAdapter(mContext, mData);
mListView.setAdapter(mSearchAdapter);
} else {
mSearchAdapter.refreshData(mData);
}
}
}