How to insert string from res / string into array String [] {};

3

I'm trying to put my Strings in an array to use on the adapter and I can not. I'm doing this:

String cores[] = String[]{getString(R.string.cor1), getString(R.string.cor1)};

But it sure is not the right way. How to do?

    
asked by anonymous 20.08.2014 / 13:21

3 answers

6

You can declare a String array in the array.xml file (within the values directory):

<string-array name="cores">
    <item>@string/cor1</item>
    <item>@string/cor2</item>
</string-array>

Then create an array of Strings in your Activity:

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

And finally put this String in your ArrayAdapter:

ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(context,
                        android.R.layout.simple_dropdown_item_1line, cores);

ListView mListView = (ListView) findViewById(R.id.listView);
mListView.setAdapter(mAdapter);
    
20.08.2014 / 15:51
2

I suggest creating a String list

List<String> cores = new ArrayList<String>();
cores.add(getString(R.string.cor1));
cores.add(getString(R.string.cor1));
    
20.08.2014 / 13:51
2

Just to leave a correct reference to Arrays in Java (which does not fit into a comment), the documentation defines the following boot modes:

Array empty with new

int[] anArray = new int[10];
anArray[0] = 100;
anArray[1] = 200;
...

The first line, with new , simply allocates 10 spaces to the array. The following lines put values.

Array filled with new

In cases where it is necessary to pass an array as a parameter, we can create and already initialize as follows:

metodoQueRecebeParametro( new String[] { "Olá", "Mundo" } );

Array prepended in declaration

When we are declaring an array, we can initialize it in a simple way, like this:

int[] anArray = { 
    100, 200, 300,
    400, 500, 600, 
    700, 800, 900, 1000
};

Note that there is no new , only the keys with the values inside.

This can be done even with multidimensional arrays:

String[][] names = {
    {"Mr. ", "Mrs. ", "Ms. "},
    {"Smith", "Jones"}
};

Conclusion

Creating an array and populating it may not be the best way to work for all cases, but it is important to know how to work with this type of structure.

However, sometimes the number of elements varies, so it would be better to use a list ( ArrayList , for example).

In other situations, the API we use to retrieve data already provides ways to retrieve an array directly. Therefore, it is imperative to know well the APIs available in the environment in which we work.

    
20.08.2014 / 17:07