How to show list of string in TextView on Android - android

I want show list of strings in TextView and I get this list from server.
List from json :
"stars": [
{
"name": "Elyes Gabel"
},
{
"name": "Katharine McPhee"
},
{
"name": "Robert Patrick"
}
]
I want show this names such as this sample :
Stars = Elyes Gabel, Katharine McPhee, Robert Patrick
I should setText from this TextView in Adapter.
With below code I can show name :
model.get(position).getStars().get(0).getName();
But just show me Elyes Gabel !!!
I want show me such as this :
Stars = Elyes Gabel, Katharine McPhee, Robert Patrick
How can I it? Please help me

Here is the correct answer you might be after,
Lets just say you have the above JSON and you have converted that in a String array.
So array will look something like below:
String stars[] = {Elyes Gabel, Katharine McPhee, Robert Patrick}
TextView textView = // initialise the textview here or however you do.
StringBuilder builder = new StringBuilder();
for (String star: stars) {
builder.append(star);
builder.append(", ");
}
textView.setText(builder.toString());
You will get the desired output...

You need to loop through all "Star" elements and build the string yourself. You should have something like this:
String concatenatedStarNames = "";
List<Star> stars = model.get(position).getStars(); // I assume the return value is a list of type "Star"!
for (int i = 0; i < stars.size(); i++) {
concatenatedStarNames += stars.get(i).getName();
if (i < stars.size() - 1) concatenatedStarNames += ", ";
}
And then you set the text of the text view to concatenatedStarNames.

You can build it yourself with a StringBuilder, something like:
final Collection<Star> stars = models.get(position).getStars();
final StringBuilder builder = new StringBuilder();
boolean first = true;
for (Star star : stars) {
final String name = star.getName();
if(first) {
first = false;
builder.append(name);
} else {
builder.append(", ").append(name);
}
}
final String allStarNames = builder.toString();

you can just do - (with your same logic of accessing stars)
String strNames;
for (int i=0; i<starsCount; i++){ //starsCount = No of stars in your JSON
strNames += model.get(position).getStars().get(i).getName();
if( i != starsCount-1)
strNames += ", ";
}
textViewVariable.setText(strNames);

Related

Compare 2 textbox values charcter by character

I want to comapare two textbox values words by words and check if the words are same or not. If its not same then it should tell me the percentage of matching words.
For example : I am a good boy(text box1)
Am a god boy (text box 2)
Then the result should be (3/5)*100 as 2 words are not matching that is I and good.
Please tell me how to do this.
here is a code as you want
public class Test {
public static void main(String[] args) {
String str1 = "I am a good boy";
String [] s_str1 = str1.split(" ");
String str2 = "Am a god boy";
String [] s_str2 = str2.split(" ");
int match = 0;
for(int i=0;i<s_str1.length;i++){
for(int j=0;j<s_str2.length;j++){
if(s_str1[i].equalsIgnoreCase(s_str2[j])){
match++;
}
}
}
int result = match*100/s_str1.length; //use length of string which is
your main str
System.out.println(result);
}
}
Try this:
int getCommonWords(String s1, String s2) {
Set<String> set1 = new HashSet<>(Arrays.asList(s1.split(" ")));
Set<String> set2 = new HashSet<>(Arrays.asList(s2.split(" ")));
set1.retainAll(set2);
return set1.size();
}
returns the number of common words between 2 strings. It is case-sensitive.

How to capitalize the first letter in custom textview?

