【问题标题】:Performing 'like' queries in Android Content Provider在 Android 内容提供程序中执行“喜欢”查询
【发布时间】:2015-10-22 16:46:29
【问题描述】:

我正在 Android 上实现内容提供程序。我希望我的查询不仅仅是完全匹配——有没有办法在内容提供者查询方法中指定“喜欢”查询?

当前代码。请注意mSearchString 是用户提供的字符串——我目前正在使用它来查询UserDictionary,它返回任何内容的唯一方法是mSearchString 是否与UserDictionary 中的单词完全匹配。我希望能够匹配部分查询(例如,如果苹果、阿姨和实用在字典中,我想搜索“a”并将它们全部返回)。

        mSelectionClause = UserDictionary.Words.WORD + " = ?";

        // Moves the user's input string to the selection arguments.
        // Remember to add code here to check for invalid or malicious input.
        mSelectionArgs[0] = mSearchString;

    // Does a query against the table and returns a Cursor object
            Cursor mCursor = getContentResolver().query(
                    UserDictionary.Words.CONTENT_URI,  // The content URI of the words table
                    mProjection,                       // The columns to return for each row
                    mSelectionClause,                   // Either null, or the word the user entered
                    mSelectionArgs,                    // Either empty, or the string the user entered
                    mSortOrder);    

【问题讨论】:

  • “我正在 Android 上实现内容提供程序”——您的代码看起来更像是在尝试使用由其他人编写的 ContentProvider。您是否尝试真正实现您的自己的ContentProvider
  • 根据this answer,至少对于UserDictionarylike ?应该确实有效。
  • 汉诺之类的?结合使用 %..% 包装用户的输入。还要向 CommonsWare 大声喊叫,让我用精确的措辞保持诚实。

标签: java android


【解决方案1】:

我正在使用SQLiteDatabase(不使用getContentResolver(),我不知道它是什么),但我可以使用此代码搜索给定模式(名为pattern)的单词like,所以因为语法看起来一样,我想它可以为你工作:

    String whereClause = "word like ?";
    String[] wildCardReplacements = {pattern};
    cursor = database.query(TABLE_NAME, mColumns, whereClause,  
             wildCardReplacements, null, null, null);

所以如果pattern 包含%a%,我会得到“苹果,阿姨,和,实用”等等。

如果不是很明显,在您的情况下,mSearchString = "%" + mSearchString + "%" 之类的内容将允许用户仅输入 a(例如)并获得所需的匹配项。

附: database 被定义为android.database.sqlite.SQLiteDatabase

【讨论】:

  • 真棒 DSlomer64,谢谢 - 你的回答完全正确。
  • 很高兴我能帮上忙。=
【解决方案2】:

100% 工作代码,更改为您的代码(光标)这样,

Cursor contactsContractContacts = resolver.query(
ContactsContract.Contacts.CONTENT_URI, projection,
ContactsContract.Contacts.DISPLAY_NAME + " like ?",
new String[]{"%" + filterStr + "%"},
ContactsContract.Contacts.DISPLAY_NAME + " ASC");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-30
    • 2016-10-20
    相关资源
    最近更新 更多