How to make variable from an array - android

I'm using an array like below and I'm using "category" variable after that without problem.
var category = resources.getStringArray(R.array.**main_menu**)
My question is, how can I make a variable "main_menu"?
There are other arrays also exist and I want to send their names as a varible in this line?
I tried the code below, but surely it's not working, because it's text and "getStringArray" expecting Int.
var **text** = R.array.main_menu
var mainCategory = resources.getStringArray(**text**)

By using getIdentifier() method, you can get the integer id of your resource. That method accepts three parameters:
Name of the resource as string
Type of the resource, which is in your case "array"
Package name
By using the resource id returned from resources.getIdentifier(arrayName, "array", getPackageName()), you can get array.
Here is full code:
var arrayName = "main_menu"
val resId = resources.getIdentifier(arrayName, "array", context.packageName)
var mainCategory = resources.getStringArray(resId)

Related

How to convert string which have array and string elements inside it, to fetch each element from the array in Kotlin [Android]

My output looks like this :
["Floor 0","Floor 1","Floor 2"]
It comes as a string. But I want to fetch each element of this array. How can I do this using Kotlin ?
implement this library Gson
you can use it like this
val text = "[\"Floor 0\",\"Floor 1\",\"Floor 2\"]"
val array = Gson().fromJson(text, ArrayList::class.java)
array.forEach {
Log.e(TAG, "onCreate: it $it")
}
Just use regular expressions to create a match for each CharSequence between the double quotes. As you want to use only the values between the quotes, you can extract the first index group values. The following code snippet does what you are asking for in Kotlin:
val str = "[\"Floor 0\",\"Floor 1\",\"Floor 2\"]"
val pattern = Regex( "\"(.*?)\"")
val fetched_elements = pattern.findAll(str).map {
it.groupValues[1]
}.toList()
// creates the list: [Floor 0, Floor 1, Floor 2]
Use also this RegExr example to explore this in detail with explanation.
If your internal strings aren't allowed to have commas, you could do it with a split function to convert it into a list:
var lst = str.replace("\"", "").split(",")
If your internal strings can have trailing whitespace, this would be better:
var lst = str.replace("\"", "").split(",").map { it.trim() }
In the above code lines, the replace function removes the quotes surrounding each internal string; the split separates the string at each comma; and the trim function removes any surrounding whitespace characters.
If your internal strings can contain commas, you're better off learning about and using regular expressions as mentioned in another answer.

Converting an int array of Drawable images to a string array of their filenames

I'm using SharedPreferences to save an array of Drawables as Int (which is later used to set setImageResource)
There's some logic I need to perform on SharedPreferences that requires me to get the actual filename, NOT the Int representation of the drawable.
My code is the following:
val imagesFromSaved = PrefsContext(context).savedLocations
imagesFromSaved prints the following:
[2131135903, 2131165414, 2134135800, 2131765348]
I need to be able to print the actual filename. Like this.
["image_one", "image_two", "image_three", "image_four"]
The closest I got was using getString with one single Int. But I'm not sure how to iterate over all the items in the array to convert everything to the string representation.
val test = context.resources.getString(2131135903)
Prints: res/drawable-nodpi-v4/image_one.webp
How can I iterate over my SharedPreferences to generate an array of Drawable filenames, instead of the Int representation of the resource?
To iterate through int array and convert them to strings you can use map function:
val imagesFromSaved = PrefsContext(context).savedLocations
val imagesNames: List<String> = imagesFromSaved.map {
context.getResources().getResourceEntryName(it)
}
map transforms the list of objects to a list of objects of another type.
The resulting imagesNames should contain the names of images.
According to your description, I suggest you should do as follows:
firstly, save the str which is your description fileName
Then get the fileName from sp
In the end, you have to use the str to generate the drawable id
//get the R.draw.fileName,it result is fileName
val fileName = context.getResources().getResourceEntryName(R.drawable.arrow_back)
// then use SharedPreferences get the str, To generate ID
val id = context.getResources().getIdentifier(fileName, "drawable", context.getPackageName());
// then use the id in imageView
imegeView.setImageResource(id)

