-1

I'm working in Android Studio 3.0.1. I created a EditText in which I write a text now I want when user long press that text it get copied in clipboard.

I used a method here (which is not working)

ClipboardManager mClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); mEditText.setText(mClipboard.getText());

It says Method Invocation 'get text' may produce 'java.lang.NullpoinyerException' I need help what should i do ?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Prateek Awasthi
  • 99
  • 1
  • 2
  • 5

1 Answers1

2

Try this , its will work for you :

 private ClipboardManager myClipboard;
 private ClipData myClip;

 //inside oncreate
 myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);



 mEditText.setOnLongClickListener(new OnLongClickListener() { 
        @Override
        public boolean onLongClick(View v) {
           String text;
            text = mEditText.getText().toString();

            myClip = ClipData.newPlainText("text", text);
            myClipboard.setPrimaryClip(myClip);

            Toast.makeText(getApplicationContext(), "Text Copied", 
               Toast.LENGTH_SHORT).show();

            return true;
        }
    });
Abhishek kumar
  • 4,347
  • 8
  • 29
  • 44