cnfw
cnfw

Reputation: 800

Issues SubStrings and outofboundsexception error

I have some code to display the first ten characters of a string on a button. but I get the out of boiunds exception error when the string is less than 10 characters or null.

I thought a simple IF statement would fix it, but it doesn't seem to have. Could someone point out my problem? Thanks

I checked with the android developers reference, and it doesn't state a way to get around this

Button item1 = (Button) findViewById(R.id.buttontext1);
String ellipsed = PrefConnector.readString(this, PrefConnector.ONE, null);

if(ellipsed.length() < 1) ellipsed = "Touch to edit";
if(ellipsed.length() > 10) ellipsed = ellipsed.substring(0, 10) + "...";

item1.setText(ellipsed);

Upvotes: 1

Views: 66

Answers (4)

Jay
Jay

Reputation: 27492

If you're getting a null-pointer exception, then there must be cases where ellipsed is null.

Even if ellipsed is never null, your code above has a problem: If ellipsed.length()<10, you change it to "Touch to edit", but then you check for length>10, and "Touch to edit".length()>10, so short strings would always end up "Touch to e..."

In any case, I think what you want to say is

if (ellipsed==null || ellipsed.length()==0)
  ellipsed="Touch to edit";
else if (ellipsed.length()>10)
  ellipsed=ellipsed.substring(0,10)+"...";

Upvotes: 1

Robin Chander
Robin Chander

Reputation: 7425

if(ellipsed != null && ellipsed.length() >10)
    ellipsed = ellipsed.substring(0, 10) + "...";
else 
     ellipsed = "Touch to edit";

Upvotes: 0

Thomas Kaliakos
Thomas Kaliakos

Reputation: 3304

Basically you take the substring of the first 10 characters and you wonder why you get an exception if you try to get the 10 first characters of a string with length less than 10? From the oracle docs:

Throws: IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

Upvotes: 0

David M
David M

Reputation: 2541

why don't you try...

    if(ellipsed.length() < 1)
        ellipsed = "Touch to edit";
    else 
        ellipsed = ellipsed.substring(1, ellipsed.length()) + "...";

Upvotes: 0

Related Questions