4

I am trying to get the number of characters the emojis in my EditText have used up. The reason for this is my EditText has a maxLength of 25 chars.

I have looked at other examples of getting the count such as:

titleView.getText().toString()).length()

This counts each emoji as 2 characters so my input stops at 12 emojis = 24 characters.

The issue I am having is I think this count is off, my server is expecting to receive a string of no more than 25 chars so it must be truncating some of these emojis.

When I then go to retrieve this data in my app, it causes it to crash. My web service does not know how to handle it. It gets into the onSuccess callback, but when I try to query the response it says its a null object.

If each emoji is uniformly 2 chars long, why is this not working for me?

if they are not uniform, how to I get the real count?

Gooner
  • 387
  • 2
  • 23

2 Answers2

2

I had the same problem.I fixed it like below

Step 1: import library

implementation group: 'com.ibm.icu', name: 'icu4j', version: '65.1'

Step 2: create method

 fun String.getGraphemeLength(): Int {
    val it: BreakIterator = BreakIterator.getCharacterInstance()
    it.setText(this)
    var count = 0
    while (it.next() != BreakIterator.DONE) {
        count++
    }
    return count
}

Step 3: Note . You must import

import com.ibm.icu.text.BreakIterator

Step 4: How to use

val text = "insert your emoji"
val count = text.getGraphemeLength()
Log.e("COUNT " + count+"")
Nguyễn Trung Hiếu
  • 2,004
  • 1
  • 10
  • 22
0

My approach to this was to import this library:

implementation 'com.vdurmont:emoji-java:4.0.0'

Then I created a utility method to get the length of a string counting emojis as 1:

fun getLengthWithEmoji(s: String): Int{
        var emojiCount = EmojiParser.extractEmojis(s).size;
        var noEmojiString = EmojiParser.removeAllEmojis(s);
        var emojiAndStringCount = emojiCount + noEmojiString.length;
        return emojiAndStringCount;
}

Generally to 'Get emoji count in string' I would use this line:

var emojiCount = EmojiParser.extractEmojis(s).size;

This accounts for all the latest emojis (depending on how up to date your library it). Check for some of the forks that others have made on the library as they in some cases have added missing emoji patterns.

jimbob
  • 3,288
  • 11
  • 45
  • 70