歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android開發:自動補全與SQLite聯合的例子

Android開發:自動補全與SQLite聯合的例子

日期:2017/3/1 10:40:08   编辑:Linux編程

從上一個例子(Android自動補全教程 http://www.linuxidc.com/Linux/2012-01/51326.htm )可以看到自動補全是很簡單的,今天再深入一點,ArrayAdapter提供的字符串從數據庫中查詢,並且使用MultiAutoCompleteTextView控件。

此控件和AutoCompleteTextView的最大區別是可以補全多個詞,看名字就能知道,呵呵。

效果如下,每個詞中間用逗號分割。


首先

布局和上一個例子相同。

創建一個名為list_item.xml的XML文件並把它保存在res/layout/文件夾下。編輯文件像下面這樣:

[html]
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <TextView xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:padding="10dp"
  6. android:textSize="16sp"
  7. android:textColor="#000">
  8. </TextView>

這個文件定義了一個簡單的TextView來顯示提示列表的每一項。

打開 res/layout/main.xml文件加入如下內容:

[html]
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="vertical" >
  6. <TextView
  7. android:id="@+id/tv"
  8. android:layout_width="fill_parent"
  9. android:layout_height="wrap_content"
  10. android:text="@string/hello" />
  11. <MultiAutoCompleteTextView
  12. android:id="@+id/mactv"
  13. android:layout_width="fill_parent"
  14. android:layout_height="wrap_content"
  15. />
  16. </LinearLayout>

下面就來設計我的數據庫,名字為person,要建一個person表,有兩個字段:name和gender。

新建一個SQLiteHelper類,繼承自SQLiteOpenHelper:

[java]
  1. package com.linc.autosqlite.dao;
  2. import android.content.Context;
  3. import android.database.Cursor;
  4. import android.database.sqlite.SQLiteDatabase;
  5. import android.database.sqlite.SQLiteOpenHelper;
  6. /**
  7. * 實現對表的創建、更新、變更列名操作
  8. * @author lincyang
  9. *
  10. */
  11. public class SQLiteHelper extends SQLiteOpenHelper {
  12. public static final String DB_NAME = "person";
  13. public static final int DB_VERSION = 1;
  14. protected static Context ctx;
  15. //
  16. //構造函數一:傳context
  17. //
  18. public SQLiteHelper(Context context) {
  19. super(context, DB_NAME, null, DB_VERSION);
  20. ctx = context;
  21. }
  22. //
  23. //構造函數二
  24. //
  25. public SQLiteHelper() {
  26. super(ctx,DB_NAME, null, DB_VERSION);
  27. }
  28. @Override
  29. public void onCreate(SQLiteDatabase db) {
  30. String sql = "create table person(name varchar(20) not null , " +
  31. "gender varchar(10) not null );";
  32. db.execSQL(sql);
  33. }
  34. @Override
  35. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  36. // TODO Auto-generated method stub
  37. }
  38. protected void closeCursor(Cursor cursor) {
  39. if (cursor != null) {
  40. cursor.close();
  41. }
  42. }
  43. }
Copyright © Linux教程網 All Rights Reserved