且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

按名称的Andr​​oid的SQLite搜索

更新时间:2023-12-01 13:59:22

在哪里在getContact数据库查询子句是目前的id =?将被替换为id参数。你需要做的的名称搜索什么是修改部分。

  //获取单个联系人
联系getContact(字符串名称){
    SQLiteDatabase DB = this.getReadableDatabase();

    光标光标= db.query(TABLE_CONTACTS,新的String [] {KEY_ID,
            KEY_NAME,KEY_PH_NUM},KEY_NAME +=?,
            新的String [] {名},NULL,NULL,NULL,NULL);
    // ...
 

您也应该改变工作codeA位,因为它不是真正的安全。游标不能是(实践),但 cursor.moveToFirst()能/会失败,如果有没有这样的名称数据库中。如果失败,你会得到一个异常的 cursor.getString(0)因为游标没有行从中获取数据。

删除该检查,并做检查光标是否可以移动到第一位置(不为空)。你也应该关闭游标一旦你不需要它了。

 联系方式联系方式= NULL;
如果(cursor.moveToFirst()){
    触点=新的联系方式(的Integer.parseInt(cursor.getString(0)),
            cursor.getString(1),cursor.getString(2));
}
cursor.close();
如果没有接触,发现//可以返回null。
返回接触;
 

I took an example for working with SQLite in Android from here: http://www.cnblogs.com/pangblog/p/3327696.html

And I strugle with getting contact by name. How can I change GetContact function to search by name?

DatabaseHandler:

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;
    }


}

Contact:

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;
    }


}

The where clause in the database query in getContact is currently id = ? and the ? is replaced with the id parameter. What you need to do to search by the name is to modify that part.

// 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);
    //...

You should also change the "working" code a bit since it's not really safe. A cursor can't be null (in practice) but cursor.moveToFirst() can / will fail if there is no such name in the database. If it fails you will get an exception at cursor.getString(0) because the cursor has no row to get data from.

Drop the null check, and do check whether cursor could be moved to the first position (is not empty). You should also close the cursor once you don't need it anymore.

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;