Unicode Encoding and Decoding - android

I want an android code or algorithum which will accept a Marathi text as input and convert the marathi text into unicode code. Also reconvert the unicode into marathi text.
i tried some code like:-
string marathi = "मी लाइक आहे";
UnicodeEncoding ue = new UnicodeEncoding(true,true);
string s1 = BitConverter.ToString(ue.GetBytes(marathi.ToCharArray())).Replace("-", "");
but this code is not working in case of android.
Help me as soon as possible. Thanks in advance.

Convert a string to unicode -
public String toUnicode(String text) {
String txt = "";
for (int i = 0; i < text.length(); i++) {
Log.d("Unicode", (int) text.charAt(i));
txt = txt + "\\" + text.charAt(i);
}
return txt;
}
To convert unicode into string, use -
public String toString(String uni){
String tt = "";
String[] parts = uni.split("\\");
for(String x:parts){
x = "\\" + x;
char un = x.toCharArray()[0];
tt = text + un;
}
return tt;
}

Related

I am trying to display text and multiple emoji from unicode in tetxview dynamically

I have try already to convert unicode to emoji but at a time only one emoji set. i want display in textview multiple emoji .
my problem is i want to display text with multiple emoji on textview dynamically.
for example : String str = "Happy" + unicode + "Birthday" + unicode + "ComingSoon" + unicode + "Dear" + unicode + unicode;
according to above string i want display multiple emoji with text on textview.
private static String escapeNonAscii(String str) {
StringBuilder mStr = new StringBuilder();
for(int i=0; i<str.length(); i++) {
int cp = Character.codePointAt(str, i);
int charCount = Character.charCount(cp);
if (charCount > 1) {
i += charCount - 1; // 2.
if (i >= str.length()) {
throw new IllegalArgumentException("truncated unexpectedly");
}
}
if (cp < 128) {
mStr .appendCodePoint(cp);
} else {
mStr .append(String.format("\\u%x", cp));
}
}
return mStr.toString();
with above code noot display emojis...

How to convert emoji unicode in android

In anroid emoji convert to unicode time alwasy get output U+5c but we give emoji string "\uD83D\uDE21" this method it's working
String a = emojiconEditText.getText().toString().trim();
String text = new String(
StringEscapeUtils.escapeJava(a).getBytes(),
StandardCharsets.UTF_8
);
int codepoint = text.codePointAt(0);
String yourUnicode = "U+"+Integer.toHexString(codepoint);
You can encode/decode emojis to the following unicode UTF-8, UTF-16 and U+<hex> using the below:
try {
//I am assuming you are getting unicode from an inputbox
String emoji = emojiconEditText.getText().toString().trim();
//I am also assuming you are getting emoji in hexadecimal form `U+<hexdigits>`
String unicodeHexEmoji = "U+";
StringBuilder sb = new StringBuilder();
//Firstly you want to encode emojis to unicode types by converting to byte array
byte[] utf8Bytes = emoji.getBytes("UTF-8"); // "\\uf0\\u9f\\u98\\u80"
byte[] utf16Bytes = emoji.getBytes("UTF-16"); // "\\ud83d\\ude00"
//convert emoji to hex
for (byte b : utf16Bytes ) {
sb.append(String.format("%02x", b));
}
//we are converting our current emoji to hex just for the purpose of this example
unicodeHexEmoji += sb; //yields "U+feffd83dde21";
byte[] utfHexBytes = getByteFromHex(unicodeHexEmoji.replace("U+","")); // "\\ud83d\\ude00"
//NB: we removed "U+" because its only a prefix denoting that the string is a <hex>
//Decoding our unicodes back to emoji string
String emojiUTF_8 = new String(utf8Bytes,"UTF-8");
String emojiUTF_16 = new String(utf16Bytes,"UTF-16");
String emojiUTF_hex = new String(utfHexBytes,"UTF-16");
Log.d("Tag", "emojiUTF_8 : "+ emojiUTF_8);
Log.d("Tag", "emojiUTF_16 : "+ emojiUTF_16)
Log.d("Tag", "emojiUTF_hex : "+ emojiUTF_hex)
//output
//emojiUTF-8 : 😀
//emojiUTF-16 : 😀
//emojiUTF-hex : 😡
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
...
public byte[] getByteFromHex(String hexString){
//To convert hex string to byte array, you need to first get the length
//of the given string and include it while creating a new byte array.
byte[] val = new byte[hexString.length() / 2];
for (int i = 0; i < val.length; i++) {
int index = i * 2;
int j = Integer.parseInt(hexString.substring(index, index + 2), 16);
val[i] = (byte) j;
}
return val;
}

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;
}

TextView misbehaving when appending two strings

I am working on writing a simple temperature conversion program, to familiarize myself with Android programming. The user types in a number to an EditText, and it converts it from Fahrenheit to Celsius, or vice versa, then puts the answer in a TextView. I want to append a Unicode Celsius/Fahrenheit symbol to the end of the answer before displaying it. When I don't have it appending the symbol, it works fine and displays the correct number, but when it is trying to append the symbol to the end, the output displays all wrong, with a long string of numbers at the end (and still no Unicode symbol).
Here's my code:
This is the converter utility class:
public class ConverterUtil {
//Convert to celsius
public static String convertFahrenheitToCelsius(float fahrenheit) {
float temperature = (fahrenheit - 32) * 5 / 9;
DecimalFormat df = new DecimalFormat("#.#");
return df.format(temperature) + R.string.celsius_symbol;
}
//Convert to fahrenheit
public static String convertCelsiustoFahrenheit(float celsius) {
float temperature = (celsius * 9) / 5 + 32; //Append the unicode Celsius symbol (\u2103), then return
DecimalFormat df = new DecimalFormat("#.#");a
return df.format(temperature) + R.string.fahrenheit_symbol; //Append the unicode Fahrenheit symbol (\u2109), then return
}
}
And this is where I call it:
public void calculateTemperature(){
RadioButton celsiusButton = (RadioButton) findViewById(R.id.button2);
TextView output = (TextView) findViewById(R.id.output);
if (text.getText().length() == 0) {
output.setText("");
return;
}
float inputValue = Float.parseFloat(text.getText().toString());
String outputText = celsiusButton.isChecked() ? ConverterUtil.convertFahrenheitToCelsius(inputValue) : ConverterUtil.convertCelsiustoFahrenheit(inputValue);
output.setText(outputText);
}
If I take out the part where I append the Unicode symbols, it looks like this:
And if I put that back in, I get this:
How do I fix that?
Looks like the resourceID of your fahrenheit_symbol & celsius_symbol are getting appended to your text than the actual character.
Try this,
public class ConverterUtil {
//Convert to celsius
public static String convertFahrenheitToCelsius(Context context, float fahrenheit) {
float temperature = (fahrenheit - 32) * 5 / 9;
DecimalFormat df = new DecimalFormat("#.#");
return df.format(temperature) + context.getResources().getString(R.string.celsius_symbol);
}
//Convert to fahrenheit
public static String convertCelsiustoFahrenheit(Context context, float celsius) {
float temperature = (celsius * 9) / 5 + 32; //Append the unicode Celsius symbol (\u2103), then return
DecimalFormat df = new DecimalFormat("#.#");a
return df.format(temperature) + context.getResources().getString(R.string.fahrenheit_symbol); //Append the unicode Fahrenheit symbol (\u2109), then return
}
}
Change where you call it like this,
public void calculateTemperature(){
RadioButton celsiusButton = (RadioButton) findViewById(R.id.button2);
TextView output = (TextView) findViewById(R.id.output);
if (text.getText().length() == 0) {
output.setText("");
return;
}
float inputValue = Float.parseFloat(text.getText().toString());
String outputText = celsiusButton.isChecked() ? ConverterUtil.convertFahrenheitToCelsius(YourActivity.this, inputValue) : ConverterUtil.convertCelsiustoFahrenheit(YourActivity.this, inputValue);
output.setText(outputText);
}
Change
return df.format(temperature) + R.string.fahrenheit_symbol;
return df.format(temperature) + R.string.celsius_symbol;
to
return df.format(temperature) + getString(R.string.fahrenheit_symbol);
return df.format(temperature) + getString(R.string.celsius_symbol);
R.string.fahrenheit_symbol and R.string.celsius_symbol are both integers. You will need to look up the relevant string resource using Context.getResources().getString().
You will need to pass a Context (such as the calling Activity) to your ConverterUtil.

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;

Categories

Resources