我正在实现一个 ContentProvider,当我实现查询方法时,我遇到了一些困难。
public final Cursor query (Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
如何获取键值对参数?
假设用户传递类似“a=? and b=?”的内容和 2,"hello"作为 selectionArgs,我想获得一个 HashMap {a:2,b:"hello"}。
最佳答案
这是一个程序,它演示了您正在寻找的解决方案。仔细查看 getHashmap()
方法,该方法将选择字符串和选择参数作为参数,并返回您要查找的内容的 HashMap 。我以您的数据集为例。根据您正在寻找的内容,它应该更接近您的解决方案。唯一需要注意的是,如果您要使用除“=”之外的不同逻辑比较,则需要修改正则表达式。让我知道它是否适合您
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;
}
关于android - ContentProvider 实现,如何将 "Selection"和 "SelectionArgs"转换为键值对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12949730/