Android Kotlin - Useful functions

 When I wrote my first app Maths Challenger using Kotlin I decided to create a small library of useful functions that can be re-used. This blog is a compilation of such functions.


  • Function to raise a toast message with a default duration LENGTH_SHORT

    fun Activity.toast(message: String, duration: Int = Toast.LENGTH_SHORT) {
    Toast.makeText(this, message, duration)
    .show()
    }

  • Function to check if the file fname exists and return a boolean. Optionally delete the file if delete = "Yes"

    fun fileExist(fname: String?, delete: String = "No"): Boolean {
    val file = baseContext.getFileStreamPath(fname)

    if (delete == "Yes") {
    val deleted = file.delete()
    }
    return file.exists()
    }

  • Function to write String data to fileName

    fun writeToFile(fileName: String, data: String) {
        var fileOutputStream: FileOutputStream
    try {
    fileOutputStream = openFileOutput(fileName, Context.MODE_PRIVATE)
    fileOutputStream.write(data.toByteArray())
    fileOutputStream.close()
    } catch (e: FileNotFoundException) {
    e.printStackTrace()
    } catch (e: Exception) {
    e.printStackTrace()
    }
    }

  • Function to read file fileName and return the content as a string.

    fun readFromFile(fileName: String): String {
     var fileInputStream: FileInputStream? = null
    fileInputStream = openFileInput(fileName)
    var inputStreamReader: InputStreamReader = InputStreamReader(fileInputStream)
    val bufferedReader: BufferedReader = BufferedReader(inputStreamReader)
    val text = bufferedReader.readLine()
    return text
    }

  • Function to increment (if action = "Inc") or decrement the content of file fileName by 1

    fun incDecFileContentByOne(fileName: String, action: String) {

        var value: String = ""

     if (action == "Inc") {
     if (fileExist(fileName)) {
     value = readFromFile(fileName)
    value = (value.toInt() + 1).toString()
    writeToFile(fileName, value)
     } else {
     writeToFile(fileName, "1")
    }
    } else {
    if (fileExist(fileName)) {
    value = readFromFile(fileName)
    if (value.toInt() > 0) {
    value = (value.toInt() - 1).toString()
    writeToFile(fileName, value)
    }
    }
    }
    }
  • Function to exit the app if back button is pressed twice.
    private var doubleBackToExitPressedOnce = false
    override fun onBackPressed() {
    if (doubleBackToExitPressedOnce) {
    super.onBackPressed()
    finishAffinity()
    System.exit(0)
    return
    }

    this.doubleBackToExitPressedOnce = true
    Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show()

    Handler().postDelayed(Runnable {
    doubleBackToExitPressedOnce = false

     }, 2000)
    }

  • Function to find the last updated date for file fileName

    fun fileChangedDate(fileName: String): String {
    val dirPath = filesDir
    val f = File(dirPath.toString())
    val filePath = f.toString() + "/" + fileName
    val file = File(filePath)

    if (file.exists()) {
    val lastModified = Date(file.lastModified())
    val formatter = SimpleDateFormat("dd/MM/yyyy")
    return formatter.format(lastModified)
    } else {
    return 0.toString()
    }
    }

  • Function to get current date

    fun getCurrentDate(): String {
    val dateFormat = SimpleDateFormat(DATE_FORMAT)
    dateFormat.timeZone = TimeZone.getTimeZone("UTC")
    val today = Calendar.getInstance().time

    return dateFormat.format(today)
    }

  • Function to get current time

    fun getCurrentTime(): String {

        val dateFormat = SimpleDateFormat(TIME_FORMAT)
    dateFormat.timeZone = TimeZone.getTimeZone("UTC")
    val today = Calendar.getInstance().time
    return dateFormat.format(today)
    }


Appreciate your patients and thanks for reading through the end of this blog. Please comment and let me know your thoughts. If you want to find out about my other apps please visit Play Store


Comments