Loading a string from a string array in strings.xml

I use the following code snippet in my application:

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

The problem is that I run an operation that contains this code many times. This way, I feel that this code is inefficient, since every time I run the operation, I need to load the whole array to just use one element specifically, since the array of strings is very large.

Is there a way to load the desired item directly?

Thank you very much in advance:)

update: I tried using the Application object as Talihawk listed below, but I get an error in the following line:

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

Error:

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

+4
source share
3 answers

You can use the Application object to store an array of strings as long as your application is active.

** EDIT **

First you must define your own 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 array of strings will be loaded only once for the duration of your application (if your application is killed, you still have to restart it)

You can find more information in the following link

+8
source

You can create a helper object with a static method to load / return an array of strings, so it will be loaded only once. If you want a real fantasy, you can declare it a soft or weak link so that it does not hang, but this is your call ... depends on the size of the array and the application.

 public class StringHelper { private static String[] stgArray; public static String[] getMyStringArray( Context ctx ) { if ( stgArray == null ) { stgArray = ctx.getResources().getStringArray(R.array.array_of_strings); } return stgArray; } 
+1
source

Source: https://habr.com/ru/post/1399446/


All Articles