Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are all strings of strings.xml are always available in heap memory in Android?

Tags:

string

android

Suppose in an apk we have 1000 strings in strings.xml.

So when we run this app on device at that time all the strings are always available in heap memory. Or they loaded in memory when we call getString() method of Context to load the Strings.

Are all strings in the heap during runtime?

like image 994
Sharad Avatar asked Oct 25 '16 07:10

Sharad


People also ask

Where is strings xml in Android?

String. xml file contains all the strings which will be used frequently in Android project. String. xml file present in the values folder which is sub folder of res folder in project structure.In Android Studio, we have many Views such as TextView,Button,EditText,CheckBox,RadioButton etc.

In which folder can you find the string resource file strings xml?

You can find strings. xml file inside res folder under values as shown below.

Why do we store strings as resources in xml?

The purpose of strings. xml (and other *. xml resource files) is to regroup similar values in one place. This facilitates finding values that would be otherwise buried in the code.

What is the role of strings xml file in an Android application?

A string resource provides text strings for your application with optional text styling and formatting. There are three types of resources that can provide your application with strings: String. XML resource that provides a single string.


1 Answers

This is a great question. We can try to find the answer by studying the Android source code.

All calls to getString() get routed to the following method inside android.content.res.AssetManager:

/**
 * Retrieve the string value associated with a particular resource
 * identifier for the current configuration / skin.
 */
/*package*/ final CharSequence getResourceText(int ident) {
    synchronized (this) {
        TypedValue tmpValue = mValue;
        int block = loadResourceValue(ident, (short) 0, tmpValue, true);
        if (block >= 0) {
            if (tmpValue.type == TypedValue.TYPE_STRING) {
                return mStringBlocks[block].get(tmpValue.data);
            }
            return tmpValue.coerceToString();
        }
    }
    return null;
}

loadResourceValue is a native function and can be found in android_util_AssetManager.cpp

The native method calls getResource() inside the class ResTable here.

The constructor for ResTable calls addInternal() here which reads the resources for each package id in the app. This table is later used to perform lookups of resources.

So to answer your question, yes, all strings (and indeed all resources) are parsed from the filesystem and loaded into a lookup table in the native heap.

like image 105
Nachi Avatar answered Oct 19 '22 02:10

Nachi