標籤:android sqlitedate
2015年的Android案例之旅案例七:電子詞典知識點:
1.自動完成文字框(AutoCompleteTextView)
AutoCompleteTextView是從EditText派生出來的,當使用者輸入一定字元之後,AutoCompleteTextView會顯示一個下拉式功能表,供使用者選擇,當使用者選擇某個菜單之後,內容會被填充到該文本中。
使用AutoCompleteTextView需要設定一個Adapter,該Adapter封裝了預設的提示文本
2.SQLiteDataBase資料庫
3.Adapter適配器
涉及檔案:
res->layout->activity_main.xml 布局檔案
res->layout->word_list_item.xml 布局檔案
res->raw-> dictionary.db 詞典資料庫
res->values->strings 資源檔之字串資源
res->values->color 資源檔之顏色資源
res->AndroidManifest.xml 系統資訊清單檔主要添加SD卡相關許可權
src->package->MainActivity.java java檔案
activity_main.xml
<!-- 線性布局 --><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="#ff808080"> <!-- 相對布局 用於設定搜尋方塊和搜尋按鈕 --> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <!-- 定義自動完成文字框,供使用者輸入單詞 --> <AutoCompleteTextView android:id="@+id/word" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:ems="20" android:layout_toLeftOf="@+id/searchWord"/> <!-- 搜尋按鈕,供使用者點擊查詢單詞 --> <Button android:id="@+id/searchWord" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentRight="true" android:text="@string/search"/> </RelativeLayout> <!-- 查詢結果 --> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/result"/> <!-- 使用者顯示查詢的結果 --> <TextView android:id="@+id/show" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/white" android:textColor="@color/blue"/></LinearLayout>
word_list_item.xml
<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/tvWordItem" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_vertical" android:minHeight="?android:attr/listPreferredItemHeight" android:paddingLeft="6dip" android:textAppearance="?android:attr/textAppearanceLarge" android:textColor="@color/gray" />
MainActivity.java
package com.example.mydicitonary;import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;import android.app.Activity;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.os.Bundle;import android.support.v4.widget.CursorAdapter;import android.text.Editable;import android.text.TextWatcher;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.view.View.OnClickListener;import android.view.ViewGroup;import android.widget.AutoCompleteTextView;import android.widget.Button;import android.widget.TextView;public class MainActivity extends Activity {//定義Log標籤private static final String TAG = "DICITONARY";//聲明控制項對象private Button search;private TextView show;private AutoCompleteTextView actv;//用到SQLiteDateBase//定義資料庫的存放路徑private static final String DATEBASE_PATH = android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+ "/dictionary";//定義資料庫的名字private static final String DATEBASE_NAME = "dictionary.db";private SQLiteDatabase database;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Log.i(TAG, "DICITONARY is onCreate");//擷取布局中的控制項init();//開啟資料庫database = openDateBase();//監聽事件處理listener();}/** * @oaram 初始化控制項 */private void init(){search = (Button)this.findViewById(R.id.searchWord);show = (TextView)this.findViewById(R.id.show);actv = (AutoCompleteTextView)this.findViewById(R.id.word);}/** * @param 處理監聽事件 */private void listener(){//按鈕點擊事件search.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {String result = "未查到該單詞資訊";//查詢指定的單詞String sql = "select chinese from t_words where english=?";Cursor cursor = database.rawQuery(sql, new String[]{actv.getText().toString()});if(cursor.getCount()>0){// 必須使用moveToFirst方法將記錄指標移動到第1條記錄的位置cursor.moveToFirst();result = cursor.getString(cursor.getColumnIndex("chinese")).replace("&", "&");}//將結果顯示到TextView中show.setText(actv.getText().toString() +"\n"+result);}});//文本變動事件actv.addTextChangedListener(new TextWatcher() {@Overridepublic void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {// TODO Auto-generated method stub}@Overridepublic void beforeTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) {// TODO Auto-generated method stub}@Overridepublic void afterTextChanged(Editable s) {Cursor cursor = database.rawQuery("select english as _id from t_words where english like ?",new String[]{ s.toString() + "%" });//建立新的AdapterDictionaryAdapter dictionaryAdapter = new DictionaryAdapter(MainActivity.this,cursor, true);//綁定適配器actv.setAdapter(dictionaryAdapter);}});}//自訂Adapter類public class DictionaryAdapter extends CursorAdapter{//對於一個沒有被載入或者想要動態載入的介面,都需要使用LayoutInflater.inflate()來載入;//對於一個已經載入的介面,就可以使用Activiyt.findViewById()方法來獲得其中的介面元素。private LayoutInflater layoutInflater;public DictionaryAdapter(Context context, Cursor c, boolean autoRequery){super(context, c, autoRequery);layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);}@Overridepublic CharSequence convertToString(Cursor cursor){return cursor == null ? "" : cursor.getString(cursor.getColumnIndex("_id"));}//將單詞資訊顯示到列表中private void setView(View view, Cursor cursor){TextView tvWordItem = (TextView) view;tvWordItem.setText(cursor.getString(cursor.getColumnIndex("_id")));}//綁定選項到列表中@Overridepublic void bindView(View view, Context context, Cursor cursor) {setView(view, cursor);}@Overridepublic View newView(Context context, Cursor cursor, ViewGroup arg2) {View view = layoutInflater.inflate(R.layout.word_list_item, null);setView(view, cursor);return view;}}/** * @param返回一個SQLiteDatabase對象 * @return */private SQLiteDatabase openDateBase(){try {// 獲得dictionary.db檔案的絕對路徑String databaseFileName = DATEBASE_PATH + "/" + DATEBASE_NAME;File dir = new File(DATEBASE_PATH);// 如果/sdcard/dictionary目錄存在,建立這個目錄if (!dir.exists())dir.mkdir();// 如果在/sdcard/dictionary目錄中不存在// dictionary.db檔案,則從res\raw目錄中複製這個檔案到// SD卡的目錄(/sdcard/dictionary)if(!(new File(databaseFileName)).exists()){// 獲得封裝dictionary.db檔案的InputStream對象InputStream is = getResources().openRawResource(R.raw.dictionary);FileOutputStream fos = new FileOutputStream(databaseFileName);byte[] buffer = new byte[9128];int count = 0;// 開始複製dictionary.db檔案while((count = is.read(buffer))!=-1){fos.write(buffer, 0, count);}//關閉檔案流is.close();fos.close();}// 開啟/sdcard/dictionary目錄中的dictionary.db檔案SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(databaseFileName, null);return database;} catch (Exception e) {// TODO: handle exception}return null;}}
我的Android案例—電子詞典