Search code examples
androidsqlandroid-contentresolver

Android/sqlite - ContentResolver query with user input


Currently, I'm using this method to query all photos user's phone has:

public void setCursor(){
    String selection;
    String[] selectionArgs;

    selection = MediaStore.Images.Media.DATA + " LIKE ?";
    selectionArgs = new String[]{"%"+getSelectionArg()+"%"};

    cursor = context.getContentResolver().query(
            EXTERNAL_CONTENT_URI,
            MainActivity.projection,
            selection,
            selectionArgs,
            MediaStore.Images.Media.DATE_ADDED
    );
    cursor.moveToPosition(getI());
}

I wanted to allow the user to filter the query by file names, so I added selection & selectionArgs part. (getSelectionArgs() returns "" if there is no user input. It returns the input if there is.)

This method has problems when user enters "s" or "d" or "%". How can I sanitize this input so that doesn't happen? I'm not experienced with SQL and I genuinely need help, so please be kind.


Solution

  • Welp, nevermind. My code was correct, and s and d showing all pictures wasn't a bug like I thought it was. It was catching (s)torage/emulate(d)/0...