I have a long string array list of "Animals" that I need to associate a code number with.
Once the "Animal" is selected via my spinner the value is stored in a variable. I also want to have the associated code number stored in its own variable.
How do I go about creating this "pairing" without writting a ton of if/then code. Can I do anything within my strings.xml file that contains my string-array?
<string-array name="Animals">
<item>Dog</item>
<item>Cat</item>
<item>Mouse</item>
...
"Dog" paired with code: "111"
"Cat" paired with code: '222"
"Mouse" paired with code:"333"
You can create the corresponding integer-array and zip them together. There is one BIG WARNING with this though, you have to make sure that if you change one of the arrays, you must update the other too!
Kotlin playground example:
fun main() {
val stringArray: Array<String> = arrayOf("Dog", "Cat")
val intArray: Array<String> = arrayOf("1", "0")
print(sArray.zip(iArray))
}
If the corresponding code is going to be only their index in the array it's simple as:
arrayOf("Dog", "Cat").mapIndexed { index, animal -> index to animal }
So with your example it would be something like this:
<string-array name="Animals">
<item>Dog</item>
<item>Cat</item>
<item>Mouse</item>
...
</string-array>
<integer-array name="AnimalsNumberCodes">
<item>111</item>
<item>222</item>
<item>333</item>
...
</integer-array>
val listOfPairs = resources.getStringArray(R.array.Animals)
.zip(
resources.getIntArray(R.array.AnimalsNumberCodes).toTypedArray()
)
To address the change in the question. All you have to do to get that lookup is to change to a map.
spinnerMap = resources.getStringArray(R.array.Animals)
.zip(
resources.getIntArray(R.array.AnimalsNumberCodes).toTypedArray()
).toMap()
spinnerMap["Dog"] // "111" or whatever you zip it with
Related
I am trying to get string value from string file like this:
var language = arrayListOf<String>(
R.string.All_Categories.toString(),
)
but it shows an Int rather than a string like this:
What am I doing wrong?
R.string.All_Categories is the id, not the string itself
To get the string you need to use
var value = getString(R.string.All_Categories)
The issue is you are doing toString on the generated reference. You should instead use R.array.All_Categories if that is the name of your referenced array. For example, you have the following in the resources file.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="my_books">
<item>Scala Cookbook</item>
<item>Play Framework Recipes</item>
<item>How I Sold My Business: A Personal Diary</item>
<item>A Survival Guide for New Consultants</item>
</string-array>
</resources>
This is how you would want to read it in the code.
Resources res = getResources();
String[] myBooks = res.getStringArray(R.array.my_books);
Kotlin code example in fragment:
val res: Resources = resources
val myBooks: Array<String> = res.getStringArray(R.array.my_books)
You can use .toList() on the Array<String> to convert it to a collections object like the arrayListOf<String> expected by you.
SOLUTION:
first, in OnCreate must define the string:
val Profile_Settings = resources.getString(R.string.ProfileSettings)
second, add the value to the array:
var language2 = arrayListOf<String>(
Profile_Settings,
)
it's very simple, you just have to use getString(your_string_id) and you are good to go!
which looks like this:
val data = getString(R.string.all_categories)
I am trying to make place dropdowns for user locations in my app. I'm using Exposed Drop-Down Menu not spinners. I've set it up so that depending on which country you have your self set to, it changes the next dropdown to reflect that.
this is how I do it:
val country= resources.getStringArray(R.array.nations)
val arrayadapters = ArrayAdapter(requireContext(), R.layout.country_dropdown, country)
view.autoCompleteTextView.setAdapter(arrayadapters)
view.autoCompleteTextView2.setOnClickListener {
val abc = autoCompleteTextView.text.toString()
if(abc == "canada"){
var country2= resources.getStringArray(R.array.canada)
val arrayadapters2 = ArrayAdapter(requireContext(), R.layout.locality_dropdown, country2 )
view.autoCompleteTextView2.setAdapter(arrayadapters2)
}
if (abc == "us"){
var country2 = resources.getStringArray(R.array.american_states)
val arrayadapters2 = ArrayAdapter(requireContext(), R.layout.locality_dropdown, country2)
view.autoCompleteTextView2.setAdapter(arrayadapters2)
}
}
anyways this takes what country you have selected and depending on that gives you a drop-down of all the regions within that country
the problem that I'm having is that of code scalability, I don't think It would be wise or reasonable to copy, paste and modify for each and every locality.
so my question is this. how do you set the name of the string array to a variable so I can have 1 line of code and just switch out the name of the location and have it read the string array that way.
if you're wondering the string array is XML stored int the res\values\strings.xml as something like this
<string-array name="canada">
<item>Alberta</item>
<item>British Columbia</item>
<item>Manitoba</item>
<item>New Brunswick</item>
<item>Newfoundland and Labrador</item>
<item>Nova Scotia</item>
<item>Nunavut</item>
<item>Ontario</item>
<item>Prince Edward Island</item>
<item>Northwest Territories</item>
<item>Quebec</item>
<item>Saskatchewan</item>
<item>Yukon</item>
</string-array>
thank you for reading my question, if you have any questions please ask.
Edited: this was a Java solution, since question was originally tagged as asking about Java. Don't spray language tags at random.
This is what maps are for. A sketch of an approach, rather than full code, follows.
The setup:
class CountryStuff {
Country country;
ArrayAdapter adapter;
...etc...
CountryStuff(Country c, ArrayAdapter a, ...etc...) {
country = c;
adapter = a;
...etc...
}
}
Map<String,CountryStuff> map = new HashMap<>();
map.put("canada", new CountryStuff(...whatever...);
map.put("us", new CountryStuff(...whatever...);
The use:
String abc = "something"; // country name as determined before
CountryStuff stuff = map.get(abc);
if (stuff == null) {
... no such country ...
}
else {
country2 = stuff.country;
adapter2 = stuff.adapter;
... etc ...
}
I don't know why array is not recognized when I create a string and type the following code to access it in MainActivity.kt:
var values: Array <String> = resources.getStringArray (R.array.names)
Define the data type of array just like below:
var values = resources.getStringArray (R.array.system)
Or
just write var values = resources.getStringArray (R.array.names)
It will automatically get the required type.
Define the array like below:-
<string-array name="system">
<item>p</item>
<item>fdd</item>
</string-array>
Begin new project in Kotlin and missing those.
Try to get string-array recources but can't.
In strings.xml I palced next items.
<string-array name="themeList">
<item>white</item>
<item>sepia</item>
<item>black</item>
<item>pink</item>
</string-array>
In code I try next:
val res: Resources = resources
val appThemeList = arrayOf(res.getStringArray(R.array.themeList))
for (value in appThemeList) {
Log.i ("value", value.toString())
}
But in logCat i see:
I/value: [Ljava.lang.String;#40145f2
And I don'r understand, what I do incorrectly.
replace
val appThemeList = arrayOf(res.getStringArray(R.array.themeList))
to
val appThemeList = res.getStringArray(R.array.themeList)
In other case you got array
val myArray = res.getStringArray(R.array.themeList) //already array
And added to another array
arrayOf(myArray) // array of arrays
In android is depend on context when outside Activity like this
val themes = context.resources.getStringArray(R.array.themeList)
or without context is direct to resource when inside Activity
val themes = resources.getStringArray(R.array.themeList)
As we know res.getStringArray return arraylist so you do not need to write arrayOf on your code.
Simple way to achieve your goal is:-
val list = res.getStringArray(R.array.list);
We can use arrayOf when we have to define our array or we have already arraylist like below :-
val myArray = arrayOf(4, 5, 7, 3);
Try this,
val Lines = Arrays.asList(resources.getStringArray(R.array.list))
In kotlin use :
var yourVar = resources.getStringArray(R.array.your_string_array)
In kotlin, also need to use context like below
var arry = context.resources.getStringArray(R.array.your_string_array)
With this line of code you get exactly the element in the place of index.
val the_string = resources.getStringArray(R.array.YOUR_STRING_ARRAY)[index].toString()
This will be your res/values/strings.xml
<string-array name="YOUR_STRING_ARRAY">
<item>kJ</item>
<item>kWh</item>
<item>Btu</item>
<item>kcal</item>
</string-array>
As an example if the index is 1 then the return value is "kWh"
If you want use the path of resources in RecyclerView.Adapter Class you must put into function onBindViewHolder
val myItem = holder.itemView.resources.getStringArray(R.array.myItem_string_array)
I need to randomly select a string defined within strings.xml file in android.
For example my strings.xml is :
<resources>
<string name="str1">Content comes here1</string>
<string name="str2">Content comes here2</string>
<string name="str3">Content comes here3</string>
</resources>
Can I randomly select one of these strings in my Activity?
Create an array contains all of your resource names you want to select:
String[] strs = new String[] {"str1", "str2", "str3"};
Get a random index:
int randomIndex = new Random().nextInt(3);
Get your random string from resource:
int resId = getResources().getIdentifier(strs[randomIndex ], "string", your_package_name);
String randomString = getString(resId);
The best way is you declare you Strings as an Array, then get it like this:
String[] arrayOfStrings = context.getResources().getStringArray(R.array.your_string_array);
String randomString = arrayOfStrings[new Random().nextInt(arrayOfStrings.length)];
Then you can use it as you like.
You would probable rather make it an array of strings (and then that is easier to select at random one of the array). Else, you can put the ids of your strings in an array and randomly select one of the items in the array.