Content Provider in Android for beginners

1_aORbk8zIhcmTgb1Tyt8Vfw.png

Content Providers is one of the android application important component that serves the purpose of a relational database to store the data of applications. Content provider in the android system is like a “central repository” in which data of the applications are stored, and it facilitates other applications to securely access and modifies that data based on the requirements.

What is Content Provider?

Content Providers is one of the android application important component that serves the purpose of a relational database to store the data of applications. Content provider in the android system is like a “central repository” in which data of the applications are stored, and it facilitates other applications to securely access and modifies that data based on the requirements. Content Providers support the four basic operations, normally called CRUD-operations.

What is Content URI(Universal Resource Identifier)?

Content URI is the key concept of content provider. To query a content provider, you can specify the query string in the form of URI.

URI: content://authority/data_type/id

  • content:// -->This is prefix of all the URI and it is mandatory part of URI.
  • authority -->This part should be always unique for every content provider, it specify the name of content provider. for example contacts, browser etc.
  • data_type --> This indicates the type of data provider by content provider.
  • id --> it is a numeric value that is used to access particular record.

Operations of Content Provider are CRUD

  • CREATE
  • READ
  • UPDATE
  • DELETE

How does Content Provider works?

Android applications UI components like Activities/Fragments use an object CursorLoader to send query requests to ContentResolver. The ContentResolver object sends requests like “create, read, update, and delete” to the ContentProvider as a client. After receiving a request, ContentProvider process it and returns the expected result.

Imlementation of Contnent Provider for fetching contact list

UI components of android applications like Activity and Fragments use an object CursorLoader to send query requests to ContentResolver. The ContentResolver object sends requests (like create, read, update, and delete) to the ContentProvider as a client. After receiving a request, ContentProvider process it and returns the desired result

                class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.buttonLoadContacts.setOnClickListener {
            loadContacts()
        }
    }

    private fun loadContacts() {
        var builder: StringBuilder
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
            &&
            checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED
        ) {
            requestPermissions(
                arrayOf(Manifest.permission.READ_CONTACTS),
                PERMISSION_REQ_READ_CONTACTS
            )
        } else {
            builder = getContacts()
            binding.listOfContacts.text = builder.toString()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == PERMISSION_REQ_READ_CONTACTS) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                loadContacts()
            } else {
                Toast.makeText(this, "no permission granted!!", Toast.LENGTH_SHORT).show()
            }
        }
    }

    @SuppressLint("Range")
    private fun getContacts(): StringBuilder {
        var builder = StringBuilder()
        val resolver: ContentResolver = contentResolver
        var cursor =
            resolver.query(
                ContactsContract.Contacts.CONTENT_URI, null, null,
                null, null
            )

        if (cursor!!.count > 0) {
            while (cursor.moveToNext()) {
                val id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID))
                val names =
                    cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME))
                val phoneNumber =
                    cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))
                        .toInt()

                if (phoneNumber > 0) {
                    val cursorPhone = contentResolver.query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " =?",
                        arrayOf(id),
                        null
                    )

                    if (cursorPhone!!.count > 0) {
                        while (cursorPhone.moveToNext()) {
                            val phoneNumValue =
                                cursorPhone.getString(
                                    cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
                                )
                            builder.append("Contact : $names")
                                .append("Phone Number is : $phoneNumValue").append("\n\n")
                            Log.i("tag", "Name $names")
                        }
                    }
                    cursorPhone.close()
                }
            }
        }
        return builder
    }

    companion object {
        const val PERMISSION_REQ_READ_CONTACTS = 100
    }
}
            

Conclusion:

you have learned all about the two types of URIs for content providers and basic concepts of using it with an example.

Thanks for reading this article. Be sure to click 👏 below to applause this article if you found it helpful. It means a lot to me.


Only registered users can post comments. Please, login or signup.

Start blogging about your favorite technologies and get more readers

Join other developers and claim your FAUN account now!

Avatar

ABHISHEK KUMAR PATHAK

Project Lead, Wipro

@myofficework000
I’m an Android Lead, passionate about building great apps. For me app development is not just about coding, it’s also about creating an awesome user experience.
Stats
15

Influence

301

Total Hits

1

Posts