setSpan() will only produce one image - android

SpannableStringBuilder authorText = new SpannableStringBuilder("");
ImageSpan is = new ImageSpan(getActivity(), R.drawable.ic_birdhead);
for (Author a : mStory.authors) {
if (!TextUtils.isEmpty(a.authorName)) {
String prefix = "";
if (count == 0) {
prefix = "By: ";
} else if (count > 0 && count < mStory.authors.size()-1) {
prefix = ", ";
} else {
prefix = " and ";
}
authorText.append(prefix + a.authorName + " ");
authorText.setSpan(is, authorText.length()-1, authorText.length(), 0);
//authorText.setSpan(is, authorText.length()-2, authorText.length()-1, 0);
//^ I put a second one there just to check is two will populate
count++;
}
So.. It goes through a for loop anyway, but I put 2 setSpan()'s to see if the last iteration would populate 2 images. It only populates an image at the very end of the string. Maybe there is a certain flag i have to put in for setspan to produce multiple?

Try this:
SpannableStringBuilder authorText = new SpannableStringBuilder("");
ImageSpan is = new ImageSpan(getActivity(), R.drawable.ic_birdhead);
for (Author a : mStory.authors) {
if (!TextUtils.isEmpty(a.authorName)) {
String prefix = "";
if (count == 0) {
prefix = "By: ";
} else if (count > 0 && count < mStory.authors.size()-1) {
prefix = ", ";
} else {
prefix = " and ";
}
authorText.append(prefix + a.authorName + " ");
authorText.setSpan(is, authorText.length()-1, authorText.length(), 0);
is = new ImageSpan(getActivity(), R.drawable.ic_birdhead);
authorText.setSpan(is, authorText.length()-2, authorText.length()-1, 0);
//^ I put a second one there just to check is two will populate
count++;
}

Related

How to set text of multiple codes in one text view

Please have a look at this code and at the bottom is the question. Thanks for your help
int i,fact=1;
String value = edtLCM.getText().toString();
for (i = Integer.parseInt(value); i >= 1; i--) {
fact = fact * i;
if (i > 1) {
String one = i + " x ";
System.out.print(i + " x ");
} else {
System.out.print(i);
String two = String.valueOf(i);
}
}
System.out.println(" = " + fact);
LCMResult.setText("");
I want to set the textview of all the 3 "System.out.println()" in one line. The desired result would be like this(if a user input 4 in the edtLCM): 4x3x2x1 = 24
Use a StringBuilder to put the new strings together instead of using system out.
int i,fact=1;
String value = edtLCM.getText().toString();
StringBuilder sb = new StringBuilder(); // find a better name
for (i = Integer.parseInt(value); i >= 1; i--) {
fact = fact * i;
if (i > 1) {
String one = i + " x ";
// System.out.print(i + " x ");
sb.append(i).append(" x ");
} else {
//System.out.print(i);
sb.append(i);
String two = String.valueOf(i);
}
}
//System.out.println(" = " + fact);
sb.append(" = ").append(fact);
String result = sb.toString(); // will be 4 x 3 x 2 x 1 = 24
LCMResult.setText("");

How to retrieve multi-line text from Edittext?

I want to get a text(Multi-line) from Edittext same as given Screenshot.
I want below output when getText() from Edittext.
Output:
Lorem Ipsum is simply dummy
text of the printing and
typesetting industry. Lorem
Ipsum has been the industry
standard dummy text.
I have tried below solution but, it doesn't work
etMessage.getText().toString().replaceAll("\\n", "<br />")
By default all the EditText widgets in Android are multi-lined. And you can configure the number of lines and the characters types. By setting the input type to multiline do the trick.
<EditText
...
android:inputType="textMultiLine" <!-- Multiline input -->
...
android:lines="8" <!-- Total Lines prior display -->
android:minLines="6" <!-- Minimum lines -->
android:gravity="top|left" <!-- Cursor Position -->
android:maxLines="10" <!-- Maximum Lines -->
android:layout_height="wrap_content" <!-- Height determined by content -->
android:layout_width="match_parent" <!-- Fill entire width -->
android:scrollbars="vertical" <!-- Vertical Scroll Bar -->
/>
After too much searching and waiting for an answer to this question. I have resolved this issue.
Solution:
I have measured each and every line & words for preserve this as Multiline text, you can use below function for that.
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
float density = metrics.density;
String result = fitString(ipText, ipText.getText().toString());
private String fitString(EditText editText, String message) {
Log.i(TAG, "fitString: Default String : " + message);
StringBuilder finalMessage = new StringBuilder();
if (isTooLarge(editText, message)) {
Log.i(TAG, "fitString: isTooLarge 1 : " + true);
List<String> lineList = Arrays.asList(message.split("\n"));
Log.i(TAG, "fitString: stringList" + lineList);
if (lineList != null && lineList.size() > 0) {
for (int i = 0; i < lineList.size(); i++) {
if (lineList.get(i) != null && !lineList.get(i).isEmpty()) {
if (isTooLarge(editText, lineList.get(i))) {
Log.i(TAG, "fitString: isTooLarge 2 : " + lineList.get(i) + " == " + true);
List<String> wordList = Arrays.asList(lineList.get(i).split(" "));
Log.i(TAG, "fitString: wordList" + wordList);
if (wordList != null && wordList.size() > 0) {
Log.i(TAG, "fitString: wordList : " + wordList.size());
StringBuilder temp = new StringBuilder();
String lastWord = "";
for (int j = 0; j < wordList.size(); j++) {
if (wordList.get(j) != null && !wordList.get(j).isEmpty()) {
if (isTooLarge(editText, wordList.get(j))) {
Log.i(TAG, "fitString: isTooLarge 3 : " + wordList.get(j) + " == " + true);
String newString = fitCharacter(editText, wordList.get(j));
Log.i(TAG, "fitString: fitCharacter == " + newString);
if (j == (wordList.size() - 1) && i == (lineList.size() - 1)) {
finalMessage.append(newString);
} else {
finalMessage.append(newString + "\n");
}
} else {
if (j == 0) {
lastWord = wordList.get(j);
} else {
lastWord = " " + wordList.get(j);
}
temp.append(lastWord);
Log.i(TAG, "fitString: temp : " + temp);
Log.i(TAG, "fitString: lastWord : " + lastWord);
if (isTooLarge(editText, temp.toString())) {
temp.setLength(0); // clear String Builder, new StringBuilder()
temp.append(lastWord);
if (j == (wordList.size() - 1) && i != (lineList.size() - 1)) {
Log.i(TAG, "fitString: ###### 1");
finalMessage.append("\n" + lastWord.trim() + "\n");
} else {
Log.i(TAG, "fitString: ###### 2");
finalMessage.append("\n" + lastWord.trim());
}
} else {
if (j == (wordList.size() - 1) && i != (lineList.size() - 1)) {
Log.i(TAG, "fitString: ###### 3");
finalMessage.append(lastWord + "\n");
} else {
Log.i(TAG, "fitString: ###### 4");
finalMessage.append(lastWord);
}
}
Log.i(TAG, "fitString: finalMessage : " + finalMessage);
}
} else {
Log.e(TAG, "fitString: Word is Null or Empty.");
finalMessage.append(" ");
}
}
} else {
Log.e(TAG, "fitString: wordList is Null or Empty.");
}
} else {
Log.i(TAG, "fitString: isTooLarge 2 : " + lineList.get(i) + " == " + false);
if (i == (lineList.size() - 1)) {
finalMessage.append(lineList.get(i));
} else {
finalMessage.append(lineList.get(i) + "\n");
}
}
} else {
Log.e(TAG, "fitString: Line is Null or Empty.");
finalMessage.append(lineList.get(i) + "\n");
}
}
} else {
Log.e(TAG, "fitString: stringList is Null or Empty.");
finalMessage.append("");
}
return finalMessage.toString();
} else {
Log.i(TAG, "fitString: isTooLarge : " + false);
return message;
}
}
public String fitCharacter(EditText editText, String message) {
Log.i(TAG, "fitCharacter2: Default Word : " + message);
StringBuilder finalWord = new StringBuilder();
int startIndex = 0;
int endIndex = 1;
for (; ; ) {
String tempSplitWord = message.substring(startIndex, endIndex);
Log.i(TAG, "fitCharacter2: startIndex : " + startIndex + " endIndex : " + endIndex + " tempSplitWord : " + tempSplitWord);
if (!isTooLarge(editText, tempSplitWord)) { // isTooLarge
if (endIndex < message.length()) {
endIndex = endIndex + 1;
Log.i(TAG, "IF fitCharacter2: endIndex < message.length() " + endIndex + " < " + message.length());
} else {
String result = finalWord.append(tempSplitWord).toString();
Log.i(TAG, "IF RETURN RESULT : " + result);
return result;
}
} else {
endIndex = endIndex - 1;
String splitWord = message.substring(startIndex, endIndex);
Log.i(TAG, "ELSE fitCharacter2: startIndex : " + startIndex + " endIndex : " + endIndex + " splitWord : " + splitWord);
boolean isTooLarge = isTooLarge(editText, splitWord);
if (!isTooLarge) {
finalWord.append(splitWord + "\n");
}
startIndex = endIndex;
endIndex = endIndex + 1;
Log.i(TAG, "ELSE fitCharacter2: startIndex : " + startIndex + " endIndex : " + endIndex);
}
}
}
private boolean isTooLarge(EditText editText, String newText) {
if (editText != null && editText.getPaint() != null) {
float textWidth = editText.getPaint().measureText(newText);
return (textWidth >= (editText.getMeasuredWidth() - (12 * density))); // editText.getMeasuredWidth();
} else {
return false;
}
}
For next comers, I find the accepted answer overcomplicated for the task. Here is a nice extension code in Kotlin that uses Paint.breakText(). That said, it can probably be simplified further...
fun EditText.getMultilineText(): String {
val maxWidth = (width - paddingLeft - paddingRight).toFloat()
val original = text.toString().trim()
val len = original.length
val multiline = mutableListOf<String>()
var p = 0
var count = -1
while (count != 0) {
count = paint.breakText(original, p, len, true, maxWidth, null)
if (p + count < len) {
var tmp = count
while (tmp > 0 && original[p + tmp - 1] != ' ') {
tmp -= 1
}
if (tmp > 0) {
count = tmp
}
}
val tmp = original.substring(p, p + count).trim()
if (tmp.isNotBlank()) {
multiline.add(tmp)
}
p += count
}
return multiline.joinToString("\r\n")
}
did you try this one
message = etMessage.getText().toString().replaceAll("\\n", "<br />")
please see this also How can I preserve line breaks from EditText?

add empty line between group of items in string

I know this is probably one of dumbest questions ever but my brain seems off.
I have this method which makes a string out of vCard:
public static String process(String vCard) {
ArrayList<ArrayList<String>> vCardData = parseData(vCard);
if (vCardData != null) {
StringBuilder readableVCard = new StringBuilder();
for (int i = 0; i < FIELD_COUNT; i++) {
ArrayList<String> vCardDataField = vCardData.get(i);
if (vCardDataField.size() > 0) {
String field = null;
if (i == FORMATTED_NAME) {
field = "Name: ";
} else if (i == PHONE_MOBILE) {
field = "Phone (mobile): ";
} else if (i == PHONE_HOME) {
field = "Phone (home): ";
} else if (i == PHONE_WORK) {
field = "Phone (work): ";
} else if (i == PHONE) {
field = "Phone: ";
} else if (i == FAX_HOME) {
field = "Fax (home): ";
} else if (i == FAX_WORK) {
field = "Fax (work): ";
} else if (i == PAGER) {
field = "Pager: ";
} else if (i == EMAIL_HOME) {
field = "Email (home): ";
} else if (i == EMAIL_WORK) {
field = "Email (work): ";
} else if (i == EMAIL) {
field = "Email: ";
} else if (i == ORGANISATION) {
field = "Company: ";
} else if (i == JOB_TITLE) {
field = "Job title: ";
} else if (i == ADDRESS_HOME) {
field = "Address (home): ";
} else if (i == ADDRESS_WORK) {
field = "Address (work): ";
} else if (i == ADDRESS) {
field = "Address: ";
} else if (i == IM_SKYPE) {
field = "Skype: ";
} else if (i == IM_GOOGLE) {
field = "Google Talk: ";
} else if (i == IM_JABBER) {
field = "Jabber: ";
} else if (i == IM_YAHOO) {
field = "Yahoo: ";
} else if (i == IM_MSN) {
field = "MSN: ";
} else if (i == IM_ICQ) {
field = "ICQ: ";
} else if (i == IM_AIM) {
field = "AIM: ";
} else if (i == TWITTER) {
field = "Twitter: ";
} else if (i == BIRTHDAY) {
field = "Birthday: ";
} else if (i == ANNIVERSARY) {
field = "Anniversary: ";
} else if (i == NOTES) {
field = "Notes: ";
} else if (i == WEBSITE) {
field = "Website: ";
} else {
continue;
}
if (readableVCard.length() != 0) {
readableVCard.append("\n");
}
readableVCard.append(field);
for (int j = 0; j < vCardDataField.size(); j++) {
if (j != 0) {
readableVCard.append("; ");
}
readableVCard.append(vCardDataField.get(j));
}
}
}
if (readableVCard.length() != 0) {
String textVCard = readableVCard.toString();
try {
textVCard = qpDecoder.decode(readableVCard.toString());
} catch (Exception e) {
Logger.e("VCard to UTF-8", e.getMessage());
}
return (textVCard);
}
}
return (null);
}
So my current output is like this:
Name: Marko
Phone(mobile):1312
Phone(fax):441231
Phone(home):543534
Email(home):dddd
Email(work):eeee
Email(other):aaaa
What I want is to add a line break between groups (name/phone/email) so I get something like this:
Name: Marko
Phone(mobile):1312
Phone(fax):441231
Phone(home):543534
Email(home):dddd
Email(work):eeee
Email(other):aaaa
Addressblablabla
.
.
.
IMsblablabla
.
.
.
Can someone help please?
Thanks.
You could iterate the string array, splitting by : and then checking if next item starts with current. If it does, then do nothing, if it doesn't you add the line break to current item and replace it in the array.
Note: splitting with : also separates all phone (xxx) types. To avoid this, you can create enum type, map type to Phone if the string starts with "phone" and use that enum as current type while iterating through the array. If current type if different than next type you add line break.
You can append line separator via
System.getProperty("line.separator");

JSON remove special characters

I want to do the replication between Android sqlite & MS SQL server.That Time i want to take Tables values from Databse.
This is my JSON
{
"Table1":[
{
"BusinessUnit":"MASS",
"ProductCode":"SLD0201",
"Description":"Lou Difan C.Blue 12"3- Commode",
"Description2":"301 0201"
},
{
"BusinessUnit":"MASS",
"ProductCode":"SLN0502",
"Description":"Lou Napoli I"vory- Cistern",
"Description2":"2011 0502"
},
{
"BusinessUnit":"MASS",
"ProductCode":"LDMBL6H",
"Description":"Dortek Taper Bullet Handle 6"5 serr ",
"Description2":"Taper Bullet Ha"
}
],
"Table2":[
{
"chk":6,
"currentchk":1
}
]
}
In Here JSON Description column value contain "(double quotation) .If we check http://jsonformatter.curiousconcept.com/ , it show error.Its a Invalid JSON.
WCF service I have converted DataSet to JSON. Some table column contain special charters.
I converted like this :
public String ConverTableToJson(DataSet dsDownloadJson,int currentSplit)
{
StringBuilder Sb = new StringBuilder();
String result = "";
int start = 0;
int end =500;
int chk = 0;
int currentChk = currentSplit;
if (dsDownloadJson.Tables.Count > 0)
{
Sb.Append("{");
foreach (DataTable dt in dsDownloadJson.Tables)
{
DataTable dtDownloadJson = dt;
string[] StrDc = new string[dtDownloadJson.Columns.Count];
string HeadStr = string.Empty;
double total = dtDownloadJson.Rows.Count;
Console.WriteLine("--1--" + dtDownloadJson.Rows.Count);
if (dtDownloadJson.Rows.Count < 500)
{
end = dtDownloadJson.Rows.Count;
}
if (chk == 0)
{
if (dtDownloadJson.Rows.Count > 500)
{
if ((dtDownloadJson.Rows.Count / 500) == 0)
{
chk = dtDownloadJson.Rows.Count / 500;
}
else
{
chk = dtDownloadJson.Rows.Count / 500 + 1;
}
}
else
{
chk = 1;
}
currentChk = 1;
}
else
{
currentChk = currentChk + 1;
start = currentChk * 500;
end = start + 500;
currentChk = chk;
}
Sb.Append("\"" + dtDownloadJson.TableName + "1\" : [");
if (dtDownloadJson.Rows.Count > 0)
{
for (int i = 0; i < dtDownloadJson.Columns.Count; i++)
{
StrDc[i] = dtDownloadJson.Columns[i].Caption;
HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";
}
if (HeadStr.Length > 0)
{
HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);
Console.WriteLine("--2--" + start);
Console.WriteLine("--3--" + end);
for (int i = start; i < end; i++)
{
string TempStr = HeadStr;
Sb.Append("{");
for (int j = 0; j < dtDownloadJson.Columns.Count; j++)
{
TempStr = TempStr.Replace(dtDownloadJson.Columns[j] + j.ToString() + "¾", dtDownloadJson.Rows[i][j].ToString());
TempStr = TempStr.Replace(""", '\"');
}
Sb.Append(TempStr + "},");
}
Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
}
}
else
{
}
Sb.Append("],");
if (chk > 1)
{
Sb.Append("\"Table2\": [{\"chk\": " + chk + ", \"currentchk\": " + currentChk + " }]");
}
else
{
Sb.Append("\"Table2\": [{\"chk\": " + chk + ", \"currentchk\": " + currentChk + " }]");
}
}
// Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
Sb.Append("}");
return Sb.ToString();
}
else
{
return "0";
}
}
My problem is removing special charters OR How to allow special characters.?
Please help me anybody...
You shouldn't use a StringBuilder to convert an object to a JSON string. Use the JsonConverter class in JayRock JSON library and it takes care of Serialising/Deserialising Json for you (including escaping)
try to use inbuilt json serialization
public static string Serialize<T>(T obj)
{
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new
System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, obj);
string retVal = Encoding.Default.GetString(ms.ToArray());
ms.Dispose();
return retVal;
}

Android,SAX parser Problem while reading Html Tags

i want to parse this text with Sax Parser,the problem is due to Html tags in content tag string buffer is not going to read Html tags can any one suggest me how to do it with Sax Parser,or refer me any of the links that parse Html data with SAX
If you can edit the text you provided, simply use CDATA:
<content><![CDATA[Your stuff here with all the <em>HTML</em> tags you can think of.]]></content>
Then SAX Parser's toString() will return a string like this: Your stuff here with all the <em>HTML</em> tags you can think of.
You can use this method to put CDATA in data (Parameter DATA: Actual Data; TAG: Name of XML tag where CDATA needs to be put.)
public static final String putCDATA(String data, String tag) {
if(data == null || data.length() <= 0 || tag == null || tag.length() <= 0) {
return null;
}
String newData = "";
while(true) {
int firstIndex = data.indexOf("<" + tag + ">");
firstIndex = firstIndex + new String("<" + tag + ">").length() - 1;
int lastIndex = data.indexOf("</" + tag + ">");
if(firstIndex == -1 || lastIndex == -1) {
break;
}
String tagValue = data.substring(firstIndex + 1, lastIndex);
tagValue = "<![CDATA[" + tagValue + "]]>";
newData += data.substring(0,firstIndex + 1);
newData += tagValue;
newData += data.substring(lastIndex, lastIndex + new String("<" + tag + ">").length() + 1);
data = data.substring(lastIndex + new String("<" + tag + ">").length() + 1, data.length());
}
newData += data;
System.out.print("FORMATED: " + "\n" + newData);
return newData;
}
An HTML file is not XML conformant.

Categories

Resources