Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android using indexOf

I have this, tweet.title is a string that is equals to I love burgers.

        CharSequence i = tweet.title.indexOf(Integer.valueOf("I"));

        SpannableString WordtoSpan = new SpannableString(i);        
        WordtoSpan.setSpan(new ForegroundColorSpan(Color.RED), 0, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        holder.txtTitle.setText(WordtoSpan);

Now I get this error from it Type mismatch: cannot convert from int to CharSequence

I wanna find the I in the string.

like image 915
John Jared Avatar asked Mar 25 '26 11:03

John Jared


2 Answers

String.indexOf returns an int not a CharSequence. Also, you can't get the index of the I using Integer.valueOf().

    int i = tweet.title.indexOf("I");

If you want to just get the "I" back do this:

    int i = tweet.title.indexOf("I");
    String s = tweet.title.substring(i, i + 1);

Edited: I fixed a couple of bugs in this code.

like image 144
mttdbrd Avatar answered Mar 27 '26 00:03

mttdbrd


Code (tested and works)

CharSequence i = tweet.title.indexOf(Integer.valueOf("I"));

should be

int index = tweet.title.indexOf("I"); // find int position of "I"

// set to be the String of where "I" is to plus 1 of that position
CharSequence i = tweet.title.substring(index, index + 1);

// Alternative to substring, you could use charAt, which returns a char
CharSequence i = Character.toString(tweet.title.charAt(index));

Explanation

indexOf(String) returns the int position of where that String is.
You gave Integer.valueOf("I") as the String to indexOf(String).

Integer.valueOf(String) converts a String to an Integer. Why would you give the indexOf(String) an Integer and why would you try to convert "I" to an Integer?

What you meant to do was this: CharSequence i = tweet.title.indexOf("I"); but that is also wrong because it will return an int (position in the String), hence the mismatch error.

You need to find the position of "I" in the tweet.title, so that's tweet.title.indexOf("I"). Then set the CharSequence to be tweet.title at that position up until that position +1 (so that you get just the one character I).

like image 45
Michael Yaworski Avatar answered Mar 27 '26 01:03

Michael Yaworski