如何从 sqlite 数据库搜索(地址簿示例)



我仍然是学习android的过程,我已经尝试了地址簿示例,该示例基本上允许用户使用sqlite存储联系人,并且效果很好。

现在我正在尝试添加允许用户搜索特定联系人的 sreachbar 功能。我尝试了很多教程,但我还想不通你能帮忙吗?如何添加搜索功能(可以通过工具栏或任何方法)

我的代码 :

主要活动处理片段和通信以及我希望执行搜索的位置:

// MainActivity.java
// Hosts the app's fragments and handles communication between them
public class MainActivity extends AppCompatActivity
implements ContactsFragment.ContactsFragmentListener,
DetailFragment.DetailFragmentListener,
AddEditFragment.AddEditFragmentListener {
   // key for storing a contact's Uri in a Bundle passed to a fragment
   public static final String CONTACT_URI = "contact_uri";
   private ContactsFragment contactsFragment; // displays contact list
   // display ContactsFragment when MainActivity first loads
   @Override
   protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
  setSupportActionBar(toolbar);
  // if layout contains fragmentContainer, the phone layout is in use;
  // create and display a ContactsFragment
  if (savedInstanceState == null &&
     findViewById(R.id.fragmentContainer) != null) {
     // create ContactsFragment

//Nuha animation
     // add the fragment to the FrameLayout
    ///Nuha try animation
     FragmentManager fragmentManager = getSupportFragmentManager();
     FragmentTransaction transaction = fragmentManager.beginTransaction();
     transaction.setCustomAnimations(R.anim.enter, R.anim.exit,     R.anim.pop_enter, R.anim.pop_exit);
    contactsFragment = new ContactsFragment();
   transaction.replace(R.id.fragmentContainer, contactsFragment);
     transaction.addToBackStack(null);
    transaction.commit();

  }
  else {
     contactsFragment =
        (ContactsFragment) getSupportFragmentManager().
           findFragmentById(R.id.contactsFragment);
  }
   }
   // display DetailFragment for selected contact
   @Override
   public void onContactSelected(Uri contactUri) {
  if (findViewById(R.id.fragmentContainer) != null) // phone
     displayContact(contactUri, R.id.fragmentContainer);
  else { // tablet
     // removes top of back stack
     getSupportFragmentManager().popBackStack();
     displayContact(contactUri, R.id.rightPaneContainer);
  }
   }
   // display AddEditFragment to add a new contact
   @Override
   public void onAddContact() {
  if (findViewById(R.id.fragmentContainer) != null) // phone
     displayAddEditFragment(R.id.fragmentContainer, null);
  else // tablet
     displayAddEditFragment(R.id.rightPaneContainer, null);
   }
   // display a contact
   private void displayContact(Uri contactUri, int viewID) {
  DetailFragment detailFragment = new DetailFragment();
  // specify contact's Uri as an argument to the DetailFragment
  Bundle arguments = new Bundle();
  arguments.putParcelable(CONTACT_URI, contactUri);
  detailFragment.setArguments(arguments);
  // use a FragmentTransaction to display the DetailFragment
  FragmentTransaction transaction =
     getSupportFragmentManager().beginTransaction();
  transaction.replace(viewID, detailFragment);
  transaction.addToBackStack(null);
  transaction.commit(); // causes DetailFragment to display
   }
   // display fragment for adding a new or editing an existing contact
   private void displayAddEditFragment(int viewID, Uri contactUri) {
  AddEditFragment addEditFragment = new AddEditFragment();
  // if editing existing contact, provide contactUri as an argument
  if (contactUri != null) {
     Bundle arguments = new Bundle();
     arguments.putParcelable(CONTACT_URI, contactUri);
     addEditFragment.setArguments(arguments);
  }
  // use a FragmentTransaction to display the AddEditFragment
  FragmentTransaction transaction =
     getSupportFragmentManager().beginTransaction();
  transaction.replace(viewID, addEditFragment);
  transaction.addToBackStack(null);
  transaction.commit(); // causes AddEditFragment to display
   }
   // return to contact list when displayed contact deleted
   @Override
   public void onContactDeleted() {
  // removes top of back stack
  getSupportFragmentManager().popBackStack();
  contactsFragment.updateContactList(); // refresh contacts
   }
   // display the AddEditFragment to edit an existing contact
   @Override
   public void onEditContact(Uri contactUri) {
  if (findViewById(R.id.fragmentContainer) != null) // phone
     displayAddEditFragment(R.id.fragmentContainer, contactUri);
  else // tablet
     displayAddEditFragment(R.id.rightPaneContainer, contactUri);
   }
   // update GUI after new contact or updated contact saved
   @Override
   public void onAddEditCompleted(Uri contactUri) {
  // removes top of back stack
  getSupportFragmentManager().popBackStack();
  contactsFragment.updateContactList(); // refresh contacts
  if (findViewById(R.id.fragmentContainer) == null) { // tablet
     // removes top of back stack
     getSupportFragmentManager().popBackStack();
     // on tablet, display contact that was just added or edited
     displayContact(contactUri, R.id.rightPaneContainer);
  }
   }
    //
 }

