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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With