Advertisement
Guest User

Content Providers

a guest
Oct 25th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 2.00 KB | None | 0 0
  1. package com.example.content_providers
  2.  
  3. import android.database.Cursor
  4. import android.net.Uri
  5. import android.os.Bundle
  6. import android.provider.ContactsContract
  7. import android.util.Log
  8. import android.widget.SimpleCursorAdapter
  9. import androidx.appcompat.app.AppCompatActivity
  10. import kotlinx.android.synthetic.main.activity_main.*
  11.  
  12.  
  13. class MainActivity : AppCompatActivity() {
  14.     val TAG = "MainActivity"
  15.  
  16.     val uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI
  17.     val SELECTED_COLUMNS = arrayOf(
  18.         ContactsContract.CommonDataKinds.Phone._ID,       // needed by simplecursoradapter
  19.         ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
  20.         ContactsContract.CommonDataKinds.Phone.NUMBER
  21.     )
  22.  
  23.  
  24.     override fun onCreate(savedInstanceState: Bundle?) {
  25.         super.onCreate(savedInstanceState)
  26.         setContentView(R.layout.activity_main)
  27.  
  28.         doContentProvidersWithAdapter()
  29.     }
  30.  
  31.     fun doContentProvidersWithAdapter() {
  32.  
  33.         val cursor: Cursor? = contentResolver.query(uri, SELECTED_COLUMNS, null, null, null)
  34.         if (cursor != null) {
  35.  
  36.             // link the SELECTED_COLUMNS to some view IDs. S
  37.             val toViews = intArrayOf(
  38.                 -1, // since we don't want to display Phone_ID, we are assigning -1 to it, which doesn't match to any real View in our layout
  39.                 R.id.name_textview,
  40.                 R.id.number_textview)
  41.  
  42.             val cursorAdapter = SimpleCursorAdapter(
  43.                 this,               // context
  44.                 R.layout.list_row,  // layout that defines the views for this list item
  45.                 cursor,             // the database cursor
  46.                 SELECTED_COLUMNS,   // "From" - column names of the data to bind to the UI
  47.                 toViews,            // TextViews that should display column in the "from" param
  48.                 0)                  // flags used to determine the behaviour of the adapter
  49.  
  50.             main_listview.setAdapter(cursorAdapter)
  51.  
  52.  
  53.         }
  54.     }
  55.  
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement