Sunday 25 September 2016

Html tags in TextView - Android

The best approach to use CData sections for the string in strings.xml file to get a actual display of the html content to the TextView the below code snippet will give you the fair idea.

//in string.xml file
<string name="welcome_text"><![CDATA[<b>Welcome,</b> to the forthetyroprogrammers blog Logged in as:]]> %1$s.</string>

Now in Java code you can assign like this,

//and in Java code
String welcomStr=String.format(getString(R.string.welcome_text),username);

CData section in string text keeps the html tag data intact even after formatting text using String.format method. So, Html.fromHtml(str) works fine and you’ll see the bold text in Welcome message.

Welcome, to your favorite music app store. Logged in as: <username>

Java - String, StringBuilder & String Buffer

Below is the main difference between these three most commonly used classes.

  • String class objects are immutable whereas StringBuffer and StringBuilder objects are mutable.
  • StringBuffer is synchronized while StringBuilder is not synchronized.
  • Concatenation operator "+" is internal implemented using either StringBuffer or StringBuilder.
Criteria to choose among StringStringBuffer and StringBuilder
  • If the Object value is not going to change use String Class because a String object is immutable.
  • If the Object value can change and will only be accessed from a single thread, use a StringBuilder because StringBuilder is not synchronized one.
  • In case the Object value can change, and will be modified by multiple threads, use a StringBuffer because StringBuffer is synchronized.
The main idea is that String is immutable. So when you are trying to modify it, new object created. StringBuffer and StringBuilder are mutable. And the difference is the first one is thread-safe.
The common approach to using StringBuilder is to parse something when you iteratively create a String object in a NON thread safe environment.
For example, you have a numbers array [1, 2, 3]. To create object "String1String2String3" you can use a StringBuilder
StringBuilder builder = new StringBuilder();
foreach(Integer num : array) {
It's better than just using String string = string + ("String" + num);. AFAIK, compiler will optimize using string concatenation in the loop to StringBuilder, but better to use it manually.
StringBuffer is used when you have shared states, that are modified by concurrent threads.
Courtesy & Source: