Search code examples
androidkotlincursorsmsandroid-contentresolver

Reading Texts Kotlin - Android SDK 29


I'm relatively new to Android Dev and I'm running Android Studio on SDK 29 for a project to read through messages, find Roster text messages for where I work and then import them into the Google Calander via API. I've had a small amount of experience with Android before so the text and onClick etc are fine (Although I used java in the past, trying kotlin as it's the future). However I'm trying to play around with reading the body of all messages and just printing them to the screen so I can understand how it works, tweak things here and there and see the results I get. However just getting the body of messages and printing them is turning out to be quite difficult.

I had issues initially however they were to do with permissions not working correctly. From there I fixed that issue and got some working code with no errors however instead of getting an output of the body of the messages I got a random '12'. So after further researching and googling I've managed to get myself to what I think is a close lot of code however, it's just incomplete and I'm unable to see what errors there may be as I haven't found a working lot of code online yet.

Furthermore the android dev documentation hasn't been a huge help. So I'm reaching out. Sorry if this seems a easy fix however it's new to me and I havent' found anything online after a fair bit of searching.

Thanks in advance

This is my code so far:


        var cr = contentResolver.query(
            Uri.parse("content://sms/inbox"),
            null,
            null,
            null,
            null
        )

        if(cr.moveToFirst()){
            do {
                var msgData = ""
                for(messages in cr.getColumnIndex("body")) {
                    lastSyncMessage.text =
                        lastSyncMessage.text.toString() + " " + msgData.toString()
                }
            }while(cr.moveToNext())
        }
    }```

Solution

  • Try the next code, the for loop is not correct:

    if(cr!= null && cr.moveToFirst()){
                do {
                     lastSyncMessage.text =cr.getString(cr.getColumnIndex("body"))
                }while(cr.moveToNext())
            }
    

    This code will set the last sms body message as the lastSyncMessage text. Just play with this.