2-地址簿数据库定义数据库的助手

class AddressBookDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "AddressBook.db";
private static final int DATABASE_VERSION = 1;

 // constructor
  public AddressBookDatabaseHelper(Context context) {
  super(context, DATABASE_NAME, null, DATABASE_VERSION);
 }
 // creates the contacts table when the database is created
  @Override
   public void onCreate(SQLiteDatabase db) {
  // SQL for creating the contacts table
  final String CREATE_CONTACTS_TABLE =
          "CREATE TABLE " + Contact.TABLE_NAME + "(" +
                  Contact._ID + " integer primary key, " +
                  Contact.COLUMN_NAME + " TEXT, " +
                  Contact.COLUMN_PHONE + " TEXT, " +
                  Contact.COLUMN_EMAIL + " TEXT, " +
                  Contact.COLUMN_SPECIALTY + " TEXT, " +
                  Contact.COLUMN_CITY + " TEXT, " +
                  Contact.COLUMN_CHARGE + " TEXT, " +
                  Contact.COLUMN_NOTE + " TEXT);";
  db.execSQL(CREATE_CONTACTS_TABLE); // create the contacts table
 }
  // normally defines how to upgrade the database when the schema changes
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
                     int newVersion) {
}
}

3-数据库说明 描述此应用数据库的表名和列名以及内容提供程序所需的其他信息

 public class DatabaseDescription {
  // ContentProvider's name: typically the package name
    public static final String AUTHORITY =
  "com.deitel.addressbook.data";
  // base URI used to interact with the ContentProvider
  private static final Uri BASE_CONTENT_URI =
  Uri.parse("content://" + AUTHORITY);
  // nested class defines contents of the contacts table
  public static final class Contact implements BaseColumns {
  public static final String TABLE_NAME = "contacts";
  // Uri for the contacts table
  public static final Uri CONTENT_URI =
     BASE_CONTENT_URI.buildUpon().appendPath(TABLE_NAME).build();
  // column names for contacts table's columns
  public static final String COLUMN_NAME = "name";
  public static final String COLUMN_PHONE = "phone";
  public static final String COLUMN_EMAIL = "email";
  public static final String COLUMN_SPECIALTY = "specialty";
  public static final String COLUMN_CITY = "city";
  public static final String COLUMN_CHARGE = "charge";
  public static final String COLUMN_NOTE = "note";
  // creates a Uri for a specific contact
  public static Uri buildContactUri(long id) {
     return ContentUris.withAppendedId(CONTENT_URI, id);
  }
    }

4_addressBookContentProvider 用于操作应用数据库的内容提供程序子类

   public class AddressBookContentProvider extends ContentProvider {
  // used to access the database
  private AddressBookDatabaseHelper dbHelper;
  // UriMatcher helps ContentProvider determine operation to perform
    private static final UriMatcher uriMatcher =
  new UriMatcher(UriMatcher.NO_MATCH);
    // constants used with UriMatcher to determine operation to perform
    private static final int ONE_CONTACT = 1; // manipulate one contact
    private static final int CONTACTS = 2; // manipulate contacts table
    // static block to configure this ContentProvider's UriMatcher
    static {
    // Uri for Contact with the specified id (#)
    uriMatcher.addURI(DatabaseDescription.AUTHORITY,
     Contact.TABLE_NAME + "/#", ONE_CONTACT);
     // Uri for Contacts table
     uriMatcher.addURI(DatabaseDescription.AUTHORITY,
     Contact.TABLE_NAME, CONTACTS);
    }
    // called when the AddressBookContentProvider is created
    @Override
    public boolean onCreate() {
       // create the AddressBookDatabaseHelper
   dbHelper = new AddressBookDatabaseHelper(getContext());
   return true; // ContentProvider successfully created
   }
  // required method: Not used in this app, so we return null
   @Override
    public String getType(Uri uri) {
  return null;
  }
  // query the database
   @Override
   public Cursor query(Uri uri, String[] projection,
  String selection, String[] selectionArgs, String sortOrder) {
  // create SQLiteQueryBuilder for querying contacts table
  SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
  queryBuilder.setTables(Contact.TABLE_NAME);
  switch (uriMatcher.match(uri)) {
     case ONE_CONTACT: // contact with specified id will be selected
        queryBuilder.appendWhere(
           Contact._ID + "=" + uri.getLastPathSegment());
        break;
     case CONTACTS: // all contacts will be selected
        break;
     default:
        throw new UnsupportedOperationException(
           getContext().getString(R.string.invalid_query_uri) + uri);
       }
       // execute the query to select one or all contacts
       Cursor cursor = queryBuilder.query(dbHelper.getReadableDatabase(),
          projection, selection, selectionArgs, null, null, sortOrder);
       // configure to watch for content changes
       cursor.setNotificationUri(getContext().getContentResolver(), uri);
       return cursor;
    }
    // insert a new contact in the database
    @Override
    public Uri insert(Uri uri, ContentValues values) {
       Uri newContactUri = null;
       switch (uriMatcher.match(uri)) {
     case CONTACTS:
        // insert the new contact--success yields new contact's row id
        long rowId = dbHelper.getWritableDatabase().insert(
           Contact.TABLE_NAME, null, values);
        // if the contact was inserted, create an appropriate Uri;
        // otherwise, throw an exception
        if (rowId > 0) { // SQLite row IDs start at 1
           newContactUri = Contact.buildContactUri(rowId);
           // notify observers that the database changed
           getContext().getContentResolver().notifyChange(uri, null);
        }
        else
           throw new SQLException(
              getContext().getString(R.string.insert_failed) + uri);
        break;
       default:
        throw new UnsupportedOperationException(
           getContext().getString(R.string.invalid_insert_uri) + uri);
       }
       return newContactUri;
    }
    // update an existing contact in the database
    @Override
    public int update(Uri uri, ContentValues values,
     String selection, String[] selectionArgs) {
     int numberOfRowsUpdated; // 1 if update successful; 0 otherwise
     switch (uriMatcher.match(uri)) {
     case ONE_CONTACT:
        // get from the uri the id of contact to update
        String id = uri.getLastPathSegment();
        // update the contact
        numberOfRowsUpdated = dbHelper.getWritableDatabase().update(
           Contact.TABLE_NAME, values, Contact._ID + "=" + id,
           selectionArgs);
        break;
        default:
        throw new UnsupportedOperationException(
           getContext().getString(R.string.invalid_update_uri) + uri);
       }
       // if changes were made, notify observers that the database changed
       if (numberOfRowsUpdated != 0) {
        getContext().getContentResolver().notifyChange(uri, null);
       }
       return numberOfRowsUpdated;
    }
    // delete an existing contact from the database
    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
       int numberOfRowsDeleted;
       switch (uriMatcher.match(uri)) {
     case ONE_CONTACT:
        // get from the uri the id of contact to update
        String id = uri.getLastPathSegment();
        // delete the contact
        numberOfRowsDeleted = dbHelper.getWritableDatabase().delete(
           Contact.TABLE_NAME, Contact._ID + "=" + id, selectionArgs);
        break;
       default:
        throw new UnsupportedOperationException(
           getContext().getString(R.string.invalid_delete_uri) + uri);
       }
       // notify observers that the database changed
       if (numberOfRowsDeleted != 0) {
     getContext().getContentResolver().notifyChange(uri, null);
       }
       return numberOfRowsDeleted;
    }
   }..

您可以为搜索栏创建 EditText,然后只需进行 SQL 查询即可按姓名或任何您想要的内容搜索联系人。

Cursor cursor = db.rawquery("SELECT 'column1','column2','column x' 
                             FROM 'yourTable'
                             WHERE name LIKE 'searchedName' ")

并检索结果:

cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
       yourList.add(cursor.getString(0)); // 0 corresponds to column 1 in this case
       yourList_2.add(cursor.getString(1)); // 1 corresponds to column 2 in this case
       yourList_x.add(cursor.getString(1)); // x corresponds to column x
       cursor.moveToNext();
    }
cursor.close();

最新更新