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?
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?
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);
I suggest creating a String list
List<String> cores = new ArrayList<String>();
cores.add(getString(R.string.cor1));
cores.add(getString(R.string.cor1));
Just to leave a correct reference to Arrays in Java (which does not fit into a comment), the documentation defines the following boot modes:
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.
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" } );
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"}
};
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.