Use string variable as object key - android

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)

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.

arrayListOf showing Int rather than String - Kotlin

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)

How to make variable from an array

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)

Convert EditText Array to String Array - Kotlin Android

I have an array of EditTexts that I would like to get converted into an Array of Strings containing the input values of each of the EditTexts. Here is my code:
val textFields = arrayOf<EditText>(dialogView.findViewById(R.id.et_name),
dialogView.findViewById(R.id.et_address), dialogView.findViewById(R.id.et_phoneNo),
dialogView.findViewById(R.id.et_amount), dialogView.findViewById(R.id.et_remark))
How do I get a String Array of the values of the EditTexts with minimal code?
Edit: Basically I want to fit the code as an argument in a function. I would prefer to have it done without using a for-loop. Perhaps an inline function that would give out an array transforming (as given in the function block) each element (EditText) of the original one to a string. I couldn't find any method so far (although it might turn out to be something obvious).
I also need to use it as a vararg parameter.
Todo this you have to map it into a string array by doing the following:
val newTextFieldStringArray = textFields.map { it.text.toString() }
Log.e("TEST", newTextFieldStringArray.toString()) // print it out
Note:
The map function returns a List. If you'd like to use it as a vararg parameter, you can achieve that using toTypedArray() and a spread operator *. Code As follows:
val varargArray = textFields.map { it.text.toString() }.toTypedArray()
myFunction(*varargArray)
private fun myFunction(vararg list: String) {}

Android regexp HTML

I've got a HTML code stored in string and I want to extract all parts that match the pattern, which is:
<a href="http://abc.pl/(.*?)/(.*?)"><img src="(.*?)"
(.*?) stands for any string. I've tried dozens of combinations and couldn't get it working. Can somebody show me a sample code, which extracts all matched data from a String and store it in variables?
Thanks in advance
Here is a solution using JavaScript. I hope this helps.
First, we need a working pattern:
var pattern = '<a href="http://abc.pl/([^/"]+)/([^/"]*)".*?><img src="([^"]*)"';
Now, the problem is that in JavaScript there is no native method or function that retrieves both all matches and all submatches at once, whatever the regexp we use.
We can easily retrieve an array of all the full matches:
var re = new RegExp(pattern, "g");
var matches = yourHtmlString.match(re);
But we also want the submatches, right? In my humble opinion, the simplest way to achieve this is to apply the non-greedy version of the same regexp to each match we obtained (because only non-greedy regexes can return submatches):
var reNonGreedy = new RegExp(pattern);
var matchesAndSubmatches = [];
for(var i = 0; i < matches.length; i++) {
matchesAndSubmatches[i] = matches[i].match(reNonGreedy);
}
Each element of matchesAndSubmatches is now an array such that:
matchesAndSubmatches[n][0] is the n-th full match,
matchesAndSubmatches[n][1] is the first submatch of the n-th full match,
matchesAndSubmatches[n][2] is the second submatch of the n-th full match, and so on.
Well, here's the sample:
Pattern pattern = Pattern.compile("patternGoesHere");
Matcher matcher = pattern.matcher(textGoesHere);
while (matcher.find())
{
// You can access substring here via matcher.group(substringIndex) [note they are indexed from 1, not 0]
}

Categories

Resources