Bea*_*ear 2 android android-contentprovider
我正在实现一个ContentProvider,当我实现查询方法时,我遇到了一些困难.
public final Cursor query (Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
Run Code Online (Sandbox Code Playgroud)
如何获取键值参数对?
假设用户传递的内容类似于"a =?和b =?" 2,"hello"作为selectionArgs,我想获得一个HashMap {a:2,b:"hello"}.
小智 5
这是一个程序,演示了您正在寻找的解决方案.仔细查看getHashmap()将选择字符串和选择参数作为参数的方法,并返回您要查找的内容的哈希映射.我以您的数据集为例.根据您的需求,它应该更接近您的解决方案.唯一需要注意的是,如果要在'='之外使用不同的逻辑比较,则需要修改正则表达式.如果它适合你,请告诉我
public static void main(String[] args) {
String sel = "a=? and b=?";
String[] ags = new String[] { "2", "hello" };
HashMap<String, String> result = getHashmap(sel, ags);
Iterator it = result.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
it.remove();
}
}
public static HashMap<String, String> getHashmap(String selection,
String[] selectionArgs) {
HashMap<String, String> result = new HashMap<String, String>();
Pattern pattern = Pattern.compile("[a-z]*(\\s)*=\\?",
Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(selection);
int pos = 0;
while (matcher.find()) {
String[] selParts = matcher.group(0).split("=");
result.put(selParts[0], selectionArgs[pos]);
pos++;
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
466 次 |
| 最近记录: |