Convert a Content Provider Cursor to JSON

This is a short article where we will read the data from the content provider and convert it to JSON. So, Let's query the SMS table and get a reference to the cursor.

// Query the sms table
val cursor = context?.contentResolver?.query(
    Telephony.Sms.Inbox.CONTENT_URI, null,
    null, null, null

With the cursor in hand, loop through it to read the rows and columns.

cursor?.use {
    // Total number of columns in the table
    Log.v(TAG, "Column Count: ${it.columnCount}")
    // Total number of rows in the table
    Log.v(TAG, "Row Count: ${it.count}")
    // Move to the first item
    // Temporary json variable that contains all the rows and their values
    val rowJson = JSONArray()
    // Loop through the rows
    do {
        // Temporary json variable that contains all the columns and their vales
        val columnJson = JSONObject()
        // Loop through the columns
        it.columnNames.forEachIndexed { i, columnName ->
            // Add the column name and its value to the column array
            columnJson.put(columnName, it.getString(i))
        Log.v(TAG, "Json Row: $columnJson")
        // Add the column data to the corresponding row
    } while (it.moveToNext())
    // Return the json string
}.apply {
    // Print the entire sms data to the Logcat
    Log.v(TAG, this)

Below is a sample row of the SMS table in the JSON format. The columns will differ for different devices and the OS versions.

   "body":"Hi Srikar Reddy, not only rides, now order food also on Ola! Fire up the app and get delicious food delivered straight to your desk. https:\/\/\/2QaptoK",

Popular posts from this blog

Add Spacing to Recycler View Linear Layout Manager Using Item Decoration

How to Set an Android App as a Default Dialer

How to Change Material Chip Text Size, Text Style and Font

How to Read Metadata from AndriodManifest File

Create Assets Folder, Add Files and Read Data From It