In Custom TextView suppose if first character as a number then next character would be a character. How to find the first character amoung numbers.
If you are using Kotlin you may go for:
Capitalize first word:
var str = "whaever your string is..."
str.capitalize()
// Whaever your string is...
Capitalize each word
var str = "whaever your string is..."
val space = " "
val splitedStr = str.split(space)
str = splitedStr.joinToString (space){
it.capitalize()
}
// Whaever Your String Is...
Try this method by splitting the entire word
String input= "sentence";
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
textview.setText(output);
Output:
Sentence
You're looking for the inputType parameter in the xml layout file for the TextView. Basically in the layout file where you wish to set the TextView in camel case, add the following line:
android:inputType = "textCapWords"
//This would capitalise the first letter in every word.
If you wish to only capitalise the first letter in the TextView, use the following instead.
android:inputType = "textCapSentences"
//This would capitalise the first letter in every sentence.
If you have a textView which has more than one sentence, and you only want to capitalise the first letter in the TextView, I would recommend using code to do this:
String[] words = input.getText().toString().split(" ");
StringBuilder sb = new StringBuilder();
if (words[0].length() > 0) {
sb.append(Character.toUpperCase(words[0].charAt(0)) + words[0].subSequence(1, words[0].length()).toString().toLowerCase());
for (int i = 1; i < words.length; i++) {
sb.append(" ");
sb.append(Character.toUpperCase(words[i].charAt(0)) + words[i].subSequence(1, words[i].length()).toString().toLowerCase());
}
}
String titleCaseValue = sb.toString();
Hope this helps :)
Use this function pass your string and return capitalize string.
public static String wordCapitalize(String words)
{
String str = "";
boolean isCap = false;
for(int i = 0; i < words.length(); i++){
if(isCap){
str += words.toUpperCase().charAt(i);
}else{
if(i==0){
str += words.toUpperCase().charAt(i);
}else {
str += words.toLowerCase().charAt(i);
}
}
if(words.charAt(i)==' '){
Utility.debug(1,TAG,"Value of i : "+i+" : "+words.charAt(i)+" : true");
isCap = true;
}else{
Utility.debug(1,TAG,"Value of i : "+i+" : "+words.charAt(i)+" : false");
isCap = false;
}
}
Utility.debug(1,TAG,"Result : "+str);
return str;
}
String text = textView.getText().toString();
for(Character c : text){
if(c.isLetter){
//First letter found
break;
}

format a string with fill places

I have setup an edittext box and set the maxlength to 10. When I copy the edittext to a string myTitles. I need the myTiles to be 10 chars long and not dependent on what is entered in the edittext box.
myTitles[0] = TitlesEdit.getText().toString();
The edittext was filled with ABCD so I need to add 6 spaces or placeholders after the ABCD. I have seen other post with str_pad and substr without success
myTitles[0] = str_pad(strTest, 0, 10);
myTitles[0] = substr(strTest,0, 10);
Try something like
public static String newString(String str) {
for (int i = str.length(); i <= 10; i++)
str += "*";
return str;
}
This will return a String with * replaced for the empty ones.
So, for eg, if your String is abcde, then on calling newString() as below
myTitles[0] = newString("abcde");
will return abcde***** as the output.
String s = new String("abcde");
for(int i=s.length();i<10;i++){
s = s.concat("-");
}
Then output your string s.
Thank you Lal, I use " " to fill and it worked fine. here is my new code.
String strTest = TitlesEdit.getText().toString();
for (int i = strTest.length(); i <= 10; i++) {
strTest += " ";
}
Log.d("TAG", "String" + strTest);
myTitles[intLinenumber] = strTest;

Reomve special character from Arraylist

I am trying to remove special character from arraylist.
Not getting click how to do this?
I have 3 editfield and filling text after certain conditions
means when 1 is filled then another can be filled. now when i click to save this. this returns an array like [hello,abc,zbz] for fields
private List<String> hashtagData;
hashtagData = new ArrayList<String>();
String status_message = status.getText().toString();
String status_message2 = status2.getText().toString();
String status_message3 = status3.getText().toString();
hashtagData.add(status_message);
hashtagData.add(status_message2);
hashtagData.add(status_message3);
But I am trying to remove "[]".
Thank you if anybody can help.
Here try this:
ArrayList<String> strCol = new ArrayList<String>();
strCol.add("[a,b,c,d,e]");
strCol.add(".a.a.b");
strCol.add("1,2,].3]");
for (String string : strCol) {
System.out.println(removeCharacter(string));
}
private String removeCharacter(String word) {
String[] specialCharacters = { "[", "}" ,"]",",","."};
StringBuilder sb = new StringBuilder(word);
for (int i = 0;i < sb.toString().length() - 1;i++){
for (String specialChar : specialCharacters) {
if (sb.toString().contains(specialChar)) {
int index = sb.indexOf(specialChar);
sb.deleteCharAt(index);
}
}
}
return sb.toString();
}
Create regex which matches with your criteria, then loop through your list.
String myRegex = "[^a-zA-Z0-9]";
int index = 0;
for (String your_string : list)
list.set(index++, s.replaceAll(myRegex, ""));
can use below function to remove special character from string using regular expressions.
using System.Text;
using System.Text.RegularExpressions;
public string RemoveSpecialCharacters(string str)
{
return Regex.Replace(str, "[^a-zA-Z0-9_.]+", "", RegexOptions.Compiled);
}

parse a string and print all database values to a textview

I am trying to colour text for my android app depending on a value entered into the SQLite database. I have set up 3 textviews and have different text colours for all of these.
The code looks like this
String arr[] = data.split("..\n\n");
for(int i = 0; i < arr.length; i++)
{
System.out.println("arr["+i+"] = " + arr[i].trim());
if(arr[i].contains("High Severity"))
{
// String highArr = arr[i];
textView.setVisibility(View.VISIBLE);
textView.setText(highArr+"\n");
textView.setTextColor(Color.RED);
}
else if(arr[i].contains("Low Severity"))
{
textView3.setVisibility(View.VISIBLE);
textView3.setText(arr[i]+"\n");
textView3.setTextColor(Color.GREEN);
}
else if(arr[i].contains("Medium Severity"))
{
textView2.setVisibility(View.VISIBLE);
textView2.setText(arr[i]+"\n");
textView2.setTextColor(Color.rgb(255, 136, 0));
}
}
I have parsed the string which has all the values for my database table, but when I try my for loop it only prints out the latest entered values.
It looks like it could be that your arr[] is only got one entry in it. You should use the debugger to see how many times your loop actually runs and what the actual lenght of the array is.
EDIT:
I just realized that you only have three textviews. Of course the textview is displaying the last one because each time your calling the settext method its reseting the text. There are a few ways to do what you are trying but Im not sure how your app is set up. You should try dynamically creating the textview, setting the text to it, then adding that textview to a linearlayout or relativelayout that you have set up. Or you could do this inside of a listview using a custom implementation of a baseadapter or any of the other adapters depending on your needs.
I would change my code like this:
String arr[] = data.split("..\n\n");
String Hseverity = "", Mseverity = "", Lseverity = "";
for(int i = 0; i < arr.length; i++)
{
System.out.println("arr["+i+"] = " + arr[i].trim());
if(arr[i].contains("High Severity"))
{
// String highArr = arr[i];
textView.setVisibility(View.VISIBLE);
Hseverity += arr[i] +"\n";
textView.setText(Hseverity);//do this to save each High Severity entry
//same for the other severity levels
textView.setTextColor(Color.RED);
}
else if(arr[i].contains("Low Severity"))
{
textView3.setVisibility(View.VISIBLE);
Lseverity += arr[i]+"\n";
textView3.setText(Lseverity);
textView3.setTextColor(Color.GREEN);
}
else if(arr[i].contains("Medium Severity"))
{
textView2.setVisibility(View.VISIBLE);
Mseverity += arr[i] + "\n";
textView2.setText(Mseverity);
textView2.setTextColor(Color.rgb(255, 136, 0));
}
}

Categories

Resources