Unable to use string resources for list view items

55 Views Asked by At

I'm trying to use string resources for my 2-line list view items rather than hard-coding them but I get this error. How can I fix that?

Before using string resources

public class ListData {

    public static final String[][] items = {
            {"America","America Description"},
            {"Europe","Europe Description"},
    };
}

After using string resources

public class ListData {

    public static final String[][] items = {
            {R.string.america,R.string.america_description},
            {R.string.europe, R.string.europe_description},
    };
}

Error

Incompatible types. Required: java.lang.String | Found: int

3

There are 3 best solutions below

0
On BEST ANSWER

it is because R.string.america is an integer which represent a string inside strings.xml. So you should change the type for String[][] to int[][]. If you have to assign the value to a TextVIew android will take care of the look up in strings.xml.

0
On

you are either using ENUMs in which case, there will be an integer assigned to each String that you have or you are using auto generated values, in which java/android produces constant integers in place of strings that you give.

either way, the output of R.string.somestring is an integer and your declarations expects you to input Strings. hence the error

0
On

You need to know that in the R class are only references stored which are resolved to the String they represent. This references are all Integers. So you have two possibilities to solve this:

  1. Simply change the type of your 2D array to int
  2. Resolve the String references using getResources().getString(stringRes) and then add it to your String array