0

我创建了一个 TabLayout,我想通过所选选项卡显示我的数据库条目。这是带有查询的代码片段:

public Cursor filteredItems(int tabPosition) throws SQLException {
        Log.d(TAG, "filteredItems called, Parameter: "+tabPosition); 

        String filter = ""; 
        if(tabPosition == 0){
            filter = "[a-cA-C]%";
        }else if(tabPosition == 1){
            filter = "[d-fD-F]%";
        }else{
            Log.d(TAG, "default tab"); 
            filter = "[a-zA-Z]%";
        }

        Cursor cursor = null;
        try{
            open();
            String query ="SELECT _id, surname, prename, street, zipcode, telephone, email FROM "+Database.getMyDbTable()+" " +
                    "WHERE surname LIKE '"+filter+"';";
            Log.d(TAG,"Query "+query);
            cursor = database.rawQuery(query, null);
        }catch(Exception ex){
            Log.e(TAG, "Could not get list");
            CharSequence text = dataNotFound;
            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
        }

        return cursor;
    }

不幸的是,过滤器不起作用——查询的结果总是空的(表不为空——我已经检查过了)。

4

4 回答 4

1

首先,LIKE 运算符不采用正则表达式。不幸的是,执行此操作的 REGEXP 运算符在 Android 中不受支持。

解决方案:将 LIKE 与逻辑 OR 一起使用。

String query ="SELECT _id, surname, prename, street, zipcode, telephone, email FROM "+Database.getMyDbTable()+" WHERE surname LIKE 'a%' OR surname LIKE 'b%' OR surname LIKE 'c%';";
于 2013-02-05T10:45:57.053 回答
1

为此,您需要使用通配符。阅读http://sqlite.awardspace.info/syntax/sqlitepg03.htm

尝试

SELECT _id, surname, prename, street, zipcode, telephone, email FROM table WHERE surname LIKE '<your letter(s)>%'
于 2013-02-05T10:38:07.457 回答
0

尝试类似:

"SELECT _id, surname, prename, street, zipcode, telephone, email FROM " + Database.getMyDbTable() + " WHERE substr(" + Database.getMyDbTable()  +",1) LIKE " + <yourletter>

通过使用substr,您只比较第一个字母。

于 2013-02-05T10:44:35.977 回答
0

LIKE不能与字符集匹配。

由于您只关心第一个字母,因此您可以使用BETWEEN

SELECT ... FROM MyTable WHERE surname BETWEEN 'A' AND 'Czzzz'

要同时处理大写和小写,请使用两个条件,或更改排序规则:

SELECT ... FROM MyTable WHERE surname BETWEEN 'A' AND 'Czzzz'
                           OR surname BETWEEN 'a' AND 'czzzz'

SELECT ... FROM MyTable WHERE surname COLLATION UNICODE BETWEEN 'A' AND 'Czzzz'

仅当列或索引已使用相同的排序规则声明时,后者才能使用索引。

于 2013-02-05T13:19:49.767 回答