6

I'm modifying an old Android application. I have a GPS lat and long being stored in a string value and displayed to the user in a non-editable text box when it resolves. I want to add a button which simply takes the value of the string, and copies it to the clipboard.

I've looked at this: How to copy text programmatically in my Android app?

But not sure how to implement it. Any help would be great, I haven't touched much development in this area recently!

Thanks

Edit:

    //Set button (inside oncreate method)
    Button button = (Button)this.findViewById(R.id.buttoncopylocation);
    button.setOnClickListener(this);

//Code added in onClick method
@Override
public void onClick(View arg0) {
    // TODO Auto-generated method stub
    ClipboardManager clipboard = (ClipboardManager)   getSystemService(Context.CLIPBOARD_SERVICE);
    ClipData clip = ClipData.newPlainText("Copied", mycoords);
    clipboard.setPrimaryClip(clip);
}

I'm getting this error: https://i.stack.imgur.com/MqGSA.jpg

Community
  • 1
  • 1
GrumP
  • 1,183
  • 6
  • 19
  • 43

2 Answers2

21

If it is just Text, it is very simple.

ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label","Your Text");
clipboard.setPrimaryClip(clip);

For further Information check out this link

Angelo.Hannes
  • 1,729
  • 1
  • 18
  • 46
  • This worked, thanks (changed slightly though): public void onClick(View arg0) { android.text.ClipboardManager clipboard = (android.text.ClipboardManager)getSystemService(CLIPBOARD_SERVICE); clipboard.setText(mycoords); Toast.makeText(getApplicationContext(), "Text copied to clipboard", Toast.LENGTH_SHORT).show(); – GrumP Oct 08 '12 at 13:14
-1

provide a context before

getSystemService(Context.CLIPBOARD_SERVICE);

like

Context context = ...;
ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
Lamorak
  • 10,957
  • 9
  • 43
  • 57