Android开发--模拟通讯录包含模糊查询

实习期间,由于工作需要学习了一下Android开发,刚学习没几天,觉得光看书没什么太大进步,便尝试着写了一个验证登录的小程序,验证的过程比较简单,就是SQLite数据库的一个匹配过程,成功登录后,页面跳转到一个自定义的通讯录,也是查询数据库的过程,即读取数据库中的信息进行列表展示的一个过程。我想在该页面上实现一个具有模糊查询的功能,类似于手机中通讯录查找的样子。几经折腾终于把雏形写出来了,漏洞肯定很多,但毕竟是我的“helloword”,就在博文中纪念一下吧,上传通讯录部分代码,也可以为刚入门的同学做个参考。
package com.channelsoft.activity;


import java.util.ArrayList;
import java.util.HashMap;
import com.channelsoft.myfirstandroid.R;
import com.channelsoft.po.Person;

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.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class SuccessActivity extends Activity {

	private TextView mContactname;
	private TextView mContactnum;
	private ImageView mContactPho;
	private EditText etSearch;
	private TextView textSearch;
	private ListView lv;
	String[] items = {"xiaoming","xiaoli","xiaohei"};
	String[] numbers={"1234556676","2342352345","3243545666"};
	
	/**
	 * 更新listView显示内容
	 * @param listItem 更新后的arraylist
	 * @return具有新内容的适配器
	 * @author mingwell
	 */
	public SimpleAdapter refresh(ArrayList> listItem){
		
		SimpleAdapter mSimpleAdapter = new SimpleAdapter(this,listItem,//需要绑定的数据
                R.layout.success,//每一行的布局
                  //动态数组中的数据源的键对应到定义布局的View中
                new String[] {"contactpho","contactname", "contactnum"},   
                new int[] {R.id.contactpho,R.id.contactname,R.id.contactnum} );
		return mSimpleAdapter;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contacts);
		
		//打开或创建test.db数据库
		SQLiteDatabase db = openOrCreateDatabase("test.db", Context.MODE_PRIVATE, null);
		db.execSQL("DROP TABLE IF EXISTS person");  
		db.execSQL("CREATE TABLE person (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, number VARCHAR)");
		//两种不同的插入数据方式
		Person person = new Person();
		person.name="xiaohuang";
		person.number="11111111111";
		db.execSQL("INSERT INTO person VALUES(NULL,?,?)", new Object[]{person.name, person.number});
		//以键值对的方式进行插入
		person.name="xiaowang";
		person.number="222222222222";
		ContentValues cv = new ContentValues();
		cv.put("name", person.name);
		cv.put("number", person.number);
		db.insert("person", null, cv);
		
		//初始状态查询数据库所有数据,并显示在listView中
		lv = (ListView)findViewById(R.id.lv);
		final ArrayList> listItem = new ArrayList>();
		Cursor c = db.rawQuery("SELECT * FROM person", null);
		//第一种插入方式,将数据库中内容添加到listitem
		while(c.moveToNext()){
			int id = c.getInt(c.getColumnIndex("id"));
			String name = c.getString(c.getColumnIndex("name"));
			String number = c.getString(c.getColumnIndex("number"));
			HashMap map = new HashMap(); 
			map.put("contactpho", R.drawable.ic_launcher);
			map.put("contactname", name);
			map.put("contactnum", number);
			listItem.add(map);
		}
		c.close();	
		//第二种插入方式,将自定义的string[]添加到listItem中
		for(int i=0;i<3;i++){  
	           HashMap map = new HashMap();  
	           map.put("contactpho", R.drawable.ic_launcher);//加入图片
	           map.put("contactname", items[i]);  
	           map.put("contactnum", numbers[i]);  
	           listItem.add(map);  
	        } 
          
		//为listView添加监听器
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView arg0, View arg1, int arg2,
                    long arg3) {
                setTitle("你点击了第"+arg2+"行");//设置标题栏显示点击的行
                
            }
        });
        db.close();
        //定义适配器
        SimpleAdapter mSimpleAdapter = refresh(listItem);
        //为ListView绑定适配器
        lv.setAdapter(mSimpleAdapter);
        
        textSearch = (TextView)findViewById(R.id.tvsearch);
        etSearch = (EditText)findViewById(R.id.edtsearch);
        //添加搜索栏editText控件文本变化监听器
        etSearch.addTextChangedListener(new TextWatcher() {
    		private String temp;
    		@Override
    		public void onTextChanged(CharSequence s, int start, int before, int count) {
    			// TODO Auto-generated method stub    			
    		}
    		
    		@Override
    		public void beforeTextChanged(CharSequence s, int start, int count,
    				int after) {
    			// TODO Auto-generated method stub
    		}
    		
    		@Override
    		public void afterTextChanged(Editable s) {
    			// TODO Auto-generated method stub
    			temp = etSearch.getText().toString();
    			//清空listitem内容
    			listItem.clear();
    			SQLiteDatabase db_search = openOrCreateDatabase("test.db", Context.MODE_PRIVATE, null);
    			Cursor csearch = db_search.rawQuery("SELECT * FROM person WHERE name LIKE '%"+temp +"%'", null);
    			//ArrayList> listSearch = new ArrayList>();
    			while(csearch.moveToNext()){
    				System.out.println("1s");
    				String name = csearch.getString(csearch.getColumnIndex("name"));
    				String number = csearch.getString(csearch.getColumnIndex("number"));
    				HashMap map = new HashMap(); 
    				map.put("contactpho", R.drawable.ic_launcher);
    				map.put("contactname", name);
    				map.put("contactnum", number);
    				listItem.add(map);
    			}
    			//定义适配器
    			SimpleAdapter tsSimpleAdapter = refresh(listItem);
    			//重新绑定适配器
    			lv.setAdapter(tsSimpleAdapter);
    		}
    	});
        
	}
		
}

运行跳转到通讯录的运行结果如

Android开发--模拟通讯录包含模糊查询_第1张图片

代码中也列举了几种操作SQLite数据库的方式。

你可能感兴趣的:(android)