I am trying to form a list with the items in arrayOf. However, when I toList().toString that strArray between each item there is a white space that I am trying to get rid of. As you can see in the picture below; when I use replace( " ", "") it takes care of that, but it's also removing the white space between Item and the number. How can I remove the white space between each item without removing the white space between the item and number? If you look at the picture below; the logcat lists correctly, but there's no space between Item1 and the rest of the items. I want it to show Item 1 and so on. I've been doing trial and error for 2 hours, and I have been doing some researches online, and I can't seem to find a solution. I appreciate the help! Thanks!
White Space Result Problem
Here is my code...
private fun strArrayInListForm() {
val strArray = arrayOf("Item 1", "Item 2", "Item 3", "Item 4", "Item 5")
val splitItems: String = strArray.toList().toString()
val getItems: String = splitItems.split(",").joinToString("\n")
.replace("[", "").replace("]", "")
.replace(" ", "")
println(getItems)
}
I think you should replace the ", " with "\n" directly after your toString() instead of splitting by "," and all that, like this:
val strArray = arrayOf("Item 1", "Item 2", "Item 3", "Item 4", "Item 5")
val splitItems: String = strArray.toList().toString().replace(", ", "\n")
val getItems: String = splitItems
.replace("[", "").replace("]", "")
println(getItems)
You can trim the strings in the list before converting it to a string and then joining with a newline delimiter.
Related
I want to remove the first 3 letters from every item (String) in my List.
My Listitems look like this:
{2: test1.mp4
3: test2.mp4
4: test3.mp4
10: test4.mp4
11: test5.mp4
I want to remove the "{2: " from the firs item and for every other item i want to remove the number + the space, so that i only have the file name.
the substring method is the solution for your case :
String text = "11: test5.mp4";
String result = text.substring(3); // test5.mp4
and if you just want to remove extra space on sides, use trim method
String text = " test5.mp4 ";
String result = text.trim(); // test5.mp4
It will probably be better to use split() instead of trimming off the white space and using a set index.
const track = '11: test5.mp4';
final splitted = track.split(': ');
print(splitted); // [11, test5.mp4];
Currently it's a little bit unclear how your list looks exactly. I am assuming, you have the following list:
List<String> myList = [
"2: test1.mp4",
"3: test2.mp4",
"4: test3.mp4",
"10: test4.mp4",
"11: test5.mp4",
];
In this case, it's not necessarily only the first 3 letters that you want to remove. A scalable solution would be the following:
final List<String> myList = [
"2: test1.mp4",
"3: test2.mp4",
"4: test3.mp4",
"10: test4.mp4",
"11: test5.mp4",
];
//We are splitting each item at ": ", which gives us a new array with two
//items (the number and the track name) and then we grab the last item of
//that array.
final List<String> myFormatedList = myList.map((e) => e.split(": ").last).toList();
print(myFormatedList);
//[test1.mp4, test2.mp4, test3.mp4, test4.mp4, test5.mp4]
This question already has answers here:
Single TextView with multiple colored text
(21 answers)
Closed 1 year ago.
I have a textview where I concat two strings, I wan the first string alone to be in different color.
tvMobileNo.text = "Mobile Number : " + sharedPreferences.getString("mobile_number", "")
tvEmail.text = "Email : " + sharedPreferences.getString("email", "")
tvAddress.text = "Address : " + sharedPreferences.getString("address", "")
In this I only want the first string(""Mobile number", "Email","Address") to be of different color.
TextView supports some html tags.
String htmlText = "<font color='#ff0000'>Mobile Number:</font> 123456";
tvMobileNo.setText(Html.fromHtml(htmlText));
Use SpannableString to complete your needs. Here I set the string whose id is restartAllEquipmentTvtextView string index from 3 to 5 to red
restartAllEquipmentTv.text = SpannableString(getString(R.string.restart_and_factory_reset_setting_restart_content)).setSpan(ForegroundColorSpan(Color.RED), 3, 5, Spannable.SPAN_EXCLUSIVE_INCLUSIVE).toString()
Make common funtion for convert your string spannable like this.
//pass param textviewid ,start,end,string
//R.color.Red it's your color you can change it as requirement
fun SpannableStringWithColor(view: TextView,start:Int,end:Int, s: String) {
val wordtoSpan: Spannable =
SpannableString(s)
wordtoSpan.setSpan(
ForegroundColorSpan(ContextCompat.getColor(view.context, R.color.Red)),
start,
end,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
view.text = wordtoSpan
}
In your case you can easy do it like this.
SpannableStringWithColor(tvMobileNo,0,14,"Mobile Number : " + sharedPreferences.getString("mobile_number", ""))
SpannableStringWithColor(tvEmail,0,5,"Email : " + sharedPreferences.getString("email", ""))
SpannableStringWithColor(tvAddress,0,8,"Address : " + sharedPreferences.getString("address", ""))
I need to sort objects with strings that contains number and include language sort
my object includes file, String file name, String isFolder.
and when I sort list of files in a folder
The list:
"file name with default language"
"file name 1"
"file name 10"
"file name 11"
"file name 2"
"file name 20"
How can I sort them like this:
"file name with default language"
"file name 1"
"file name 2"
"file name 10"
"file name 11"
"file name 20"
My code:
final Collator collator = Collator.getInstance(Locale.getDefault());
// listJFiles = ArrayList of my objects called "JFile"
listJFiles.sort((o1, o2) -> collator.compare(o1.isFolder + o1.fileName, o2.isFolder + o2.fileName));
(This one does not help - How to sort by two fields in Java?
Because I need to sort also by language, and I don't know how to combine it with my code which does sort by language)
Firstly, I’d like to write few words to explain the observed behaviour. It is correct and expected. String objects are compared character by character referring to an ordinal number of a character in the ASCII table (http://www.asciitable.com/). In case of two strings have identical start, the longer string is considered bigger. This is why "file name 10” is bigger than “file name 1” and “file name 2” is bigger than “file name 10”.
The behaviour you want to achieve requires to include one more factor to the comparison mechanism: to take numbers into account and compare them using arithmetical rules.
I suppose the case you posted as an example is partial and simple one: there is no number or only one number and it is always placed at the end of a string. Whereas a full problem may imply that a string may contain an arbitrary number of numbers located at any position.
I’ll give you a one possible solution to this problem, which solves the simple case (the one you described):
data class Item(val text: String)
data class SplitItem(val text: String, val number: Int?)
fun SplitItem.toItem() = Item(text + (number?.let { " $it" } ?: ""))
fun main() {
val items = listOf(
Item("file name with default language"),
Item("file name 1"),
Item("file name 10"),
Item("file name 11"),
Item("file name 2"),
Item("file name 20")
).shuffled()
val splitItems = items.map {
val split = it.text.split(' ')
try {
val number = Integer.parseInt(split.last())
SplitItem(
text = split.dropLast(1).joinToString(separator = " "),
number = number
)
} catch (e: NumberFormatException) {
SplitItem(
text = it.text,
number = null
)
}
}
val sortedItems = splitItems.sortedWith { o1, o2 ->
val n = compareValues(o1.number, o2.number)
val t = compareValues(o1.text, o2.text)
compareValues(n, t)
}
sortedItems
.map { it.toItem() }
.forEach { println(it) }
}
Which produces the next output:
Item(text=file name with default language)
Item(text=file name 1)
Item(text=file name 2)
Item(text=file name 10)
Item(text=file name 11)
Item(text=file name 20)
To solve the full problem I’d suggest you to evolve this approach.
Here is my code:
try{
JSONObject jsonObjitem = new JSONObject(jsonString);
JSONArray phrasemaster = jsonObjitem.getJSONArray("phrases");
for(int i = 0; i<phrasemaster.length();i++){
JSONObject scan = phrasemaster.getJSONObject(i);
int id = scan.getInt("id");
if (id == current){
String question = scan.getString("question");
idoutcome1 = scan.getString("idoutcome1");
idoutcome2 = scan.getString("idoutcome2");
idoutcome3 = scan.getString("idoutcome3");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
The user on launch gets random number, when he press the button he is being moved to another fragment where this number is used to pull item from JSON, this number serves as id.
Each item have another three id's. So when I pull my item with this code I also pull 3 id's from that json item. Now what I want is to output the question string from these id's.
{
"phrases": [
{
"id": 1,
"question": "first item",
"idoutcome1": 2,
"idoutcome2": 3,
"idoutcome3": 4
},
{
"id": 2,
"nameofoption": "item 2",
"question": "some question 2",
"idoutcome1": 5,
"idoutcome2": 6,
"idoutcome3": 7
},
{
"id": 3,
"nameofoption": "item 3",
"question": "some question 3",
"idoutcome1": 8,
"idoutcome2": 9,
"idoutcome3": 10
}
]
}
The thing is that I don't understand how I can reach out to these values.
Edit: illustration of what I'm trying to do.
While parsing I take the idoutcome1,2,3 values and output them on my buttons.
However, I want to output the value written in the nameofoption field instead of these numbers. Just like the example, instead of 2 it should show "left".
The problem is that I have this try that searches for id that it got on the previous page and outputs item with corresponding id. How can I implement it within the course of this try that it would go deeper and depending on the idoutcome's of this JSON item display values from the nameofoption field?
I've solved it in a following way, all of the idoutcome's were put in arraylist, then I've reused the same json parsing code to loop through the items with the respective id's and then output them ti the buttons with settext.
That was my first json experience, thanks for the downvotes.
I am working on an android project and came to a halt in my design process. I am a beginning java programmer and also new to the android sdk so please bear with me... On my main screen, it prompts the user to make 6 selections from separate spinner drop down menus. Each of the 6 spinners contain the same StringArray. What I want to do is display the 6 different spinner selections within an EditText field on another screen when a 'submit' button is clicked. I have the submit button listener set up correctly along with a new activity and intent to switch the layout to the output screen. What I don't understand is how to take the spinner(s) and display them into the text fields. I have tried setting up 6 individual SetOnItemSelectedListener methods but unsure if that is allowed. Help, please and thank you!
I sugggest you setup your spinners with a simple ArrayAdapter like so:
String[] selections = new String[] { "Selection 1", "Selection 2", "Selection 3", "Selection 4" };
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(mySpinner1.getContext(), android.R.layout.simple_spinner_item, selections);
myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner1.setAdapter(myAdapter);
Follow the same concept for all 6 spinners. And then when you fetch their values like so:
String value1 = mySpinner1.getSelectedItem().toString();
String value2 = mySpinner2.getSelectedItem().toString();
String value3 = mySpinner2.getSelectedItem().toString();
String value4 = mySpinner2.getSelectedItem().toString();
String value5 = mySpinner2.getSelectedItem().toString();
String value6 = mySpinner2.getSelectedItem().toString();
Now you can concatenate these string as needed and display them in your text view like so:
myTextView.setText(value1 + "," + value2 + "," + value3 + "," + value4 + "," + value5 + "," + value6);
Hope that helps. Have fun.