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
    it.moveToFirst()
    // 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
        rowJson.put(columnJson)
    } while (it.moveToNext())
    // Return the json string
    rowJson.toString()
}.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.

{  
   "_id":"792",
   "thread_id":"286",
   "address":"IX-OLACBS",
   "person":"0",
   "date":"1545299882278",
   "date_sent":"1545299882000",
   "protocol":"0",
   "read":"0",
   "status":"-1",
   "type":"1",
   "reply_path_present":"0",
   "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:\/\/bit.ly\/2QaptoK",
   "service_center":"+919844047238",
   "locked":"0",
   "sub_id":"0",
   "network_type":"13",
   "error_code":"0",
   "creator":"com.android.mms",
   "seen":"1",
   "mtype":"0",
   "privacy_mode":"0",
   "group_id":"2592",
   "addr_body":"0,",
   "time_body":"0,",
   "risk_url_body":"",
   "is_secret":"0"
}

Popular posts from this blog

How to Read Metadata from AndriodManifest File

Add Spacing to Recycler View Linear Layout Manager Using Item Decoration

Add Options Menu to Activity and Fragment

Create Assets Folder, Add Files and Read Data From It

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