Android: java.lang.StringIndexOutOfBoundsException: on copy to clipboard selected text on long press event <p>In my app I would like to give copy to clipboard selected text functionality on long press event.foo is a text view foo = (TextView) findViewById(R.id.single_string);. I am using the below code to implement this functionality.</p> <pre><code> protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); activateToolbar(); text = parseSourceCode(text); foo = (TextView) findViewById(R.id.single_string); foo.setTextSize(mRatio + 14); foo.setText(Html.fromHtml(text,imgGetter, null)); foo.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { String stringYouExtracted = foo.getText().toString(); int startIndex = foo.getSelectionStart(); int endIndex = foo.getSelectionEnd(); stringYouExtracted = stringYouExtracted.substring(startIndex, endIndex); if(android.os.Build.VERSION.SDK_INT &lt; android.os.Build.VERSION_CODES.HONEYCOMB) { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setText(stringYouExtracted); } else { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); android.content.ClipData clip = android.content.ClipData.newPlainText("Copied Text", stringYouExtracted); clipboard.setPrimaryClip(clip); } // TODO Auto-generated method stub return false; } }); </code></pre> <p>I am able to set the text but my code is getting crashed when I press long on the screen to copy the selected text. Error I am getting is : </p> <pre><code>java.lang.StringIndexOutOfBoundsException: length=3704; regionStart=-1; regionLength=0 at java.lang.String.startEndAndLength(String.java:504) at java.lang.String.substring(String.java:1333) at java.lang.String.subSequence(String.java:1671) – </code></pre>