androidshareclipboardcopy-pasteselectedtext

Clipboard item disappeared after the first use


I have this piece of code implemented for a "share" button, it is supposed to take the already selected text in my app and share it with other app:

shareBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                TextView et = (TextView) mActivity.findViewById(R.id.msg_row);

                int startSelection = et.getSelectionStart();
                int endSelection = et.getSelectionEnd();

                String selectedText = et.getText().toString().substring(startSelection, endSelection);

                if (!selectedText.isEmpty()) {

                    myClipboard = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
                    ClipData clip = ClipData.newPlainText("label", selectedText);
                    myClipboard.setPrimaryClip(clip);


                    ClipData.Item item = myClipboard.getPrimaryClip().getItemAt(0);
                    String pasteData = (String) item.getText();
                    Intent sendIntent = new Intent();
                    sendIntent.setAction(Intent.ACTION_SEND);
                    sendIntent.putExtra(Intent.EXTRA_TEXT, pasteData);
                    sendIntent.setType("text/plain");
                    startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
                }

            }
        });

The problem here is that it works for the first time that I click the button but after that when I select another text and press the button again both selectedText and clipboard are empty. Do anyone know how this behave?


Solution

  • You have to specify your shareBtn.setOnClickListener in onResume() method.