Search code examples
javaandroidtwitter4jindexoutofboundsexceptionindexof

indexOf("@") method in Java


Why does this always return -1? Does this have anything to do with '@' being the annotation symbol?

What can I do to search for the first occurrence of a substring starting with '@'?

 UserMentionEntity[] userMentionEntities = status.getUserMentionEntities();
    for (UserMentionEntity ume : userMentionEntities) {
        final String mention = ume.getText();
        int mentionStart = text.indexOf("@" + mention);
        int mentionEnd = mentionStart + mention.length();
        ss.setSpan(new ForegroundColorSpan(Color.parseColor(COLOR)), mentionStart, mentionEnd + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

Apparently, mentionStart is -1. I am using twitter4j library.

Sample:

text: RT @Cornerstone_TMC Thank you @ukgdos at sa lahat ng nag-abang kanina kay @yengpluggedin! #SeenZoned @academyofrocksg… http://t.co/rsLqjlZJgg
mention: ukgdos

Solution

  • I fixed the problem with my app.

        UserMentionEntity[] userMentionEntities = status.getUserMentionEntities();
        for (UserMentionEntity ume : userMentionEntities) {
            final String mention = ume.getText().toLowerCase();
            int mentionStart = text.toLowerCase().indexOf("@" + mention);
            int mentionEnd = mentionStart + mention.length();
            ss.setSpan(new ForegroundColorSpan(Color.parseColor(COLOR)), mentionStart, mentionEnd + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    

    I noticed that Twitter allows you to change cases in the mentions.

    @yengPLUGGEDin can be shown as @yengpluggedin so that ume.getText() in the code there returns the proper screenname while text contains the tweet text as it is.

    I am not quite sure why it also failed on my sample input there. Maybe it didn't but failed on the next before the print was executed.