Query Contacts table programatically using UiAutomator executeShellCommand

by acrespo   Last Updated May 15, 2019 18:11 PM

I'm trying to automate some actions involving the contacts table, using UiAutomator. But I'm having this weird problem related to shell escape characters.

I know that I can do this from the command line:

adb shell content query --uri content://com.android.contacts/raw_contacts --projection _id --where "account_name=\’SOME_ACCOUNT_NAME\’"

which will correctly output (There is one contact with account_name=SOME_ACCOUNT_NAME)

Row: 0 _id=1

but when I try to do this via code like this:

fun test_01_a_user_can_setup_P2P_mode() {
    val uiAutomation = InstrumentationRegistry.getInstrumentation().uiAutomation
    uiAutomation.executeShellCommand("content query --uri content://com.android.contacts/raw_contacts --projection _id --where \"account_name=\'SOME_ACCOUNT_NAME\'\"")

    val baos = ByteArrayOutputStream()
    writeDataToByteStream(fd!!, baos)

    val output = String(baos.toByteArray())
    Log.println(Log.DEBUG, "TAG", output)

private val BUFFER_SIZE = 8192

private fun writeDataToByteStream(
        pfDescriptor: ParcelFileDescriptor, outputStream: ByteArrayOutputStream) {
    val inputStream = ParcelFileDescriptor.AutoCloseInputStream(pfDescriptor)
    try {
        val buffer = ByteArray(BUFFER_SIZE)
        var len = inputStream.read(buffer)
        while (len >= 0) {
            outputStream.write(buffer, 0, len)
            len = inputStream.read(buffer)
    } finally {

prints No result found.

However, removing the --where \"account_name=\'SOME_ACCOUNT_NAME\'\" part, correclty prints

Row: 0 _id=1

I tried many different ways of escaping " and ' but I'm lost between Java String escape characters and shell escape characters.

Related Questions

Updated May 15, 2019 19:11 PM

Updated January 30, 2019 01:11 AM

Updated August 13, 2017 12:11 PM

Updated July 12, 2017 11:11 AM

Updated May 05, 2016 08:04 AM