How to decode unicode to get Emoji/Smiley in android Edittext? - android

When i fetch the smiley from edittext then there is need to make its Unicode to send it on server. I got Unicode by using below code :
public static String escapeJavaString(String st)
{
StringBuilder builder = new StringBuilder();
try {
for (int i = 0; i < st.length(); i++) {
char c = st.charAt(i);
if(!Character.isLetterOrDigit(c) && !Character.isSpaceChar(c)&& !Character.isWhitespace(c) ){
String unicode = String.valueOf(c);
int code = (int)c;
if(!(code >= 0 && code <= 255)){
unicode = "\\\\u"+Integer.toHexString(c);
}
builder.append(unicode);
}
else{
builder.append(c);
}
}
Log.i("Unicode Block", builder.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return builder.toString();
}
I got the output as '\ud83d\ude12' , then send it to server. On receiving side, i got the same from server but when placed it in EditText then it'll shows Unicode in text form same as above output, Doesn't get emoji. How it will decode it to show emoji instead of Unicode in EditText ??
Anybody, have an idea??

I got solution of my above question. call following method as message.setText(unescapeJava(your_string)); to Decode or unescape unicode to smiley in Edittext
public static String unescapeJava(String escaped) {
if (escaped.indexOf("\\u") == -1)
return escaped;
String processed = "";
int position = escaped.indexOf("\\u");
while (position != -1) {
if (position != 0)
processed += escaped.substring(0, position);
String token = escaped.substring(position + 2, position + 6);
escaped = escaped.substring(position + 6);
processed += (char) Integer.parseInt(token, 16);
position = escaped.indexOf("\\u");
}
processed += escaped;
return processed;
}

Look at Html.fromHtml OR See example
Try this
editText.setText(Html.fromHtml("\ud83d\ude12"));

Related

in email mutipart message body (with attachment) is comming as plain text instead html format

I am writing an email client android app. In it, I am using JavaMail. While reading emails from server everything is coming properly except for a few mails which have attachments. In those cases the email body is coming as plain text instead of HTML format.
My code is as follows:
String str; //=bodyPart.toString();//(bodyPart.getContent());
if (bodyPart instanceof Part) {
if (bodyPart.getContent() instanceof String) {
str = bodyPart.getContent().toString();
}
else {
MimeMultipart mimeMultipart = (MimeMultipart) bodyPart.getContent();
str = getTextFromMimeMultipart(mimeMultipart);
}
}
else
str = bodyPart.getContent().toString();
//
//*****************************
//
private String getTextFromMimeMultipart(MimeMultipart mimeMultipart) throws MessagingException, IOException {
String result = "";
int count = mimeMultipart.getCount();
for (int i = 0; i < count; i++) {
BodyPart bodyPart = mimeMultipart.getBodyPart(i);
if (bodyPart.isMimeType("text/plain")) {
result = result + "\n" + bodyPart.getContent();
break; // without break same text appears twice in my tests
}
else if (bodyPart.isMimeType("text/html")) {
String html = (String) bodyPart.getContent();
result = result + "\n" + Jsoup.parse(html).text();//html;// + org.Jsoup.parse(html).text();
}
else if (bodyPart.getContent() instanceof MimeMultipart) {
result = result + getTextFromMimeMultipart((MimeMultipart)bodyPart.getContent());
}
}
return result;
}

Emoji in profile avatar

I'm in need to setting profile name as profile picture, For this i'll take the first character of word
String getImageText(String name) {
StringBuilder avatarText = new StringBuilder();
try {
if (!TextUtils.isEmpty(name)) {
String[] words = name.split("\\s");//splits the string based on whitespace
for (int count = 0; (count <= 1 && count < words.length); count++) { // taking first letter of first two words
avatarText.append(words[count].charAt(0)); // appending first letter of the string
}
}
} catch (Exception exception) {
Log.e(TAG, "Exception while getting image text : " + exception.getMessage(), exception);
}
return avatarText.toString();
}
This works pretty good when text contains only words/numbers/special characters.But while setting the emoji as profile name it is not working good.
It displayed like
this
Try this to remove all emojis:
Your edited code:
String removeEmoji(text){
String regex = "[^\\p{L}\\p{N}\\p{P}\\p{Z}]";
String result = text.replaceAll(regex, "");
return result;
}
String getImageText(String inputName) {
StringBuilder avatarText = new StringBuilder();
String name = "";
try {
if (!TextUtils.isEmpty(inputName)) {
name = removeEmoji(inputName);
String[] words = name.split("\\s");//splits the string based on whitespace
for (int count = 0; (count <= 1 && count < words.length); count++) { // taking first letter of first two words
avatarText.append(words[count].charAt(0)); // appending first letter of the string
}
}
} catch (Exception exception) {
Log.e(TAG, "Exception while getting image text : " + exception.getMessage(), exception);
}
return avatarText.toString();
}
Checkout this for more information

What is this type of MD5?

guys i have a code who hash string and object but when i hash the code online on any website encrypt its come out different from the other one in the code i want to know what is makes the other MD5 code different from this online
the md5 code:
public static String md5(String paramString){
if (Utils.isNullOrEmpty(paramString)) {
return "";
}
try
{
Object localObject1 = MessageDigest.getInstance("MD5");
if (localObject1 != null) {
((MessageDigest)localObject1).update(paramString.getBytes());
}
paramString = ((MessageDigest)localObject1).digest();
localObject1 = new StringBuilder();
int j = paramString.length;
int i = 0;
while (i < j)
{
String str = Integer.toHexString(paramString[i] & 0xFF);
if (str.length() == 1) {
((StringBuilder)localObject1).append('0');
}
((StringBuilder)localObject1).append(str);
i += 1;
}
}
catch (NoSuchAlgorithmException localNoSuchAlgorithmException)
{
Object localObject2;
for (;;)
{
localNoSuchAlgorithmException.printStackTrace();
localObject2 = null;
}
return ((StringBuilder)localObject2).toString();
}
he take two value
public static String generateChkSum(HashMap<String, Object> paramHashMap) {
paramHashMap = a(paramHashMap);
Log.d("CheckSum Before Concat :::::::::: ", paramHashMap);
paramHashMap = md5(paramHashMap);
paramHashMap = md5(paramHashMap + "^" + AppConstants.a);
Log.d("CheckSum After Concat :::::::::: ", paramHashMap);
return paramHashMap;
the logcat:
01-27 02:25:08.440 2369-3661/com.test.app D/CheckSum Before Concat ::::::::::: kinghema^1784e7fe94d4750df3af902489489b77
01-27 02:25:08.440 2369-3661/com.test.app D/CheckSum After Concat  ::::::::::: 781973a6c9d36f18d9f02f80dc2e5d6e
and the result is :781973a6c9d36f18d9f02f80dc2e5d6e
but if we take the 2 value and hash them online normally:
39cec39f604f5a4380bae1f00c7404b6
so my question is what is this type of hashing he use? whats is the difference between this code and the online code what is the method he use?

How to do fractions in an Android editText. Inputfilter? Custom IME?

I'm trying to write code for an editText which can accept imperial values { ie. 1 , 3/4 , 1 1/3}. So far, with a lot of help from StackOverflow, I have it just about nailed. But there are three things missing.
android:inputType="number" or numberSigned, numberDecimal, phone etc
none of these display the / key I need to enter data and the QWERTY keyboard is too cumbersome for a single keypress. I'm amazed there isn't a keyboard for this, what do the yanks do? Can I override and replace a single key on the stock keyboard, do I have to implement my own keyboard for this seemingly simple task?
I am also struggling with the logic which prevents the first character being a space or /. I can allow one of each in a given string no problem, I just can't prevent it being the first key. Additionally, when you enter a value - like "1 5/9" - if you backspace to the /, the flags are not reset, so you are prohibited from entering another /.
Code for the InputFilter is as follows:
imperial_filter = new InputFilter() {
boolean canEnterSpace = true, canEnterSlash = true;
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (imperial_editText.getText().toString().equals("")) {
canEnterSpace = true;
canEnterSlash = true;
}
StringBuilder builder = new StringBuilder();
for (int i = start; i < end; i++) {
char currentChar = source.charAt(i);
if (Character.isDigit(currentChar) || (Character.isWhitespace(currentChar) && canEnterSpace && canEnterSlash) || (currentChar == '/' && canEnterSlash)) {
builder.append(currentChar);
if (Character.isWhitespace(currentChar)) canEnterSpace = false;
if (currentChar == '/') canEnterSlash = false;
}
}
return builder.toString();
}
};
And this one is a little more complex, slightly adapted from code already on StackOverflow:
public float testImperialString(String testString) {
boolean goodInput = true, goodInputSpace = true, containsSpace = false;
float result = 0, whole = 0;
String fractions = "";
if (testString.contains(" ")) {
containsSpace = true;
String pieces[] = testString.split(" ");
try {
whole = Float.parseFloat(pieces[0]);
fractions = pieces[1];
} catch (Exception e) {
goodInputSpace = false;
}
} else fractions = testString;
if (fractions.contains("/")) {
//possible division
String pieces[] = fractions.split("/");
if (pieces.length != 2) {
goodInput = false;
} else {
try {
float numerator = Float.parseFloat(pieces[0]);
float denominator = Float.parseFloat(pieces[1]);
result = numerator / denominator;
} catch (Exception e) {
goodInput = false;
}
}
}
if (!testString.contains(" ") && !(result > 0)) {
try {
result = Float.parseFloat(testString);
} catch (Exception e) {
goodInput = false;
}
}
Log.d(TAG, "Contains Space = " + containsSpace + " Good Input = " + goodInput + " Good InputSpace = " + goodInputSpace);
return whole + result;
}
I run that result through a method which converts imperial measurements into a metric equivalent, that I can perform maths functions with.
TL:DR
I need a number keyboard with a / symbol
I need to prevent a space or / as the first letter of an input
I need to re-allow a space or / input, if a previous occurrence in a string was deleted.

Compare contents of two files line by line

public class MainActivity extends Activity {
FileOutputStream fos;
FileInputStream fOne, fTwo;
ArrayList<String> arr1 = new ArrayList<String>();
ArrayList<String> arr2 = new ArrayList<String>();
ArrayList<String> words = new ArrayList<String>();
ArrayList<String> wordsTwo = new ArrayList<String>();
int count = 0;
int countTwo = 0;
int countThree = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button fileOne = (Button)findViewById(R.id.file1);
Button fileTwo = (Button)findViewById(R.id.file2);
Button compare = (Button)findViewById(R.id.compare);
arr1.add("1");
arr1.add("2");
arr1.add("3");
arr1.add("4");
//arr1.add("3");
arr2.add("1");
arr2.add("2");
fileOne.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try
{
fos = openFileOutput("File1", Context.MODE_PRIVATE);
for(int temp = 0; temp< arr1.size(); temp++)
{
fos.write((arr1.get(temp).getBytes()) );
fos.write(System.getProperty("line.separator").getBytes());
}
fos.close();
fos.flush();
}
catch(Exception e)
{
}
}
});
fileTwo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try
{
fos = openFileOutput("File2", Context.MODE_PRIVATE);
for(int temp = 0; temp< arr2.size(); temp++)
{
fos.write((arr2.get(temp).getBytes()) );
fos.write(System.getProperty("line.separator").getBytes());
}
fos.close();
fos.flush();
}
catch(Exception e)
{
}
}
});
compare.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try
{
fOne = openFileInput("File1");
fTwo = openFileInput("File2");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Scanner scanFile = new Scanner(new DataInputStream(fOne));
Scanner scanFileT = new Scanner(new DataInputStream(fTwo));
words = new ArrayList<String>();
wordsTwo = new ArrayList<String>();
while (scanFile.hasNextLine())
{
if(scanFile.nextLine()!=null)
{
count++;
}
while(scanFileT.hasNextLine())
{
if(scanFileT.nextLine()!=null)
{
countTwo++;
}
}
}
try
{
fOne.close();
fTwo.close();
scanFile.close();
scanFileT.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(getBaseContext(), "One : " + count, 1000).show();
Toast.makeText(getBaseContext(), "Two : " + countTwo, 1000).show();
Toast.makeText(getBaseContext(), "Three : " + countThree, 1000).show();
count = 0 ;
countTwo = 0;
countThree = 0;
}
});
}
}
Above is the code to write and read the file. What I did here, write two files and read the contents..Now I have to compare contents of files line by line. What needs to be done?
Try following code. This will give you desired output. I took files from asset directory. So you need to replace that line of code if you are taking files from other directory.
private void compareFiles() throws Exception {
String s1 = "";
String s2 = "", s3 = "", s4 = "";
String y = "", z = "";
// Reading the contents of the files
BufferedReader br = new BufferedReader(new InputStreamReader(
getAssets().open("first.txt")));
BufferedReader br1 = new BufferedReader(new InputStreamReader(
getAssets().open("second.txt")));
while ((z = br1.readLine()) != null) {
s3 += z;
s3 += System.getProperty("line.separator");
}
while ((y = br.readLine()) != null) {
s1 += y;
s1 += System.getProperty("line.separator");
}
// String tokenizing
StringTokenizer st = new StringTokenizer(s1);
String[] a = new String[10000];
for (int l = 0; l < 10000; l++) {
a[l] = "";
}
int i = 0;
while (st.hasMoreTokens()) {
s2 = st.nextToken();
a[i] = s2;
i++;
}
StringTokenizer st1 = new StringTokenizer(s3);
String[] b = new String[10000];
for (int k = 0; k < 10000; k++) {
b[k] = "";
}
int j = 0;
while (st1.hasMoreTokens()) {
s4 = st1.nextToken();
b[j] = s4;
j++;
}
// comparing the contents of the files and printing the differences, if
// any.
int x = 0;
for (int m = 0; m < a.length; m++) {
if (a[m].equals(b[m])) {
} else {
x++;
Log.d("Home", a[m] + " -- " + b[m]);
}
}
Log.d("Home", "No. of differences : " + x);
if (x > 0) {
Log.d("Home", "Files are not equal");
} else {
Log.d("Home", "Files are equal. No difference found");
}
}
Input File 1
Hi
Hello
Chintan
Rathod
Input File 2
Hi
HellO
Chintan
RathoD
Output
08-26 12:07:58.219: DEBUG/Home(2350): Hello3. -- HellO3.
08-26 12:07:58.219: DEBUG/Home(2350): Rathod -- RathoD
08-26 12:07:58.229: DEBUG/Home(2350): No. of differences : 2
08-26 12:07:58.229: DEBUG/Home(2350): Files are not equal
Edit
To get Difference between two files
Use StringUtils library which is provide by Apache and check this Documentation for more about that library.
And modify following lines of code.
int x = 0;
for (int m = 0; m < a.length; m++) {
if (a[m].equals(b[m])) {
} else {
x++;
Log.d("Home", a[m] + " -- " + b[m]);
//to print difference
if (a[m].length() < b[m].length())
Log.d("Home", "" + StringUtils.difference(a[m], b[m]));
else
Log.d("Home", "" + StringUtils.difference(b[m], a[m]));
}
}
Output
08-26 17:51:26.949: DEBUG/Home(17900): 12 -- 123
08-26 17:51:26.949: DEBUG/Home(17900): Difference String : 3
08-26 17:51:26.949: DEBUG/Home(17900): No. of differences : 1
08-26 17:51:26.949: DEBUG/Home(17900): Files are not equal
Try using java.util.Scanner
while (sc1.hasNext() && sc2.hasNext()) {
String str1 = sc1.next();
String str2 = sc2.next();
if (!str1.equals(str2))
System.out.println(str1 + " != " + str2);
}
Change your while loop to the following:
while (scanFile.hasNextLine() && scanFileT.hasNextLine())
{
if(scanFileT.nextLine().equals(scanFile.nextLine()))
{
// The lines are equal.
} else {
// The lines are not equal.
}
}
if(scanFile.hasNextLine() || scanFileT.hasNextLine())
{
// If more lines remain in one of the files, they are not equal.
} else {
// If no content remains in both files, they are equal.
}
Depending on the size of your file, I would recommend some optimisation like checking the file sizes before you go through them line by line.
The overall logic reads as follows; if both have another line, compare it to see if it is equal. If they don't have another line, check if one of them has lines remaining, if so, they are not equal.
Update
After clarifying the objective of the comparison in chat, see the comments to this question, I have come to the conclusion that another comparison would be more effective and, as a matter of fact, correct. The comparison algorithm above works great if comparing the structure of text but not if comparing a data vector which may or may not be sorted. After some discussion, we came to the conclusion that data needs to be sorted or the comparison will blow the complexity to at least O(n^2)which could be done in O(2n) if the data is sorted. Here the algorithm's skeleton:
if(! scanGroupFriends.hasNextLine())
{
//simple sanity check to see if we need to compare at all. In this case, add all friends.
} else {
String nextFriend = scanGroupFriends.nextLine();
while(scanAllFriends.hasNextLine())
{
if(scanAllFriends.nextLine().equals(nextFriend))
{
// Friend already figures, do not add him and advance the list of group friends.
if(scanGroupFriends.hasNextLine())
{
nextFriend = scanGroupFriends.nextLine();
} else {
// There are no more friends in the group, add all remaining friends to list to show.
break; // Terminate the `while` loop.
}
}
}
}
However, I personally think it is bad to make to many assumptions. What I would suggest is that the friends be saved in a Set, a TreeSet for example. Then, serialize the object rather than manually writing it to file. Sets are neat because they hold several interesting objects. For example, you could easily use the following code to remove all friends in a group from the set of all friends:
allFriends.removeAll(groupFriends);
However, be aware that this removes it from the set completely so you should make a copy beforehand.

Categories

Resources