Good day.

I want to make sure that by clicking on the button the contents of the TextView copied to the buffer.

  Button copyButton = (Button)findViewById(R.id.copyButton); TextView generatedCode = (TextView) findViewById(R.id.generatedCode); String stringYouExtracted = generatedCode.getText().toString(); int startIndex = generatedCode.getSelectionStart(); int endIndex = generatedCode.getSelectionEnd(); stringYouExtracted = (stringYouExtracted).substring(startIndex, endIndex); if(android.os.Build.VERSION.SDK_INT < 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); } 

This code does not work correctly because of the line:

 stringYouExtracted = (stringYouExtracted).substring(startIndex, endIndex); 

throws a ClassCastException . Thank you in advance.

  • why do you take the variable name in brackets? (stringYouExtracted) .substring (startIndex, endIndex); - Ksenia
  • In general, it is unlikely that the problem was precisely because of the given line. Please post a stack trace. - Ksenia
  • I used this example on stackoverflow.com/questions/6624763/… - Maksims
  • In the example there are no brackets, why did you decide that you need them? ClassCastExeption says that you have a type casting error, and you are trying to cast the type to these brackets when you just need to take a substring from a string. - pavlofff
  • This is a consequence of pasting several examples into one. The brackets removed, but now the application does not start and throws FATAL EXCEPTION into the log: main java.lang.RuntimeException: Unable to start activity ComponentInfo {company.generator / company.generator.MainActivity}: java.lang.StringIndexOutOfBoundsException: length = 0; regionStart = -1; regionLength = 0 - Maksims

1 answer 1

What method is this code of yours in? Most likely, in the onCreate method, which starts to run when the application starts. Therefore, in your TextView with id equal to generatedCode , there can be no selected text, so your startIndex and endIndex both -1. Because of this, you get an error. Transfer the code to another method (for example, to the button click handling method) or check the startIndex and endIndex for -1, for example:

 ... int startIndex = generatedCode.getSelectionStart(); int endIndex = generatedCode.getSelectionEnd(); if (startIndex != -1) { stringYouExtracted = stringYouExtracted.substring(startIndex, endIndex); } ... 

And better do both.