Use string variable as object key

I have strings in my strings.xml e.g.:
<string name="category__service">Service</string>
I want to access them like this:
val key = "category__$this.name" // "category__service"
val s = R.string.[key]
This would give me the Id of the string which I can use.
But this way I get the error
The expression cannot be a selector (occur after a doted text)
I also tried
val s = R.string.$key
but I get:
Expecting an element
The documentation on what R is to begin with, isn't giving me much. As far as I see – R.string does not have a simple getter.
So at this point I'm just guessing for a solution. Is this even possible in Kotlin?
You can try following:
val key = "category__$this.name" // "category__service"
val s = resources.getIdentifier(key, "string", context.packageName)

I want to use var to determine which photo to load into the image-view- Kotlin

I have a var with kind of food in it (For example: pizza, burger ext.), I want to use that var to load a apecific image based on that var value from my drawable directory into the image view without using when.
I have those files: pizza.png, burger.png
I want to use something like this:
var food = "pizza.png"
food_icon.setImageResource(R.drawable.food)//image is the pizza
food = "burger.png"
food_icon.setImageResource(R.drawable.food)//image is the burger
Is there a way to do this?
If I understand your question correctly you can use following method:
Resources resources = context.getResources();
final int resourceId = resources.getIdentifier("[your_drawable_name]", "drawable", context.getPackageName());
return resources.getDrawable(resourceId);
With this you can specify the name of your rawable and load it.
If you need only the resourceId you can return the resourceId without getting the drawable itself.
You could use an enum which corresponds to the right drawable for example
enum class FoodTypes(private val value: Int) {
PIZZA(R.drawable.pizza),
BURGER(R.drawable.burger);
fun getValue(): Int = value
}
Then you can use it like this
var food = FoodTypes.PIZZA
food_icon.setImageResource(food.getValue())
food = FoodTypes.BURGER
food_icon.setImageResource(food.getValue())
why not doing this ?
var food = R.drawable.pizza
food_icon.setImageResource(food)//image is the pizza
food = R.drawable.burger
food_icon.setImageResource(food)//image is the burger

Can you call a string resource with a string?

I have a method that returns one of about 20 possible strings from an EditText. Each of these strings has a corresponding response to be printed in a TextView from strings.xml. Is there a way to call a string from strings.xml using something like context.getResources().getString(R.strings."stringFromMethod")? Is there another way to call a string from a large list like that?
The only methods I can think of is converting each string to an int, and use that to find a string in a string array, or a switch statement. Both of which involve a huge amount if-else if statements to convert the string to an int, and would take just enough steps to change if any strings were added or taken away that I'd be more likely to miss one and have fun bug hunting. Any ideas to do this cleanly?
Edit: Forgot to add, another method I tried was using was to get the resourceID from
int ID = context.getResources().getIdentifier("stringFromMethod", "String", context.getPackageName())
and taking that integer and putting it in
context.getResources().getString(ID)
That doesn't appear to be working either.
No, you can't. The getString() requires the resource id in integer format, so you can't append a string to it.
You can, however, try this:
String packageName = context.getPackageName();
int resId = context.getResources().getIdentifier("stringFromMethod", "string", packageName);
if (resId == 0) {
throw new IllegalException("Unknown string resource!"; // can't find the string resource!
}
string stringVal = context.getString(resId);
The above statements will return string value of resource R.string.stringFromMethod.
You need to use reflection (pretty ugly but only solution) load the R class, and get the relevant field by you string and get the value of it.
this is what I used to do in these kind of situations, I will made a Array like
int[] stringIds = { R.string.firstCase,
R.string.secondCase, R.string.thridCase,
R.string.fourthCase,... };
int caseFromServer=getCaseofServerResponse();
here caseFromServer varies from 0 to wahtever
and then simply
context.getResources().getString(stringIds[caseFromServer]);

Categories

Resources