Android Kotlin: How to get string resource by name

The code demonstrates how to retrieve a string resource by its name in an Android application written in Kotlin. It defines an extension function stringFromResourcesByName that takes the resource name as a parameter and returns the corresponding string value.

Here's a breakdown of the code:

  1. Import Statements:

    • The code starts by importing necessary classes like Context, Resources, etc. These classes provide access to Android's resource framework.
  2. MainActivity Class:

    • The MainActivity class inherits from AppCompatActivity, which is the base class for most activities in Android applications.
  3. onCreate Method:

    • The onCreate method is the entry point of the activity's lifecycle. It's called when the activity is first created.
  4. Setting Layout:

    • Inside the onCreate method, the setContentView method is used to set the layout file (activity_main.xml) for the activity.
  5. Get String Resource:

    • The following line retrieves the string resource by name:
    Kotlin
    textView.text = applicationContext.stringFromResourcesByName("developer")
    
    • Here, applicationContext.stringFromResourcesByName("developer") calls the extension function to get the string resource named "developer". The retrieved string value is then assigned to the text property of the TextView with the id textView.
  6. stringFromResourcesByName Extension Function:

    • The stringFromResourcesByName function is defined as an extension function of the Context class. This allows you to call this function on any context object.

    • The function takes a string parameter resourceName which represents the name of the string resource to retrieve.

    • Inside the function, it attempts to get the resource ID for the given resource name using getIdentifier method. It takes three arguments:

      • The resource name (resourceName)
      • The resource type ("string" in this case)
      • The package name of the application (packageName)
    • If the resource is found, the function retrieves the string value using the getString method with the resource ID and returns it.

    • If the resource is not found, it catches a Resources.NotFoundException and returns null.

Summary:

The provided code snippet showcases a practical approach to fetching string resources by name in an Android Kotlin project. The stringFromResourcesByName extension function offers a concise way to access string resources from within your activities or other parts of your code. This promotes better code organization and maintainability by separating UI strings from the application logic.


MainActivity.kt

package com.example.jetpack

import android.content.Context
import android.content.res.Resources
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // get string from resources by resource name and show it
        textView.text = applicationContext
            .stringFromResourcesByName("developer")
    }
}


// extension function to get a string resource by resource name
fun Context.stringFromResourcesByName(resourceName: String): String? {
    return try {
        // get the string resource id by name
        val resourceId = resources.getIdentifier(
            resourceName,
            "string",
            packageName
        )

        // return the string value
        getString(resourceId)
    }catch (e:Resources.NotFoundException){
        null
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#EDEAE0"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:fontFamily="sans-serif-condensed"
        android:gravity="center"
        android:padding="32dp"
        android:textColor="#0014A8"
        android:textSize="35sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="TextView" />

</androidx.constraintlayout.widget.ConstraintLayout>
res/values/strings.xml

<resources>
    <string name="app_name">Kotlin - Get string resource by name</string>
    <string name="developer">Saiful Alam, Khulna, Bangladesh</string>
</resources>
More android kotlin tutorials