通过SQLite实现搜索功能

首先进行布局 (需要借助前面博客里的代码)



    

    

        

        

            

            

                

                

                

                    

                    

完成监听

public class SearchActivity extends BaseActivity {

	private Button searchBtn;
	private EditText searchText;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);

		super.init("搜索问题", 2);

		searchBtn = (Button) findViewById(R.id.search_btn);
		searchText = (EditText) findViewById(R.id.search_text);

		searchBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String text = searchText.getText().toString();

				Intent in = new Intent(SearchActivity.this,
						QuestionListActivity.class);
				in.putExtra("keyword", text);
				startActivity(in);
			}
		});

	}
}

修改分页查询方法,多加入一个关键字

public static List> listDataPage(int pageNo,
			int pageSize, String keyword) {
		List> allValues = new ArrayList>();
		String sql = "SELECT id,question,answer FROM question WHERE question LIKE ? LIMIT ?,?";
		Cursor c = Globals.dbc.getReadableDatabase().rawQuery(
				sql,
				new String[] { "%" + keyword + "%",
						(pageNo - 1) * pageSize + "", pageSize + "" });
		c.moveToFirst();
		while (!c.isAfterLast()) {
			Map map = new HashMap();
			map.put("id", c.getInt(0));
			map.put("question", c.getInt(0) + "、" + c.getString(1));
			map.put("answer", c.getString(2));
			allValues.add(map);

			c.moveToNext();
		}
		c.close();

		return allValues;
	}

	public static int getAllCount(String keyword) {
		String sql = "SELECT COUNT(*) FROM question WHERE question LIKE ?";
		Cursor c = Globals.dbc.getReadableDatabase().rawQuery(sql,
				new String[] { "%" + keyword + "%" });
		c.moveToFirst();
		int count = c.getInt(0);
		c.close();
		return count;
	}

修改ListActivity,处理关键字的接收和查询。

protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_question_list);
		// 接收关键字
		keyword = getIntent().getStringExtra("keyword");
		if (keyword == null) {
			super.init("全部问题", 1);
			keyword = "";
		} else {
			super.init("搜索: " + keyword, 1);
		}

		list = (ListView) findViewById(R.id.list);

		allValues = QuestionDAOUtils.listDataPage(pageNo, pageSize,keyword);
		// 查询记录数
		count = QuestionDAOUtils.getAllCount(keyword);





































你可能感兴趣的:(android)