Sunday, March 20, 2016

android - Get string from resources using name

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    android:background="#e4e3de"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="40sp"
        android:textColor="#000000"
        android:textStyle="bold"
        />
    <TextView
        android:id="@+id/tv_second"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="40sp"
        android:textColor="#418910"
        android:textStyle="bold"
        android:layout_below="@id/tv"
        />
</RelativeLayout>
res/values/strings.xml

<resources>

    <string name="app_name">Android Example</string>
    <string name="title_activity_settings">Settings</string>
    <string name="title_activity_main">Android Example - Get String From Resources Using Name</string>

    <string name="country">Bangladesh</string>
    <string name="city">Khulna</string>

</resources>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.app.Activity;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RelativeLayout;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {

    private Context mContext;
    private Activity mActivity;

    private RelativeLayout mRelativeLayout;
    private TextView mTextView;
    private TextView mTextViewSecond;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the application context
        mContext = getApplicationContext();

        // Get the activity
        mActivity = MainActivity.this;

        // Get the widgets reference from XML layout
        mRelativeLayout = (RelativeLayout) findViewById(R.id.rl);
        mTextView = (TextView) findViewById(R.id.tv);
        mTextViewSecond = (TextView) findViewById(R.id.tv_second);

        // Set the first TextView text from string resource by resource id
        mTextView.setText("Country : " + getResources().getString(R.string.country));

        // Set the second TextView text from string resources by resource name
        mTextViewSecond.setText("City : " + getStringFromResourcesByName("city"));
   }

    // Custom method to get a string resource by resource name
    private String getStringFromResourcesByName(String resourceName){
        /*
            getPackageName()
                Return the name of this application's package.
        */
        // Get the application package name
        String packageName = getPackageName();

        /*
            getResources()
                Return a Resources instance for your application's package.
        */
        /*
            public int getIdentifier (String name, String defType, String defPackage)
                Return a resource identifier for the given resource name. A fully qualified resource
                name is of the form "package:type/entry". The first two components (package and type)
                are optional if defType and defPackage, respectively, are specified here.

                Note: use of this function is discouraged. It is much more efficient to retrieve
                resources by identifier than by name.

            Parameters
                name String: The name of the desired resource.

                defType String: Optional default resource type to find, if "type/" is
                    not included in the name. Can be null to require an explicit type.

                defPackage String: Optional default package to find, if "package:" is not
                    included in the name. Can be null to require an explicit package.
            Returns
                int : int The associated resource identifier. Returns 0 if no such resource
                    was found. (0 is not a valid resource ID.)
        */
        // Get the string resource id by name
        int resourceId = getResources().getIdentifier(resourceName,"string",packageName);

        // Return the string value
        return getString(resourceId);
    }
}