5

我从这里举了一个在 Android 中使用 SQLite 的例子:http ://www.cnblogs.com/pangblog/p/3327696.html

我在努力通过名字联系。如何更改 GetContact 函数以按名称搜索?

数据库处理器:

public class DatabaseHandler extends SQLiteOpenHelper {

    //Database Version 
    private static final int DATABASE_VERSION = 1;

    //Database Name
    private static final String DATABASE_NAME = "contactsManager";

    //Contacts table name 
    private static final String TABLE_CONTACTS = "contacts";

    //Contacts Table Columns names 
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_PH_NUM = "phone_number";

    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables : CREATE TABLE table_name (column_name column_type);
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
                + KEY_PH_NUM + " TEXT" + ")";       
        db.execSQL(CREATE_CONTACTS_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed 
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

        // Create tables again
        onCreate(db);
    }   


    //Adding new contact 
    void addContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, contact.getName()); // Contact Name
        values.put(KEY_PH_NUM, contact.getPhoneNumber()); // Contact Phone

        // Inserting Row
        db.insert(TABLE_CONTACTS, null, values);
        db.close(); // Closing database connection
    }

    // Getting single contact 
    Contact getContact(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
                KEY_NAME, KEY_PH_NUM }, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1), cursor.getString(2));

        return contact;
    }

    // Getting All Contacts
    public List<Contact> getAllContacts() {
        List<Contact> contactList = new ArrayList<Contact>();
        // Select All Query :SELECT * FROM tableName WHERE criteria
        String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Contact contact = new Contact();
                contact.setID(Integer.parseInt(cursor.getString(0)));
                contact.setName(cursor.getString(1));
                contact.setPhoneNumber(cursor.getString(2));
                // Adding contact to list
                contactList.add(contact);
            } while (cursor.moveToNext());
        }

        return contactList;
    }


}

接触:

public class Contact {

    int _id;
    String _name;
    String _phone_number;


    public Contact() {

    }


    public Contact(int id, String name, String phone_number) {
        this._id = id;
        this._name = name;
        this._phone_number = phone_number;
    }


    public Contact(String name, String phone_number) {
        this._name = name;
        this._phone_number = phone_number;
    }

    public int getID() {
        return this._id;
    }

    public void setID(int id) {
        this._id = id;
    }

    public String getName() {
        return this._name;
    }

    public void setName(String name) {
        this._name = name;
    }

    public String getPhoneNumber() {
        return this._phone_number;
    }

    public void setPhoneNumber(String phone_number) {
        this._phone_number = phone_number;
    }


}
4

4 回答 4

6

getContact 中数据库查询中的 where 子句当前id = ??id 参数。按名称搜索所需要做的是修改该部分。

// Getting single contact 
Contact getContact(String name) {
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
            KEY_NAME, KEY_PH_NUM }, KEY_NAME + "=?",
            new String[] { name }, null, null, null, null);
    //...

您还应该稍微更改“工作”代码,因为它并不安全。如果数据库中没有这样的名称,游标不能null(实际上)但可以/将失败。cursor.moveToFirst()如果失败,您将收到异常,cursor.getString(0)因为游标没有可从中获取数据的行。

放弃null检查,并检查光标是否可以移动到第一个位置(不为空)。一旦不再需要光标,您也应该关闭它。

Contact contact = null;
if (cursor.moveToFirst()) {
    contact = new Contact(Integer.parseInt(cursor.getString(0)),
            cursor.getString(1), cursor.getString(2));
}
cursor.close();
// can return null if no contact was found.
return contact;
于 2013-09-18T09:45:06.473 回答
2

http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#query(java.lang.String , java.lang.String[], java.lang.String, java.lang.String[ ], java.lang.String, java.lang.String, java.lang.String, java.lang.String)

使用文档。

制作

db.query(TABLE_CONTACTS, new String[] { KEY_ID,
                KEY_NAME, KEY_PH_NUM }, KEY_NAME+ "=?",
                new String[] { String.valueOf(NAME) }, null, null, null, null);

并在函数头部推送变量 NAME。

于 2013-09-18T09:46:02.950 回答
1

您可以在 SQLite 中通过以下代码进行搜索;

在主活动中;

 search.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
        }
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            adapter.getFilter().filter(s.toString());
        }
    });
    adapter.setFilterQueryProvider(new FilterQueryProvider() {
        public Cursor runQuery(CharSequence constraint) {
            return 
   //Here you can filter data by any row , just change text replace of "subject"
  dbManager.fetchdatabyfilter(constraint.toString(),"subject");
        }
    });

数据库助手.java

 public Cursor fetchdatabyfilter(String inputText,String filtercolumn) throws SQLException {
    Cursor row = null;
    String query = "SELECT * FROM "+DatabaseHelper.TABLE_NAME;
    if (inputText == null  ||  inputText.length () == 0)  {
        row = database.rawQuery(query, null);
    }else {
        query = "SELECT * FROM "+DatabaseHelper.TABLE_NAME+" WHERE "+filtercolumn+" like '%"+inputText+"%'";
        row = database.rawQuery(query, null);
    }
    if (row != null) {
        row.moveToFirst();
    }
    return row;
}
于 2017-07-28T10:54:57.867 回答
0

   EditText et = (EditText) findViewById(R.id.myFilter);
        et.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable s) {
            }
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                adapter.getFilter().filter(s.toString());
            }
        });

        adapter.setFilterQueryProvider(new FilterQueryProvider() {
            public Cursor runQuery(CharSequence constraint) {
                return db.fetchdatabyfilter(constraint.toString(),"name" );
            }
        });

于 2018-07-11T09:15:41.420 回答