If we use Kotlin, this is shorter. An example of a class that is responsible for providing call logs:
import android.content.Context import android.database.Cursor import android.provider.CallLog.Calls.* class CallsLoader { fun getCallLogs(context: Context): List<List<String?>> { val c = context.applicationContext val projection = arrayOf(CACHED_NAME, NUMBER, TYPE, DATE, DURATION) val cursor = c.contentResolver.query( CONTENT_URI, projection, null, null, null, null ) return cursorToMatrix(cursor) } private fun cursorToMatrix(cursor: Cursor?): List<List<String?>> { val matrix = mutableListOf<List<String?>>() cursor?.use { while (it.moveToNext()) { val list = listOf( it.getStringFromColumn(CACHED_NAME), it.getStringFromColumn(NUMBER), it.getStringFromColumn(TYPE), it.getStringFromColumn(DATE), it.getStringFromColumn(DURATION) ) matrix.add(list.toList()) } } return matrix } private fun Cursor.getStringFromColumn(columnName: String) = getString(getColumnIndex(columnName)) }
We can also convert the cursor to a map:
fun getCallLogs(context: Context): Map<String, Array<String?>> { val c = context.applicationContext val projection = arrayOf(CACHED_NAME, NUMBER, TYPE, DATE, DURATION) val cursor = c.contentResolver.query( CONTENT_URI, projection, null, null, null, null ) return cursorToMap(cursor) } private fun cursorToMap(cursor: Cursor?): Map<String, Array<String?>> { val arraySize = cursor?.count ?: 0 val map = mapOf( CACHED_NAME to Array<String?>(arraySize) { "" }, NUMBER to Array<String?>(arraySize) { "" }, TYPE to Array<String?>(arraySize) { "" }, DATE to Array<String?>(arraySize) { "" }, DURATION to Array<String?>(arraySize) { "" } ) cursor?.use { for (i in 0 until arraySize) { it.moveToNext() map[CACHED_NAME]?.set(i, it.getStringFromColumn(CACHED_NAME)) map[NUMBER]?.set(i, it.getStringFromColumn(NUMBER)) map[TYPE]?.set(i, it.getStringFromColumn(TYPE)) map[DATE]?.set(i, it.getStringFromColumn(DATE)) map[DURATION]?.set(i, it.getStringFromColumn(DURATION)) } } return map }
Artem Botnev Jul 02 '19 at 8:09 2019-07-02 08:09
source share