How to insert res/string string in the String[]{} array;

Asked

Viewed 2,485 times

3

I’m trying to put my Strings in an array to use on Adapter and I can’t. I’m doing like this:

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

but it’s certainly not the right way. How to do?

  • 1

    Emerson, you can create an array of String within Resource. There is a better solution than retrieving item by item and adding to an array. Have a look at http://developer.android.com/guide/topics/resources/string-resource.html#Stringarray.

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 on 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);

2

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

Empty array with new

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

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

Array filled with new

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

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

Array set in declaration

When we are declaring an array, we can start it simply, like this:

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

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

This can even be done with multidimensional arrays:

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

Completion

Creating an array and filling 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 essential to know well the Apis available in the environment in which we work.

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));
  • then @helder, I can use so? ArrayAdapterItem adapter = new ArrayAdapterItem(this, R.layout.list_view_row_item, cores);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.