Clipboard

Course- Android >

Android offers clipboard framework for copying and pasting various types of data. Data can be text, images, binary stream data, or other complex data types

To provide copying and pasting framework, Android Clipboard Manager and ClipData and ClipData.Item's Library provides. To use the clipboard framework, you have to insert the data into the clip object, and then that object will be inserted into the system wide clipboard.

To use the clipboard, you must instantiate the object of the clipboard manager by calling the GetSystemService () method. Its syntax is given below -


ClipboardManager myClipboard;
myClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);

Copying data

The next thing to do is to call ClipData class related type data method to instantiate clip data objects. In the case of text data, the new plain text method will be called. After that you have to set that data as a clips of clipboard manager objects. Its syntax is given below−


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

The ClipData object can take these three form and following functions are used to create those forms.

Sr.No ClipData Form & Method
1 Text

newPlainText(label, text)

Returns a ClipData object whose single ClipData.Item object contains a text string.

2 URI

newUri(resolver, label, URI)

Returns a ClipData object whose single ClipData.Item object contains a URI.

3 Intent

newIntent(label, intent)

Returns a ClipData object whose single ClipData.Item object contains an Intent.

Pasting data

To paste the data, we'll first get the clip by calling the GetPrimaryClip () method. And with that click, we will get the items in the clip data.itam object. And we will get data from the object. Its syntax is given below -


ClipData abc = myClipboard.getPrimaryClip();
ClipData.Item item = abc.getItemAt(0);
String text = item.getText().toString();

Apart from the these methods , there are other methods provided by the ClipboardManager class for managing clipboard framework. These methods are listed below −

Sr.No Method & description
1 getPrimaryClip()

This method just returns the current primary clip on the clipboard

2 getPrimaryClipDescription()

This method returns a description of the current primary clip on the clipboard but not a copy of its data.

3 hasPrimaryClip()

This method returns true if there is currently a primary clip on the clipboard

4 setPrimaryClip(ClipData clip)

This method sets the current primary clip on the clipboard

5 setText(CharSequence text)

This method can be directly used to copy text into the clipboard

6 getText()

This method can be directly used to get the copied text from the clipboard

Example

This is an example demonstrating the use of the clipboard manager class, it creates the original copy paste application that allows you to copy the text and paste it through the clipboard.

To experiment with this example, you can run it on a real device or in an emulator.

Steps Description
1 You will use Android studio IDE to create an Android application and under a package com.example.sairamkrishna.myapplication. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2 Modify src/MainActivity.java file to add necessary code.
3 Modify the res/layout/activity_main to add respective XML components
4 Run the application and choose a running android device and install the application on it and verify the results

Following is the content of the modified main activity file src/MainActivity.java.


package com.example.sairamkrishna.myapplication;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;

import android.os.BatteryManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Set;


public class MainActivity extends ActionBarActivity {
   EditText ed1,ed2;
   Button b1,b2;
   
   private ClipboardManager myClipboard;
   private ClipData myClip;.
   
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      ed1=(EditText)findViewById(R.id.editText);
      ed2=(EditText)findViewById(R.id.editText2);
      
      b1=(Button)findViewById(R.id.button);
      b2=(Button)findViewById(R.id.button2);
      
      myClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
      
      b1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            String text;
            text = ed1.getText().toString();
            
            myClip = ClipData.newPlainText("text", text);
            myClipboard.setPrimaryClip(myClip);
            
            Toast.makeText(getApplicationContext(), "Text Copied",Toast.LENGTH_SHORT).show();
         }
      });
      
      b2.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            ClipData abc = myClipboard.getPrimaryClip();
            ClipData.Item item = abc.getItemAt(0);
            
            String text = item.getText().toString();
            ed2.setText(text);
            
            Toast.makeText(getApplicationContext(), "Text Pasted",Toast.LENGTH_SHORT).show();
         }
      });
   }
   
   @Override
   protected void onDestroy() {
      super.onDestroy();
   }
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.menu_main, menu);
      return true;
   }
   
   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      
      int id = item.getItemId();
      
      //noinspection SimplifiableIfStatement
      if (id == R.id.action_settings) {
         return true;
      }
      return super.onOptionsItemSelected(item);
   }
}

Following is the modified content of the xml res/layout/activity_main.xml.


 xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
   android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" 
   tools:context=".MainActivity">
   
    android:text="Example" android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/textview"
      android:textSize="35dp"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true" />
      
   
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point"
      android:id="@+id/textView"
      android:layout_below="@+id/textview"
      android:layout_centerHorizontal="true"
      android:textColor="#ff7aff24"
      android:textSize="35dp" />
      
   
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:src="@drawable/abc"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true" />
      
   
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText"
      android:layout_alignParentRight="true"
      android:layout_alignParentEnd="true"
      android:hint="Copy text"
      android:layout_below="@+id/imageView"
      android:layout_alignLeft="@+id/imageView"
      android:layout_alignStart="@+id/imageView" />
      
   
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText2"
      android:layout_alignLeft="@+id/editText"
      android:layout_alignStart="@+id/editText"
      android:hint="paste text"
      android:layout_below="@+id/editText"
      android:layout_alignRight="@+id/editText"
      android:layout_alignEnd="@+id/editText" />
      
   
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Copy text"
      android:id="@+id/button"
      android:layout_below="@+id/editText2"
      android:layout_alignLeft="@+id/editText2"
      android:layout_alignStart="@+id/editText2" />
      
   
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Paste text"
      android:id="@+id/button2"
      android:layout_below="@+id/editText2"
      android:layout_alignRight="@+id/editText2"
      android:layout_alignEnd="@+id/editText2" />
      

Following is the content of the res/values/string.xml.


    name="app_name">My Application
    name="hello_world">Hello world!
    name="action_settings">Settings

Following is the content of AndroidManifest.xml file.


xml version="1.0" encoding="utf-8"?>
 xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.clipboard"
   android:versionCode="1"
   android:versionName="1.0" >

   
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      
         android:name="com.example.sairamkrishna.myapplication.MainActivity"
         android:label="@string/app_name" >
         
         
             android:name="android.intent.action.MAIN" />
             android:name="android.intent.category.LAUNCHER" />
         
    

Let's try to run an application that we have just modified. I think you had made your AVD while setting up the environment, to run the app from Android Studio, open an activity file from your project and click the Run icon from the toolbar. The Android Studio Installer will display an image