1. 程式人生 > >Android開發--模擬通訊錄包含模糊查詢

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<HashMap<String, Object>> 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<HashMap<String, Object>> listItem = new ArrayList<HashMap<String,Object>>();
		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<String, Object> map = new HashMap<String, Object>(); 
			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<String, Object> map = new HashMap<String, Object>();  
	           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<HashMap<String, Object>> listSearch = new ArrayList<HashMap<String,Object>>();
    			while(csearch.moveToNext()){
    				System.out.println("1s");
    				String name = csearch.getString(csearch.getColumnIndex("name"));
    				String number = csearch.getString(csearch.getColumnIndex("number"));
    				HashMap<String, Object> map = new HashMap<String, Object>(); 
    				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);
    		}
    	});
        
	}
		
}

執行跳轉到通訊錄的執行結果如

程式碼中也列舉了幾種操作SQLite資料庫的方式。