Basically I have a paragraph like this
Difference between the lower energy level of conduction band $ec and upper energy level of valence band $ev is called energy band gap.
Now I'm trying to parse through the text, to get those $ prefixed symbols, and replace them with small PNG images that are mathematical formulas. They are just single/dbl letter constant symbols like Ev and Ec. They are in my assets folder. Basically this is the code
public SpannableStringBuilder getConstants(String desc, String constpath){
SpannableStringBuilder builder = new SpannableStringBuilder();
if (desc.contains("$")){
Matcher matcher = Pattern.compile("\\$\\w+").matcher(desc);
int lastEnding=0;
while (matcher.find()) {
String constName = matcher.group();
constName = constName.substring(1,constName.length());
int startIndex = matcher.start();
int endIndex = matcher.end();
String brokenDescFirstPart = desc.substring(lastEnding, startIndex - 1);
lastEnding = endIndex+1;
builder.append(brokenDescFirstPart).append(" ");
try{
InputStream imgStream = getContext().getAssets().open(constpath+constName+".png");
Drawable dconstImg = Drawable.createFromStream(imgStream, null);
imgStream.close();
builder.setSpan(new ImageSpan(dconstImg,ImageSpan.ALIGN_BOTTOM), builder.length() -3, builder.length() -1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
builder.append(" ");
}catch (Exception e){
builder.append(" ");
}
}
String brokenDescLastPart = desc.substring(lastEnding, desc.length() - 1);
builder.append(brokenDescLastPart);
}else{
builder = SpannableStringBuilder.valueOf(desc);
}
return builder;
}
Quick summary of code is that desc is the string I want to parse. I then use regex to get the $word pattern and use the matcher.match method to iterate through the text. I use some int variables to keep track of start and endpoints in between those symbols to carefully reconstruct the original string with images embedded. Now the code
try{
InputStream imgStream = getContext().getAssets().open(constpath+constName+".png");
Drawable dconstImg = Drawable.createFromStream(imgStream, null);
imgStream.close();
builder.setSpan(new ImageSpan(dconstImg,ImageSpan.ALIGN_BOTTOM), builder.length() -3, builder.length() -1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
builder.append(" ");
}catch (Exception e){
builder.append(" ");
}
is the crux of my question. I got it from some other question on the issue. They said it works. But it doesn't in mine. I've set breakpoints all over the code and gone through line by line execution. No errors nothing whatsoever. Still doesn't work.
The text loads with extra spaces in the textview that I've intentionally used to identify the places where it must have injected the images. My TextView is the Small Text View widget in Android Studio.