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) {}
Related
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.
I want to add a field of type array inside a collection.
if the field doesn't exist create it. if it exists overwrite it with the new array value.
the field should be called macAddress and it's of type array of String
I have tried the following:
val macInput = setting_mac_text.text.toString()
val macArray = macInput.split(",")
val macList = Arrays.asList(macArray)
val data =
hashMapOf(Pair(FirebaseConstants.USER_MAC_ADDRESS, macArray))
//save it in firebase
db.collection(FirebaseConstants.ORGANIZATION)
.document(orgID + ".${FirebaseConstants.USER_MAC_ADDRESS}")
.set(FieldValue.arrayUnion(macList))
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.d(TAG, "successfully inserted")
} else {
Log.d(TAG, " failed ${task.exception}")
}
}
also tried to insert the list itself and hash map like this
val data = hashMapOf(Pair(FirebaseConstants.USER_MAC_ADDRESS, macArray))
db.collection(FirebaseConstants.ORGANIZATION)
.document(orgID)
.set(data))
but it keeps giving me java.lang.IllegalArgumentException: Invalid data. Nested arrays are not supported
what am I doing wrong here?
You're doing three things wrong here:
FieldValue.arrayUnion() is only meant to be used as the value of a field to add elements to that field. The way you are using it now in the first sample, it's being taken as the entire contents of the document.
set() with one parameter is only intended to create or overwrite an entire document. It can't be used to update an existing document. You would have to pass in SetOptions to tell it to merge if you want an update. Or, you would simply use update() to modify an existing document.
Your code that deals with macArray and macList isn't working the way you expect. You are creating a list with one element, which is itself an array. The error message is telling you that you can't have nested arrays like this.
I suggest taking a step back and simplifying your code, removing all the moving parts that don't have to do with Firestore. Just hard code values in your Firestore update until the update works the way you want, then add in the code that works with actual values. Get one simple thing to work, then add to it. If you get an error, you will know that the code you just added was incorrect.
To overwrite an array, you would simply call the set method and have the merge option set to true:
try {
const query = await DatabaseService.queryBuilder({
collection: CollectionName,
});
return await query
.doc(insuranceId)
.set(
{ DOCUMENT_PROPERTY_HERE: ARRAY_HERE },
{ merge: true }
);
} catch (exception) {
return Promise.reject(exception);
}
how can i change item's data type in arrays or lists in kotlin ?
i found a usual way but i need an easier and faster and better way to change data type of an array :)
fun typeChanger (data:MutableList<Number>): DoubleArray {
val result = mutableListOf<Double>()
for (i in data.iterator()){
result.add(i.toDouble())
}
return result.toDoubleArray()
}
val x = mutableListOf<Number>(+1,+1,-1,-1)
val xx:DoubleArray = typeChanger(x) // It works but i need an easier and faster and better way :)
Array map is your friend. You could keep your function and simplify, or remove it completely as below:-
val xx = x.map { it.toDouble() }
Once it's a list of doubles, you can then leave as a list or use .toDoubleArray() if you need an array.
Trying to understand the difference between map and mapTo in kotlin. Could anyone help me out in explaining the difference using some examples
map creates a new list internally, and puts its results into that list, then it returns that list:
val mapResult = listOf(1, 2, 3).map { it * 2 } // you get a new list instance returned
If you use mapTo instead, you can specify the destination where it places the mapped elements, by providing your own list as the first parameter:
val myList = ArrayList<Int>()
val mapToResult = listOf(1, 2, 3).mapTo(myList) { it * 2 }
If the list you're provided already has elements in it, those will be kept, and the new ones will be added to those. It also returns the destination list for convenience.
map: map can transform your data(List) and can return either complete modified list or List of a variable of model, for ex:
You have a model:
data class Student(var id:String, var name:String, var className:String)
Now from arrayOfStudent, we want all the name of students in capital letters, so apply map like this:
val listOfNamesInCapitalLetters= arrStudent.map {
it.name= it.name.toUpperCase()
}
Log.d("map_test", "student's name: $listOfNamesInCapitalLetters")
The output will be:
[AMIT, VIJAY, SUMIT, KARAN, SMAEER]
Now, what if you want the whole student list, with name in capital letters and className is increased by 1, let's do this:
val result= arrStudent.map {
it.name= it.name.toUpperCase() // transforming name to upper case
it.className=it.className+1 // increasing class by 1
it // <- Note that we return it, because list will be prepared of the object which is returned by last statement of map
}
Log.d("modified_list", result.toString())
The output will be:
[Student(id=1, name=AMIT, className=6), Student(id=2, name=VIJAY, className=7), Student(id=3, name=KARAN, className=8), Student(id=4, name=VIRAT, className=9), Student(id=5, name=SAM, className=10)]
mapTo: If you want to transform your list into a different type of list then use mapTo, for example, we have a different data class named: CompactStudent
data class CompactStudent(val id:String, val name:String)
Now if we want to convert List to List, note that CompactStudent contains id and name but not the className as compared to Student model, so to do this:
val arrayList=ArrayList<CompactStudent>()
arrStudent.mapTo(arrayList){
CompactStudent(it.id,it.name)
}
Log.d("studentCompact", arrayList.toString())
Output will be:
[StudentCompct(id=1, name=AMIT), StudentCompct(id=2, name=VIJAY), StudentCompct(id=3, name=KARAN), StudentCompct(id=4, name=VIRAT), StudentCompct(id=5, name=SAM)]
I have a probleme here.
I don't know how to read all values of a SharedPreferences for one particular key.
Actually I'm trying to write an Arraylist in preferences , then read it.
Let me explain with some code, Here is my methods for write in preferences :
fun writeArrayOnPreferences(key: String?, array: ArrayList<String>, c:Context) {
val preferences = c.getSharedPreferences(
c.getString(key), Context.MODE_PRIVATE)
with(preferences.edit()) {
for (value in array) {
putString(key, value)
}
commit()
}
}
My writing code works , it's persistent , but I don't really understand how to READ this Arraylist from preferences.
I tried a lot of things to read this but it show me only the last element wrote in preferences
I really want you to understand that I want multiple values for a specific key
This is a quick example based on Nabin Bhandari's answer
fun writeArrayOnPreferences(key: String, array: ArrayList<String>, c:Context) {
val jsonString = Gson().toJson(array)
pref.edit().putString(key, jsonString).commit()
}
fun readArrayFromPreferences(key: String, c: Context): ArrayList<String> {
val jsonString = pref.getString(key)
val array = Gson().fromJson(jsonString, ArrayList<String>()::class.java)
return array
}
ok here how it is! If you want multiple data against one key in share pref editor then SET is your solution as After API 11 the SharedPreferences Editor accept Sets. You could convert your List into a HashSet or something similar and store it like that When your read it back, convert it into an ArrayList, sort it if needed and you're good to go.
//Set the values
val yourSet = HashSet<String>()
set.addAll(listOfExistingScores)
yourPrefEditor.putStringSet("key", yourSet)
yourPrefEditor.commit()
//Retrieve the values
val yourSet = yourPref.getStringSet("key", null)
SOLUTION NUMBER 2
would be like serializing the ArrayList and passing it! but there can be a catch if any value in your array does posses any rule that can't be Parced it will crash!
For More check this Thread this is in java but it will help tell you more!
You cannot simply loop values in an ArrayList put them in the preferences using same key for all values and expect to retrieve the ArrayList back.
You can convert the 'ArrayList' in JSON format and store it in SharedPreferences. Then to parse the JSON string to get the ArrayList.
You can make this process easier with the help of a library called Gson.
Try this:
with(preferences.edit()) {
var s = ""
for (value in array) {
s = s + value + ","
}
putString(key, value)
commit()
}
your array will be saved like comma separated values which when read back in a string, by using the split function will become an array.