How to filter the results of content resolver in android?

前端 未结 4 1445
再見小時候
再見小時候 2020-12-07 20:37

I would like to get user contacts and then append some kind of regular expression and append them to a list view. I am currently able to get all the contacts via

4条回答
  •  余生分开走
    2020-12-07 21:37

    Instead of

    getContentResolver().query(People.CONTENT_URI, null, null, null, null); 
    

    you should use something like

    final ContentResolver resolver = getContentResolver();
    final String[] projection = { People._ID, People.NAME, People.NUMBER };
    final String sa1 = "%A%"; // contains an "A"
    cursor = resolver.query(People.CONTENT_URI, projection, People.NAME + " LIKE ?",
       new String[] { sa1 }, null);
    

    this uses a parameterized request (using ?) and provides the actual values as a different argument, this avoids concatenation and prevents SQL injection mainly if you are requesting the filter from the user. For example if you are using

    cursor = resolver.query(People.CONTENT_URI, projection,
       People.NAME + " = '" + name + "'",
       new String[] { sa1 }, null);
    

    imagine if

    name =  "Donald Duck' OR name = 'Mickey Mouse") // notice the " and '
    

    and you are concatenating the strings.

提交回复
热议问题