近期学弟问了用SQLite存储List,今天没事,写一下
需求:用一种存储方式,存储搜索历史记录,数据不可重复,以列表形式倒序输出
解决:本篇介绍用SQLite实现,以后会用SharedPreferences等实现
前端页面写的简单一点,布局就不贴出来了,大概就是这个样子:
1、创建数据库,创建表,创建一个类SearchListSQLiteOpenHelper继承SQLiteOpenHelper
public class SearchListSQLiteOpenHelper extends SQLiteOpenHelper { private final static String DB_NAME = "keep.db"; private final static int DB_VERSION = 1; public SearchListSQLiteOpenHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String sqlStr = "CREATE TABLE IF NOT EXISTS building (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT);";//创建存储搜索楼盘的表 db.execSQL(sqlStr); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
2、创建数据库操作类SearchListDbOperation ,用于对数据进行,增删查等操作
/** * 搜素列表数据库操作类 * * tableName 表名 */ public class SearchListDbOperation { SearchListSQLiteOpenHelper searchListSQLiteOpenHelper; SQLiteDatabase recordsDb; String tableName; public SearchListDbOperation(Context context, String tableName){ searchListSQLiteOpenHelper = new SearchListSQLiteOpenHelper(context); this.tableName = tableName; } //添加搜索记录 public void addRecords(String record) { if (!isHasRecord(record)) { recordsDb = searchListSQLiteOpenHelper.getReadableDatabase(); ContentValues values = new ContentValues(); values.put("name", record); //添加 recordsDb.insert(tableName, null, values); //关闭 recordsDb.close(); } } //判断是否含有该搜索记录 public boolean isHasRecord(String record) { boolean isHasRecord = false; recordsDb = searchListSQLiteOpenHelper.getReadableDatabase(); Cursor cursor = recordsDb.query(tableName, null, null, null, null, null, null); while (cursor.moveToNext()) { if (record.equals(cursor.getString(cursor.getColumnIndexOrThrow("name")))) { isHasRecord = true; } } //关闭数据库 recordsDb.close(); return isHasRecord; } //获取全部搜索记录 public List<String> getRecordsList() { List<String> recordsList = new ArrayList<>(); recordsDb = searchListSQLiteOpenHelper.getReadableDatabase(); Cursor cursor = recordsDb.query(tableName, null, null, null, null, null, null); while (cursor.moveToNext()) { String name = cursor.getString(cursor.getColumnIndexOrThrow("name")); recordsList.add(name); } //关闭数据库 recordsDb.close(); return recordsList; } //清空搜索记录 public void deleteAllRecords() { recordsDb = searchListSQLiteOpenHelper.getWritableDatabase(); recordsDb.execSQL("delete from "+tableName); recordsDb.close(); } }
3、使用ListView展示搜索记录列表,创建适配器
public class SearchRecordsListAdaptet extends BaseAdapter { private Context context; private List<String> searchRecordsList; private LayoutInflater inflater; public SearchRecordsListAdaptet(Context context, List<String> searchRecordsList) { this.context = context; this.searchRecordsList = searchRecordsList; inflater = LayoutInflater.from(context); } @Override public int getCount() { return searchRecordsList.size() == 0 ? 0 : searchRecordsList.size(); } @Override public Object getItem(int position) { return searchRecordsList.size() == 0 ? null : searchRecordsList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if(null == convertView){ viewHolder = new ViewHolder(); //search_records_list_item布局很简单,就一个TextView convertView = inflater.inflate(R.layout.search_records_list_item,null); viewHolder.search_records_list_tv = (TextView) convertView.findViewById(R.id.search_records_list_tv); convertView.setTag(viewHolder); }else{ viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.search_records_list_tv.setText(searchRecordsList.get(position)); return convertView; } private class ViewHolder { TextView search_records_list_tv; } }
4、在Activity中的使用
public class SearchActivity extends AppCompatActivity { private EditText search_et; private Button search_bt,search_bt2; private ListView search_lv; private List<String> searchRecordsList; private List<String> tempList;//临时列表 private SearchListDbOperation searchListDbOperation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); initTheView(); } public void initTheView(){ search_et = (EditText) findViewById(R.id.search_et); search_bt = (Button) findViewById(R.id.search_bt); search_bt2 = (Button) findViewById(R.id.search_bt2); search_lv = (ListView) findViewById(R.id.search_lv); searchListDbOperation = new SearchListDbOperation(this,"building");//传入表名,以对表进行操作 searchRecordsList = new ArrayList<>(); tempList = new ArrayList<>(); tempList.addAll(searchListDbOperation.getRecordsList()); reversedList();//倒序输出 //设置适配器 final SearchRecordsListAdaptet adaptet = new SearchRecordsListAdaptet(this,searchRecordsList); search_lv.setAdapter(adaptet); search_bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (search_et.getText().toString().length() > 0) { String record = search_et.getText().toString(); //判断数据库中是否存在该记录 if (!searchListDbOperation.isHasRecord(record)) { tempList.add(record); } //将搜索记录保存至数据库中 searchListDbOperation.addRecords(record); reversedList(); adaptet.notifyDataSetChanged(); } else { MyToast.showToast(SearchActivity.this,"搜索内容不能为空").show(); } } }); //清空所有历史记录 search_bt2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { tempList.clear(); reversedList(); searchListDbOperation.deleteAllRecords(); adaptet.notifyDataSetChanged(); } }); } //颠倒list顺序,用户输入的信息会从上依次往下显示 private void reversedList(){ searchRecordsList.clear(); for(int i = tempList.size() - 1 ; i >= 0 ; i --){ searchRecordsList.add(tempList.get(i)); } } }到此就完成了!