Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading string from string array in strings.xml file

Tags:

android

I am using the following piece of code in my app:

string_array = getResources().getStringArray(R.array.array_of_strings);
my_text_view.setText(string_array[i]);

The problem is that I start the activity which contains this code many times. So, I feel that this code is inefficient as every time i start the activity i have to load the whole array to just use one element specially as the string array is very large.

Is there a way to load the wanted element directly?

Thanks a lot in advance :)

update: I tried using Application object as Talihawk stated below, but i get an error at the following line:

MyApplication my_obj = (MyApplication) getApplication();
string_array = my_obj.getStringArray(); 

The Error is:

android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)

like image 474
Elshaer Avatar asked Dec 22 '22 01:12

Elshaer


1 Answers

You can use the Application object to save the string array for as long as your application is active.

** EDIT**

First you have to define your custom Application class in your AndroidManifest.xml :

<application
    android:name="MyApplication"
    android:icon="@drawable/icon"
    android:label="@string/app_name"
>

** EDIT **

public class MyApplication extends Application {

    private String[] string_array;

    @Override
    public void onCreate() {
        super.onCreate();
        string_array = getResources().getStringArray(R.array.array_of_strings);
    }

    public String[] getStringArray() {
        return string_array;
    }
}

And in your activity just do :

string_array = ((MyApplication) getApplication()).getStringArray();
my_text_view.setText(string_array[i]);

This way your string array will only be loaded once for the duration of your application (if your application is killed you'll have to reload it anyway)

You can find more information in the following link

like image 108
Talihawk Avatar answered Jan 10 '23 18:01

Talihawk