0

so as my question says, I am in a situation where I need to get ten different strings using getResources() and then compare them to a string the user enters.
This is how I'm doing it currently:

if(string == getResources().getString(R.string.x)) 

Since this code is going to be repeated ten times for ten different strings in R.java, I'm wondering if there is going to be a loss in performance by calling getResources() so many times.

Is there an easier solution, like creating an object from getResources() and then getting one string at a time from that object?

Sorry if I'm blabbering, I'm new to this.

Thanks!

Carl Witthoft
  • 20,573
  • 9
  • 43
  • 73
Dakshin
  • 437
  • 1
  • 6
  • 16
  • `string ==` ... good luck ... anyway http://c2.com/cgi/wiki?PrematureOptimization – Selvin Jul 23 '14 at 11:32
  • 1
    if you are so worried just assign it once: `final Resources resources = getResources()` . Also for string you have to use `equals` not `==` – Blackbelt Jul 23 '14 at 11:32

4 Answers4

2

Then you can do something like this:

Resources res = yourContext.getResources();
//use this res variable instead of getResources() function a small example
Bitmap bitmap = BitmapFactory.decodeResource(res,R.id.ic_launcher);
Illegal Argument
  • 10,090
  • 2
  • 44
  • 61
  • 1
    Thanks! Thats the answer I wanted.. sort of. Just a thought, supposing I'm in the onCreate() method, can I just type in "this" in place of yourContext, or do I need to specify it like, "MainActivity.this"? – Dakshin Jul 23 '14 at 16:03
0

Another approach is to add the strings you're getting as a string-array

<string-array name="string_array_name">
    <item>text_string</item>
    <item>text_string</item>
</string-array>

and get your array:

String[] myArr = getResources().getStringArray(R.array.string_array_name);

and loop over them .. you'll call getResources() once ...

But anyways resources object is a shared object throughout the application and you're merely calling it's getter so no performance isuue there

elmorabea
  • 3,243
  • 1
  • 14
  • 20
0

you can create an array in string.xml

string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="item_array">
        <item>item 1</item>
        <item>item 2</item>
        <item>item 3</item>
        <item>item 4</item>
...
    </string-array>
</resources>

in your java code you access this as

String[] mTestArray =   getResources().getStringArray(R.array. item_array);
Yaseen Ahmad
  • 1,807
  • 5
  • 25
  • 43
0

To avoid the getResources() repeated call, create before a variable of type Resources, and use it instead of the call, as follows:

Resources res = getResources();
if (string == res.getString(R.string.x);

In this way, you can also pass the variable as a parameter to other methods/functions, having only one call to getResources() in all your code.

Jared Forth
  • 1,577
  • 6
  • 17
  • 32
Raaaaac
  • 86
  • 2
  • 6